o
    wi_                    @  s`  d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
 ddlmZmZmZmZ ddlmZ ddlmZ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*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z9 ddl:m;Z; ddl<m=Z=m>Z> ddl?m@Z@mAZA ddlBmCZD ddlEmFZF ddlGmHZHmIZImJZJ ddlKmLZL ddlMmNZN erdd lOmPZPmQZQmRZRmSZSmTZTmUZUmVZV dd!lWmXZX dd"lYmZZZ d#d$l[m\Z\m]Z]m^Z^m_Z_m`Z` d#d%lambZb d#d&lcmdZd eeefZgG d'd( d(ZhG d)d* d*ZCd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).
    )annotationsN)Iterator)
HTTPStatus)TYPE_CHECKINGAnyCallableLiteral)ValidationError)Unpackoverload)Clientgql)
RetryError)envutil)tracked)one)nameof)public)normalize_exceptions)RETRY_TIMEDELTA)
RegistriesRegistry)"fetch_org_entity_from_organization)
ServiceApi)PathType!fetch_org_from_settings_or_entity
gql_compatparse_org_from_registry_path)
UsageError)wandb_internal_pb2)
Deprecated)wandb_loginwandb_setup)resolve_org_entity_nameserver_supports)Api)LAUNCH_DEFAULT_PROJECT)retryrunidwbauth)warn_and_record_deprecation)GraphQLSession)
ActionType
Automation	EventTypeIntegrationNewAutomationSlackIntegrationWebhookIntegration)WriteAutomationsKwargsArtifact   )ArtifactCollectionArtifactCollections	ArtifactsArtifactTypeArtifactTypesTeamUserc                   @  sV   e Zd ZdZedZdddZdd ZdddZe	dd Z
e	dd ZdddZdS )RetryingClientzdA GraphQL client that retries requests on failure.

    <!-- lazydoc-ignore-class: internal -->
    a$  
        query ServerInfo{
            serverInfo {
                cliVersionInfo
                latestLocalVersionInfo {
                    outOfDate
                    latestVersionString
                    versionOnThisInstanceString
                }
            }
        }
        clientr   c                 C  s   d | _ || _d | _d S N)_server_info_client_execute_decorated)selfrB    rH   I/home/ubuntu/.local/lib/python3.10/site-packages/wandb/apis/public/api.py__init__h   s   
zRetryingClient.__init__c                 O  s$   | j d u r
|  | _ | j |i |S rC   )rF   _build_execute_wrapper)rG   argskwargsrH   rH   rI   executem   s   

zRetryingClient.executereturnCallable[..., Any]c                   s2   dd l  tjttjt jfd fdd}|S )Nr   )retry_timedeltacheck_retry_fnretryable_exceptionsc                    s^   z
j j| i |W S   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.)rE   rN   
exceptionsReadTimeout	transportdefault_timeoutwandbtermwarn)rL   rM   rT   requestsrG   rH   rI   _wrappedu   s   
z7RetryingClient._build_execute_wrapper.<locals>._wrapped)r]   r(   	retriabler   r   no_retry_authr   RequestException)rG   r^   rH   r\   rI   rK   r   s   z%RetryingClient._build_execute_wrapperc                 C  s   t | jjjddd S )Nz/graphql /)r   app_urlrE   rX   urlreplacerG   rH   rH   rI   rd      s   zRetryingClient.app_urlc                 C  s$   | j d u r| | jd| _ | j S )N
serverInfo)rD   rN   
INFO_QUERYgetrg   rH   rH   rI   server_info   s   
zRetryingClient.server_infomin_versionstrboolc                 C  s&   ddl m} |||| jd d kS )Nr   )parsecliVersionInfomax_cli_version)packaging.versionro   rk   )rG   rl   ro   rH   rH   rI   version_supported   s   z RetryingClient.version_supportedN)rB   r   )rO   rP   )rl   rm   rO   rn   )__name__
__module____qualname____doc__r   ri   rJ   rN   rK   propertyrd   rk   rs   rH   rH   rH   rI   rA   S   s    



rA   c                   @  s  e Zd ZdZedZ			ddddZdddZdddZ	dddZ
dddddddZ				ddd'd(Zdd0d1Z				ddd6d7Zddd=d>Zdd?d@ZeddBdCZeddDdEZeddFdGZeddHdIZdJdK ZddMdNZdOdP ZddRdSZeddUdVZeddXdVZddZdVZ	[d dd_d`ZdddbdcZ	edddgdhZdddldmZddndoZ ddrdsZ!d	dudvZ"			w	e	x	xd
dd~dZ#e$dddZ%		ddddZ&dddZ'e$dddZ(e$ddddZ)e$ddddZ*e$	eddddZ+e$dddZ,e$dddZ-e$	e	ddddZ.e$	8ddddZ/e$ddddZ0e$ddddZ1e$dddZ2e$ddddZ3e$dddZ4e5			ddddZ6e5dd ddZ7e5			dd!ddZ8e5	ddedd"ddZ9e5	ddedd#ddĄZ:e5ddedŜd$ddȄZ;dddɜd%ddτZ<d&dd҄Z=e5ddӜd'ddքZ>e5	dddedלd(ddڄZ?e$e5d8dۜd)ddZ@e$e5d8dd*ddZAe$e5d+ddZBdS (,  r&   zmUsed for querying the W&B server.

    Examples:
    ```python
    import wandb

    wandb.Api()
    ```
       N	overridesdict[str, Any] | NonerT   
int | Noneapi_key
str | NonerO   Nonec              	   C  s  t   | _| j|pi  | jd d| jd< |r'tj| jd |d| _n
| j| jd d| _| jjj	}t
| jtjrK| jj| _tj| j|d nd| _| j }d| _i | _i | _i | _i | _d| _|durk|n| j| _| jdp~ttjdd	}tt| jd
dd| j|d||dd| _ t!| j | _"t#j$j%j&t' d| _(| )  t*+ j, }||_-| jpd|_t.|d| _/dS )a  Initialize the API.

        Args:
            overrides: You can set `base_url` if you are
                using a W&B server other than `https://api.wandb.ai`. You can also
                set defaults for `entity`, `project`, and `run`.
            timeout: HTTP timeout in seconds for API requests. If not
                specified, the default timeout will be used.
            api_key: API key to use for authentication. If not provided,
                the API key from the current environment or configuration will be used.
                Prompts for an API key if none is provided
                or configured in the environment.
        base_urlrc   )hostr}   )r   )keyr   N_proxiesWANDB__PROXIES{}true)z
User-AgentzUse-Admin-PrivilegesTz
{}/graphql)headersuse_jsonrT   authre   proxies)rX   )pidrb   )settings)0InternalApir   updaterstripr*   
AuthApiKey_auth
_load_authr   re   
isinstancer}   r"   _verify_loginas_requests_auth_viewer	_projects_runs_sweeps_reports_default_entity_HTTP_TIMEOUT_timeoutrj   jsonloadsosenvironr   r,   
user_agentformat_base_clientrA   rE   rZ   	analyticssentrySentrygetpid_sentry_configure_sentryr#   	singleton
model_copyr   r   _service_api)rG   rz   rT   r}   r   session_authr   r   rH   rH   rI   rJ      s^   



zApi.__init__r   rm   wbauth.Authc                 C  s*   t j|ddt jjd}|std|S )z.Load or prompt for authentication credentials.zwandb.Api()T)r   source
no_offlineinput_timeoutz:No authentication configured. Use `wandb login` to log in.)r*   authenticate_sessionr#   r   r   login_timeoutr   )rG   r   r   rH   rH   rI   r      s   
zApi._load_authc              	   C  sf   t  sd S dd l}z| j}W n t|jfy   Y d S w |r"|jnd }| j}| jj	||dd d S )Nr   )entityemail)tags)
r   error_reporting_enabledr]   viewer
ValueErrorra   r   default_entityr   configure_scope)rG   r]   r   r   r   rH   rH   rI   r     s   

zApi._configure_sentrynamer   c                 C  s:   ddl m}m} |||d}| jt|d| i dS )zCreate a new project.

        Args:
            name: The name of the new project.
            entity: The entity of the new project.
        r   )CREATE_PROJECT_GQLUpsertModelInput)r   entity_nameinputN)wandb.apis._generatedr   r   rB   rN   r   
model_dump)rG   r   r   r   r   	gql_inputrH   rH   rI   create_project  s   zApi.create_projectrun_idprojectr   r   r   
public.Runc                C  s"   |du r| j }tjj| |||dS )a  Create a new run.

        Args:
            run_id: The ID to assign to the run. If not specified, W&B
                creates a random ID.
            project: The project where to log the run to. If no project is specified,
                log the run to a project called "Uncategorized".
            entity: The entity that owns the project. If no entity is
                specified, log the run to the default entity.

        Returns:
            The newly created `Run`.
        Nr   )r   r   Runcreate)rG   r   r   r   rH   rH   rI   
create_run*  s   zApi.create_runtypepublic.RunQueueResourceTypeprioritization_mode(public.RunQueuePrioritizationMode | Noneconfigdict | Nonetemplate_variables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 in W&B Launch.

        Args:
            name: Name of the queue to create
            type: Type of resource to be used for the queue. One of
                "local-container", "local-process", "kubernetes","sagemaker",
                or "gcp-vertex".
            entity: Name of the entity to create the queue. If `None`, use
                the configured or default entity.
            prioritization_mode: Version of prioritization to use.
                Either "V0" or `None`.
            config: Default resource configuration to be used for the queue.
                Use handlebars (eg. `{{var}}`) to specify template variables.
            template_variables: A dictionary of template variable schemas to
                use with the config.

        Returns:
            The newly created `RunQueue`.

        Raises:
            `ValueError` if any of the parameters are invalid
            `wandb.Error` on wandb API errors
        Nr   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r   r   default_settingsrQ   resource_argssuccessz(failed to create default resource configdefaultResourceConfigIDPROJECTfailed to create run queue)rB   r   r   r   _access_default_resource_config_id_default_resource_config)r   r   r   lenupperr   r'   r   r   r   r   dumpscreate_default_resource_configrZ   Errorcreate_run_queuer   RunQueuerB   )rG   r   r   r   r   r   r   apiconfig_jsoncreate_config_result	config_idcreate_queue_resultrH   rH   rI   r   B  sj   "	

zApi.create_run_queuedisplay_name	spec_typeLiteral['vega2']accessLiteral['private', 'public']spec
str | dictc           
      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"},
            )
            ```
        )rQ   )r   r   r   r   r   r   Nchartzfailed to create custom chartid)r   r   r   create_custom_chartrj   rZ   r   )
rG   r   r   r   r   r   r   backend_accessr   resultrH   rH   rI   r     s   @

zApi.create_custom_chartresource_configdict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 )aj  Upsert a run queue in W&B Launch.

        Args:
            name: Name of the queue to create
            entity: Optional name of the entity to create the queue. If `None`,
                use the configured or default entity.
            resource_config: Optional default resource configuration to be used
                for the queue. Use handlebars (eg. `{{var}}`) to specify
                template variables.
            resource_type: Type of resource to be used for the queue. One of
                "local-container", "local-process", "kubernetes", "sagemaker",
                or "gcp-vertex".
            template_variables: A dictionary of template variable schemas to
                be used with the config.
            external_links: Optional dictionary of external links to be used
                with the queue.
            prioritization_mode: 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
        Nr   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 ))labelre   rH   ).0r   valuerH   rH   rI   
<listcomp>J  s    z(Api.upsert_run_queue.<locals>.<listcomp>r   )r   r  r   r   r   configSchemaValidationErrorszresource config validation: )rB   r   r   )r   r   r   r   r   r   r'   r   r   r   itemsupsert_run_queuerZ   r   rj   r[   r   r   rB   )rG   r   r  r  r   r   r  r   r   upsert_run_queue_resultschema_errorserrorrH   rH   rI   r    sh   $		
	
zApi.upsert_run_queueFr   adminbool | Noner@   c                 C     ddl m} || ||S )zCreate a new user.

        Args:
            email: The email address of the user.
            admin: Set user as a global instance administrator.

        Returns:
            A `User` object.
        r7   r?   )usersr@   r   )rG   r   r  r@   rH   rH   rI   create_useri  s   
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   r   r   mark_syncedrd   viewverbosesync_tensorboardrc   )
wandb.syncr  r)   generate_idr   rj   r   rB   rd   addstartis_donepollrunjoin)rG   root_dirr   r   r   r  sm_rH   rH   rI   r  w  s(   


zApi.sync_tensorboardrA   c                 C  s   | j S )zReturns the client object.)rE   rg   rH   rH   rI   rB     s   z
Api.clientc                 C  s   d tjS )zReturns W&B public user agent.zW&B Public Client {})r   rZ   __version__rg   rH   rH   rI   r     s   zApi.user_agentc                 C  sT   ddl m}m} | jdu r'| jt|}||}|j }r'|j	 }r'|| _| jS )zReturns the default W&B entity.r   )GET_DEFAULT_ENTITY_GQLGetDefaultEntityN)
r   r(  r)  r   rE   rN   r   model_validater   r   )rG   r(  r)  datar   r   r   rH   rH   rI   r     s   

zApi.default_entityc                 C  s|   ddl m}m} ddlm} | jdu r;| jt|}|	|}|j
 }du r-d}t||| j| | _| jj| _| jS )zReturns the viewer object.

        Raises:
            ValueError: If viewer data is not able to be fetched from W&B.
            requests.RequestException: If an error occurs while making the graphql request.
        r   )GET_VIEWER_GQL	GetViewerr7   r?   NzHUnable to fetch user data from W&B, please verify your API key is valid.)r   r,  r-  r  r@   r   rE   rN   r   r*  r   r   r   r   r   )rG   r,  r-  r@   r+  r   r   msgrH   rH   rI   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   rg   rH   rH   rI   flush  s   
z	Api.flushpathc              	   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.

        Args:
            path: 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.

        Examples:
        In the proceeding code snippets "project", "team", "run_id", "sweep_id",
        and "report_name" are placeholders for the project, team, run ID,
        sweep ID, and the name of a specific report, respectively.

        ```python
        import wandb

        api = wandb.Api()

        project = api.from_path("project")
        team_project = api.from_path("team/project")
        run = api.from_path("team/project/runs/run_id")
        sweep = api.from_path("team/project/sweeps/sweep_id")
        report = api.from_path("team/project/reports/report_name")
        ```
        / rc   r7      r         r"  sweepreportz---z>Invalid report path, should be team/project/reports/Name--XXXX r   )displayNamer   r   zSInvalid path, should be TEAM/PROJECT/TYPE/ID where TYPE is runs, sweeps, or reports)stripsplitr   r   r"  
startswithr5  rZ   r   r   
BetaReportrB   urllibro   unquoterf   )rG   r0  partsr   r   rH   rH   rI   	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  r   Nrc   r7   )r   r   r<  r   )rG   r0  r   r   rA  rH   rH   rI   _parse_project_path  s   zApi._parse_project_pathtuple[str, str, str]c                 C  s  | j d p| j}| j d }d}|}|dd}|dd}|d}|d}t|dkrB|d	 d
krB|d |d |d }}}n[t|dkrW|d |d |d	 }}}nFt|d	kr}d|d v rs|d }|d jddd\}}n*|d |d }}n t|dkr|d rd|d v r|d jddd\}}n|d }|o| }|o| }|o| }|std|d|std|d|std||||fS )a:  Parse url, filepath, or docker paths.

        Allows paths in the following formats:
        - entity/project/runs/id (URL)
        - entity/project/id
        - entity/project:id (Docker style)
        - project/id
        - project:id
        - id (cannot contain colons)

        The path may also start with /runs/ or /sweeps/.

        Returns:
            A tuple with the extracted (entity, project, id).

        Raises:
            ValueError: If the path is in an invalid format or is missing
                an entity that is not otherwise provided.
        r   r   Nz/runs/rc   z/sweeps/r1  r4  r2  runsr   r7   r3  :)maxsplitzInvalid path: z (missing entity)z (missing project))r   r   rf   r;  r<  r   r   )rG   r0  r   r   r   
input_pathrA  rH   rH   rI   _parse_path  s>   



zApi._parse_pathtuple[str | None, str]c                 C     d S rC   rH   rG   r0  rH   rH   rI   _parse_artifact_path[     zApi._parse_artifact_pathtuple[str | None, str, str]c                 C  rK  rC   rH   rL  rH   rH   rI   rM  ]  rN  tuple[str | None, ...]c                 C  sb   ddl m} | jd pd}| jd p| j}|du r||fS ||}|j||d}|j|j|jfS )zGReturn project, entity and artifact name for project specified by path.r   )ArtifactPathr   r  r   N)prefixr   )	wandb.sdk.artifacts._validatorsrQ  r   r   from_strwith_defaultsrR  r   r   )rG   r0  rQ  r   r   parsedrH   rH   rI   rM  `  s   
   per_pageint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: 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: 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.
        Nr   r   rX  )r   r   r   r   r   ProjectsrB   )rG   r   rX  rH   rH   rI   projectsm  s   

zApi.projectspublic.Projectc                 C  sn   ddl m} ||r|nd}|du r| jd p| j}||r.| jd p%| j}t| j||d}t| j||i S )ar  Return the `Project` with the given name (and entity, if given).

        Args:
            name: The project name.
            entity: 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   is_artifact_registry_projectrb   Nr   non_org_entityorg_or_entity)rS  r`  r   r   r$   rB   r   Project)rG   r   r   r`  orgsettings_entityrH   rH   rI   r     s   zApi.projectrb   2   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.

        Note: `wandb.Api.reports()` API is in beta and will likely change in
        future releases.

        Args:
            path: The path to the project the report resides in. Specify the
                entity that created the project as a prefix followed by a
                forward slash.
            name: Name of the report requested.
            per_page: 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.

        Examples:
        ```python
        import wandb

        wandb.Api.reports("entity/project")
        ```
        z	/fake_runrc   r   rX  )rI  r?  ro   r@  r#  rm   r   r   ReportsrB   rd  )rG   r0  r   rX  r   r   r&  r   rH   rH   rI   reports  s   

zApi.reportsteamadmin_usernamer>   c                 C  r  )zCreate a new team.

        Args:
            team: The name of the team
            admin_username: Username of the admin user of the team.
                Defaults to the current user.

        Returns:
            A `Team` object.
        r7   r=   )teamsr>   r   )rG   rl  rm  r>   rH   rH   rI   create_team  s   zApi.create_teamc                 C  s   ddl m} || j|S )zReturn the matching `Team` with the given name.

        Args:
            team: The name of the team.

        Returns:
            A `Team` object.
        r7   r=   )rn  r>   rB   )rG   rl  r>   rH   rH   rI   rl    s   	zApi.teamusername_or_emailUser | Nonec           
      C  s   ddl m}m} ddlm} | jt|d|i}||}|j }r(|j	 }s*dS t
|dkr:d|}	t|	 || j|d j S )aU  Return a user from a username or email address.

        This function only works for local administrators. Use `api.viewer`
            to get your own user object.

        Args:
            username_or_email: The username or email address of the user.

        Returns:
            A `User` object or None if a user is not found.
        r   SEARCH_USERS_GQLSearchUsersr7   r?   queryNz8Found multiple users, returning the first user matching )r   rs  rt  r  r@   rE   rN   r   r*  edgesr   rZ   r[   noder   )
rG   rp  rs  rt  r@   r+  r   connrv  r.  rH   rH   rI   user  s   


zApi.user
list[User]c                   sh   ddl m}m} ddlm  jt|d|i}||}|j }r(|j	 }s*g S  fdd|D S )aZ  Return all users from a partial username or email address query.

        This function only works for local administrators. Use `api.viewer`
            to get your own user object.

        Args:
            username_or_email: The prefix or suffix of the user you want to find.

        Returns:
            An array of `User` objects.
        r   rr  r7   r?   ru  c                   s   g | ]} j |j qS rH   )rE   rw  r   )r  edger@   rG   rH   rI   r
    s    zApi.users.<locals>.<listcomp>)
r   rs  rt  r  r@   rE   rN   r   r*  rv  )rG   rp  rs  rt  r+  r   rx  rv  rH   r|  rI   r    s   
z	Api.users+created_atTfiltersorderinclude_sweepsrn   lazyc                 C  s   |  |\}}|p
i }|pdt| t| }	| j|	r-| j|	 }
|s+|
jr+|
  |
S tj| j||| j	|||||d	| j|	< | j|	 S )a  Returns a `Runs` object, which lazily iterates over `Run` objects.

        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`



        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 (default).
                If you prepend order with a - order is descending.
                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.
            lazy: (bool) Whether to use lazy loading for faster performance.
                When True (default), only essential run metadata is loaded initially.
                Heavy fields like config, summaryMetrics, and systemMetrics are loaded
                on-demand when accessed. Set to False for full data upfront.

        Returns:
            A `Runs` object, which is an iterable collection of `Run` objects.

        Examples:
        ```python
        import wandb
        from wandb.apis.public import Api

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

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

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

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

        ```python
        # Find runs in project sorted by ascending loss
        Api.runs(path="my_entity/project", order="+summary_metrics.loss")
        ```
        rb   )service_apir~  r  rX  r  r  )
rC  rm   r   rj   _lazyupgrade_to_fullr   RunsrB   r   )rG   r0  r~  r  rX  r  r  r   r   r   cached_runsrH   rH   rI   rE    s(   m


zApi.runsc                 C  sF   |  |\}}}| j|stj| j|||| jdd| j|< | j| S )ak  Return a single run by parsing path in the form `entity/project/run_id`.

        Args:
            path: 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.
        F)r  r  )rI  r   rj   r   r   rB   r   )rG   r0  r   r   r   rH   rH   rI   r"    s   
zApi.run
queue_namerun_queue_item_idc              	   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   	QueuedRunrB   )rG   r   r   r  r  r  r  rH   rH   rI   
queued_run  s   zApi.queued_runc                 C  s   t | j||S )zReturn the named `RunQueue` for entity.

        See `Api.create_run_queue` for more information on how to create a run queue.
        )r   r   rB   )rG   r   r   rH   rH   rI   	run_queue  s
   	zApi.run_queuec                 C  s>   |  |\}}}| j|st| j|||| j|< | j| S )a~  Return a sweep by parsing path in the form `entity/project/sweep_id`.

        Args:
            path: 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.
        )rI  r   rj   r   SweeprB   )rG   r0  r   r   sweep_idrH   rH   rI   r5    s   
z	Api.sweepr<   c                 C  sl   ddl m} ddlm} |}| |\}}||r/| jd p | j}t|tj	}t
| j||d}|| j||S )zReturns a collection of matching artifact types.

        Args:
            project: The project name or path to filter on.

        Returns:
            An iterable `ArtifactTypes` object.
        r   r_  r7   )r<   r   ra  )rS  r`  	artifactsr<   rC  r   r   r   r   r   r$   rB   )rG   r   r`  r<   project_pathr   rf  re  rH   rH   rI   artifact_types  s   
zApi.artifact_types	type_namer;   c           	      C  sn   ddl m} ddlm} |}| |\}}||r/t|tj}| jd p&| j	}t
| j||d}|| j|||S )zReturns the matching `ArtifactType`.

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

        Returns:
            An `ArtifactType` object.
        r   r_  r7   )r;   r   ra  )rS  r`  r  r;   rC  r   r   r   r   r   r$   rB   )	rG   r  r   r`  r;   r  r   re  rf  rH   rH   rI   artifact_type  s   zApi.artifact_typeproject_namer9   c           
      C  sn   ddl m} ddlm} | |\}}||r-t|tj}| jd p$| j	}	t
| j|	|d}|| j||||dS )a  Returns a collection of matching artifact collections.

        Args:
            project_name: The name of the project to filter on.
            type_name: The name of the artifact type to filter on.
            per_page: Sets the page size for query pagination.
                Usually there is no reason to change this.

        Returns:
            An iterable `ArtifactCollections` object.
        r   r_  r7   )r9   r   ra  r[  )rS  r`  r  r9   rC  r   r   r   r   r   r$   rB   )
rG   r  r  rX  r`  r9   r   r   re  rf  rH   rH   rI   artifact_collections&  s   zApi.artifact_collectionsr8   c           
      C  s~   ddl m} ddlm} | |\}}}||r.t|tj}| jd p%| j	}	t
| j|	|d}|du r6td|| j||||S )	a  Returns a single artifact collection by type.

        You can use the returned `ArtifactCollection` object to retrieve
        information about specific artifacts in that collection, and more.

        Args:
            type_name: The type of artifact collection to fetch.
            name: An artifact collection name. Optionally append the entity
                that logged the artifact as a prefix followed by a forward
                slash.

        Returns:
            An `ArtifactCollection` object.

        Examples:
        In the proceeding code snippet "type", "entity", "project", and
        "artifact_name" are placeholders for the collection type, your W&B
        entity, name of the project the artifact is in, and the name of
        the artifact, respectively.

        ```python
        import wandb

        collections = wandb.Api().artifact_collection(
            type_name="type", name="entity/project/artifact_name"
        )

        # Get the first artifact in the collection
        artifact_example = collections.artifacts()[0]

        # Download the contents of the artifact to the specified root directory.
        artifact_example.download()
        ```
        r   r_  r7   )r8   r   ra  NzZCould not determine entity. Please include the entity as part of the collection name path.)rS  r`  r  r8   rM  r   r   ARTIFACTr   r   r$   rB   r   )
rG   r  r   r`  r8   r   r   collection_namere  rf  rH   rH   rI   artifact_collectionE  s    $zApi.artifact_collectionc                 C  s"   t tdddd | j|||dS )z@Deprecated. Use `Api.artifacts(type_name, name)` method instead.T)api__artifact_versionszaApi.artifact_versions(type_name, name) is deprecated, use Api.artifacts(type_name, name) instead.)featuremessager[  )r+   r!   r  )rG   r  r   rX  rH   rH   rI   artifact_versions  s
   zApi.artifact_versionsr   list[str] | Noner:   c              	   C  st   ddl m} ddlm} | |\}}}	||r.t|tj}
| jd p%| j	}t
| j||
d}|| j|||	|||dS )a  Return an `Artifacts` collection.

        Args:
            type_name: The type of artifacts to fetch.
            name: The artifact's collection name. Optionally append the
                entity that logged the artifact as a prefix followed by
                a forward slash.
            per_page: Sets the page size for query pagination. Usually
                there is no reason to change this.
            tags: Only return artifacts with all of these tags.

        Returns:
            An iterable `Artifacts` object.

        Examples:
        In the proceeding code snippet, "type", "entity", "project", and
        "artifact_name" are placeholders for the artifact type, W&B entity,
        name of the project the artifact was logged to,
        and the name of the artifact, respectively.

        ```python
        import wandb

        wandb.Api().artifacts(type_name="type", name="entity/project/artifact_name")
        ```
        r   r_  r7   )r:   r   ra  )rX  r   )rS  r`  r  r:   rM  r   r   r  r   r   r$   rB   )rG   r  r   rX  r   r`  r:   r   r   r  re  rf  rH   rH   rI   r    s$   "zApi.artifactsenable_trackingr6   c                 C  s   ddl m}m} ddlm} |d u rtd| |\}}}	||rE|ddkr0|dd n| j	d }
| j	d p<| j
}t| j||
d	}|d u rMtd
||||	d}|j|| j|d}|d urq|j|krqtd| d|j |S )Nr   )FullArtifactPathr`  r5   z,You must specify name= to fetch an artifact.rc   r2  organizationr   ra  zXCould not determine entity. Please include the entity as part of the artifact name path.)rR  r   r   )r0  rB   r  ztype z( specified but this artifact is of type )rS  r  r`  wandb.sdk.artifacts.artifactr6   r   rM  countr<  r   r   r$   rB   
_from_namer   )rG   r   r   r  r  r`  r6   r   r   artifact_namer  rf  r0  artifactrH   rH   rI   	_artifact  s:   zApi._artifactc                 C  s   | j ||ddS )ar  Returns a single artifact.

        Args:
            name: The artifact's name. The name of an artifact resembles a
                filepath that consists, at a minimum, the name of the project
                the artifact was logged to, the name of the artifact, and the
                artifact's version or alias. Optionally append the entity that
                logged the artifact as a prefix followed by a forward slash.
                If no entity is specified in the name, the Run or API
                setting's entity is used.
            type: 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.

        Examples:
        In the following code snippets "entity", "project", "artifact",
        "version", and "alias" are placeholders for your W&B entity, name
        of the project the artifact is in, the name of the artifact,
        and artifact's version, respectively.

        ```python
        import wandb

        # Specify the project, artifact's name, and the artifact's alias
        wandb.Api().artifact(name="project/artifact:alias")

        # Specify the project, artifact's name, and a specific artifact version
        wandb.Api().artifact(name="project/artifact:version")

        # Specify the entity, project, artifact's name, and the artifact's alias
        wandb.Api().artifact(name="entity/project/artifact:alias")

        # Specify the entity, project, artifact's name, and a specific artifact version
        wandb.Api().artifact(name="entity/project/artifact:version")
        ```

        Note:
        This method is intended for external use only. Do not call `api.artifact()` within the wandb repository code.
        T)r   r   r  )r  )rG   r   r   rH   rH   rI   r    s   /zApi.artifact
public.Jobc                 C  s<   |du rt d|ddksd|vrt dt| ||S )zReturn a `Job` object.

        Args:
            name: The name of the job.
            path: The root path to download the job artifact.

        Returns:
            A `Job` object.
        Nz&You must specify name= to fetch a job.rc   r2  rF  zfInvalid job specification. A job must be of the form: <entity>/<project>/<job-name>:<alias-or-version>)r   r  r   Job)rG   r   r0  rH   rH   rI   job"  s   zApi.joblist[dict[str, Any]]c                 C  s   ddl }|du rtd|du rtdtd}z=| j|||dd}|r*|d s9td	| d
| d g W S |d d du rDg W S |d d d d }dd |D W S  |jjya   Y dS w )zReturn a list of jobs, if any, for the given entity and project.

        Args:
            entity: The entity for the listed jobs.
            project: The project for the listed jobs.

        Returns:
            A list of matching jobs.
        r   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  )projectName
entityNameartifactTypeNamer   z
Project: 'z' not found in entity: 'z' or access denied.artifactTypeartifactCollectionsrv  c                 S  s   g | ]}|d  d qS )rw  r  rH   )r  xrH   rH   rI   r
    s    z!Api.list_jobs.<locals>.<listcomp>F)	r]   r   r   rE   rN   rZ   	termerrorrV   	HTTPError)rG   r   r   r]   ru  artifact_queryr  rH   rH   rI   	list_jobs5  s@   #	
zApi.list_jobsc              
   C  sV   ddl }z	| || W dS  tjjy* } zt|j|jr W Y d}~dS d}~ww )a[  Whether an artifact version exists within the specified project and entity.

        Args:
            name: The name of artifact. Add the artifact's entity and project
                as a prefix. Append the version or the alias of the artifact
                with a colon. If the entity or project is not specified,
                W&B uses override parameters if populated. Otherwise, the
                entity is pulled from the user settings and the project is
                set to "Uncategorized".
            type: The type of artifact.

        Returns:
            True if the artifact version exists, False otherwise.

        Examples:
        In the proceeding code snippets "entity", "project", "artifact",
        "version", and "alias" are placeholders for your W&B entity, name of
        the project the artifact is in, the name of the artifact, and
        artifact's version, respectively.

        ```python
        import wandb

        wandb.Api().artifact_exists("entity/project/artifact:version")
        wandb.Api().artifact_exists("entity/project/artifact:alias")
        ```

        r   NFT)r]   r  rZ   errors	CommErrorr   excTimeoutrG   r   r   r]   erH   rH   rI   artifact_exists  s   zApi.artifact_existsc              
   C  sV   ddl }z	| || W dS  tjjy* } zt|j|jr W Y d}~dS d}~ww )a  Whether an artifact collection exists within a specified project and entity.

        Args:
            name: An artifact collection name. Optionally append the
                entity that logged the artifact as a prefix followed by
                a forward slash. If entity or project is not specified,
                infer the collection from the override params if they exist.
                Otherwise, entity is pulled from the user settings and project
                will default to "uncategorized".
            type: The type of artifact collection.

        Returns:
            True if the artifact collection exists, False otherwise.

        Examples:
        In the proceeding code snippet "type", and "collection_name" refer to the type
        of the artifact collection and the name of the collection, respectively.

        ```python
        import wandb

        wandb.Api.artifact_collection_exists(type="type", name="collection_name")
        ```
        r   NFT)r]   r  rZ   r  r  r   r  r  r  rH   rH   rI   artifact_collection_exists  s   zApi.artifact_collection_existsd   r  filterr   c                 C  s:   t | jtjstd|pt| j| j}t| j|||dS )a`  Returns a lazy iterator of `Registry` objects.

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

        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 lazy registry iterator.
                Fields available to filter for registries 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`
            per_page: Sets the page size for query pagination.

        Returns:
            A lazy iterator of `Registry` objects.

        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"}]}
        )
        ```
        zRegistry search API is not enabled on this wandb server version. Please upgrade your server version or contact support at support@wandb.com.)r  r  rX  )	r%   rB   pbARTIFACT_REGISTRY_SEARCHRuntimeErrorr   r   r   r   )rG   r  r  rX  rH   rH   rI   
registries  s   ;
zApi.registriesr   c                 C  sP   t | j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.)r%   rB   r  r  r  r   r   r   r   r   load)rG   r   r  
org_entityregistryrH   rH   rI   r    s   zApi.registry
visibility%Literal['organization', 'restricted']descriptionr  c                 C  s   t | j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   r  Nz	Registry z  already exists in organization z, please use a different name.)r%   rB   r  +INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATIONr  r   r   r   r  r   r   r   )rG   r   r  r  r  r  existing_registryrH   rH   rI   create_registryA  s4   ,zApi.create_registryr[  Iterator[Integration]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   	variablesrX  )wandb.apis.public.integrationsr  r   rB   )rG   r   rX  r  r  rH   rH   rI   integrations  s   zApi.integrationsIterator[WebhookIntegration]c                C  r  )a@  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   r  )r  r  r   rB   )rG   r   rX  r  r  rH   rH   rI   webhook_integrations     %zApi.webhook_integrations)r   rX  Iterator[SlackIntegration]c                C  r  )a5  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   r  )r  r  r   rB   )rG   r   rX  r  r  rH   rH   rI   slack_integrations  r  zApi.slack_integrationseventactionr  EventType | Noner  ActionType | Nonec                C  s`   ddl m}m} |du p||v pt| jd|j }|du p+||v p+t| jd|j }|o/|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  r%   rB   r	  )rG   r  r  r  r  supports_eventsupports_actionrH   rH   rI   _supports_automation  s   zApi._supports_automationset[str]c              	     sj   ddl m} ddlm}m}m}m} |jt||j	t||j
t||jt|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  rj   )r  r  fragment_namesr   rG   rH   rI   	<genexpr>9  s    

z4Api._omitted_automation_fragments.<locals>.<genexpr>)wandb.automationsr-   wandb.automations._generatedr  r  r  r  NO_OPr   	QUEUE_JOBNOTIFICATIONGENERIC_WEBHOOKset)rG   r-   r  r  r  r  rH   r  rI   _omitted_automation_fragments  s   




z!Api._omitted_automation_fragments)r   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")
        ```
        )r   r   zNo automations foundzMultiple automations found)	too_shorttoo_long)r   automationsr   )rG   r   r   rH   rH   rI   
automation@  s
    zApi.automationri  Iterator[Automation]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)r  rX  _queryc                   s
   | j  kS rC   r   )r  r  rH   rI   <lambda>  s   
 z!Api.automations.<locals>.<lambda>)	wandb.apis.public.automationsr  r  r  r   r  r   rB   r  )rG   r   r   rX  r  r  r   r  gql_strr  ru  iteratorrH   r  rI   r  f  s    
zApi.automations)fetch_existingobjr1   r	  rM   Unpack[WriteAutomationsKwargs]c             
   K  s  ddl }ddlm} ddlm}m} ddlm} ||fi |}	| j|	j	 }
|	j
 }ds8td|
d|d	|  }t||d
}d|	 i}|	j}z
| jj||d}W n9 |jy } z,t|jj}|tju r|rt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 )aZ  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   N)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   variable_valuesAutomation z exists. Fetching it instead.r  z5 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  r  triggering_event_typetriggered_action_typer   r  r   r   r   rB   rN   r  r   responsestatus_codeCONFLICTrZ   termlogr  r*  r   r	   r  trigger)rG   r
  r	  rM   r]   r.   r  r  r  r   r  r  r  mutationr  r   r+  r  statusr   r.  rH   rH   rI   create_automation  sV   ;




zApi.create_automation)create_missingr  c             
   K  s  ddl }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sGtd	|j d
|j d|  }t||d}d|
 i}|
j}z
| jj||d}W nE |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 )ap  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   N)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   r  r  z not found. Creating it.z 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  r  r  r  r  r   r	  r  r   r   r   rB   rN   r  r   r  r  	NOT_FOUNDrZ   r  r  r  textr*  r   r	   r  )rG   r
  r  rM   r]   r-   r.   r   r!  r"  r   r  r  r  r  r  r   r+  r  r  r   r.  rH   rH   rI   update_automation	  s`   <




zApi.update_automationAutomation | strLiteral[True]c              
   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   rB   rN   r*  r   r	   r  r   )rG   r
  r(  r)  r*  id_r  r  r+  r   r  r.  rH   rH   rI   delete_automation	  s&   


zApi.delete_automation)NNN)rz   r{   rT   r|   r}   r~   rO   r   )r   rm   rO   r   )rO   r   )r   rm   r   rm   rO   r   )r   r~   r   r~   r   r~   rO   r   )NNNN)r   rm   r   r   r   r~   r   r   r   r   r   r   rO   r   )r   rm   r   rm   r   rm   r   r   r   r   r   r   rO   rm   )r   rm   r  r  r  r   r   r~   r   r   r  r   r   r   )F)r   rm   r  r  rO   r@   )rO   rA   )rO   rm   )rO   r~   )rO   r@   )r0  rm   )r0  rm   rO   rD  )r0  r   rO   rJ  )r0  rm   rO   rO  )r0  r~   rO   rP  )NrW  )r   r~   rX  rY  rO   rZ  rC   )r   rm   r   r~   rO   r^  )rb   Nrg  )r0  rm   r   r~   rX  rY  rO   rh  )rl  rm   rm  r~   rO   r>   )rl  rm   rO   r>   )rp  rm   rO   rq  )rp  rm   rO   rz  )NNr}  rg  TT)r0  r~   r~  r{   r  rm   rX  rY  r  rn   r  rn   )rb   )NN)r   rm   r   rm   r  rm   r  rm   )r   rm   r   rm   )r   r~   rO   r<   )r  rm   r   r~   rO   r;   )rg  )r  rm   r  rm   rX  rY  rO   r9   )r  rm   r   rm   rO   r8   )rg  N)
r  rm   r   rm   rX  rY  r   r  rO   r:   )NF)r   rm   r   r~   r  rn   rO   r6   )r   rm   r   r~   )r   r~   r0  r~   rO   r  )r   rm   r   rm   rO   r  )r   rm   r   r~   rO   rn   )r   rm   r   rm   rO   rn   )NNr  )r  r~   r  r{   rX  rY  rO   r   )r   rm   r  r~   rO   r   )r   rm   r  r  r  r~   r  r~   r  r  rO   r   )r   r~   rX  rY  rO   r  )r   r~   rX  rY  rO   r  )r   r~   rX  rY  rO   r  )r  r  r  r  rO   rn   )rO   r  )r   rm   r   r~   rO   r.   )r   r~   r   r~   rX  rY  rO   r  )r
  r1   r	  rn   rM   r  rO   r.   )r
  r.   r  rn   rM   r  rO   r.   )r
  r&  rO   r'  )Crt   ru   rv   rw   r   get_http_timeoutr   rJ   r   r   r   r   r   r   r  r  r  rx   rB   r   r   r   r/  rB  rC  rI  r   rM  r]  r   rk  ro  rl  ry  r  rE  r   r"  r  r  r5  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r%  r,  rH   rH   rH   rI   r&      s$   


N


kTm

	@
L
, 97-0O'#G'J),0%8l{r&   )irw   
__future__r   r   loggingr   r?  collections.abcr   httpr   typingr   r   r   r   pydanticr	   typing_extensionsr
   r   	wandb_gqlr   r   wandb_gql.clientr   rZ   r   r   wandb._analyticsr   wandb._iterutilsr   wandb._strutilsr   
wandb.apisr   wandb.apis.normalizer   wandb.apis.public.constr   wandb.apis.public.registriesr   r   #wandb.apis.public.registries._utilsr   wandb.apis.public.service_apir   wandb.apis.public.utilsr   r   r   r   wandb.errorsr   wandb.protor    r  wandb.proto.wandb_telemetry_pb2r!   	wandb.sdkr"   r#   wandb.sdk.artifacts._gqlutilsr$   r%   wandb.sdk.internal.internal_apir&   r   wandb.sdk.launch.utilsr'   wandb.sdk.libr(   r)   r*   wandb.sdk.lib.deprecationr+   wandb.sdk.lib.gql_requestr,   r  r-   r.   r/   r0   r1   r2   r3   r  r4   r  r6   r  r8   r9   r:   r;   r<   rn  r>   r  r@   	getLoggerrt   loggerrA   rH   rH   rH   rI   <module>   sZ    $	
J