o
    ni@X                    @  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Zddl	Z
ddlZddlZddlZddlZddlZddlZddlmZ ddlmZmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZmZm Z m!Z! dd	l"m#Z# ddl$Z$ddl%Z%dd
l%m&Z&m'Z'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZF ddlGmHZH ddlImJZJmKZK ddlLmMZM ddlNmOZO ddlPmQZQ ddlRmSZS ddlTmUZU ddlVm ZW ddlVmXZX ddlYmZZ[ dd l\m]Z] dd!l^m_Z_m`Z`maZambZb dd"lcmdZdmeZe dd#lfmgZgmhZhmiZi dd$ljmkZk dd%llmmZmmnZnmoZompZp dd&lqmrZr e(s Ztdd'lumvZv et  ewexZyergdd(lzm{Z{ G d)d* d*Z|d5d.d/Z}d6d1d2Z~G d3d4 d4eWZeXe dS )7zArtifact class.    )annotationsN)copy)datetime	timedelta)partial)PurePosixPath)	IOTYPE_CHECKINGAnyDictIteratorLiteralSequenceTypecast)urlparse)
data_typesenvutil)normalize_exceptions)ArtifactCollectionArtifactFilesRetryingClientRun)WBValue)	termerrortermlogtermwarn)ensure_loggedensure_not_finalizedvalidate_aliasesvalidate_tags)ArtifactDownloadLogger)artifact_instance_cache)ArtifactManifest)ArtifactManifestEntry)ArtifactManifestV1)ArtifactState)ArtifactTTL)ArtifactNotLoggedErrorWaitTimeoutError)get_staging_dir)_GCSIsADirectoryError)StorageLayout)WANDB_STORAGE_POLICY)StoragePolicy)r   )TypeRegistry)Api)_thread_local_api_settings)
filesystemretryrunid	telemetry)
Deprecated	deprecate)B64MD5b64_to_hex_idmd5_file_b64)Mailbox)FilePathStrLogicalPathStrPathURIStr)generate_id)gql)MessageFuturec                   @  s`  e Zd ZdZedZeej	 				ddddZ
dddZedddZeddddd Zedd#d$Zdd%d&Zedd'd(Zedd)d*Zeedd+d,Zeedd-d.Zedd/d0Zedd1d2Zeedd3d4Zeedd6d7Zeedd8d9Zeedd:d;Zedd<d=Zedd>d?Zeedd@dAZeeddBdCZ eddDdEZ!eddFdGZ"e"j#ddHdGZ"eddJdKZ$e$j#ddLdKZ$eddNdOZ%e%j#ddRdOZ%eeddTdUZ&e&j#eddWdUZ&eeddXdYZ'e'j#edd[dYZ'edd\d]Z(e(j#dd_d]Z(ed d`daZ)eddbdcZ*eddddeZ+ed!dgdhZ,eddidjZ-ed"dldmZ.eeddndoZ/eed"dpdqZ0eeddrdsZ1eeddtduZ2d#dvdwZ3d dxdyZ4d dzd{Z5		d$d%d~dZ6d&ddZ7d'd(ddZ8d)ddZ9e:d#ddZ;d*ddZ<d+ddZ=e>j?e@	d,d-ddZAe@					d.d/ddZBe@			d0d1ddZCe@			d2d3ddZDe@	d4d5ddZE				d6d7ddZFe@d8ddZGd9ddZHed9ddZIed*ddZJd:ddZKd;ddńZLe				d<d=dd˄ZM			d>d?dd̈́ZN			d@dAddτZOePjQeRddэeSjTdҍdBdCdd؄ZUed'dDddڄZVed'dEdd܄ZWed'dFddބZXe	ߐdGdHddZYdIdJddZZdKddZ[dLddZ\ed4dMddZ]e:d4dMddZ^e:d'dNddZ_ed#ddZ`e:d#ddZaedOddZbedPddZcedQd dZdeedRddZfeedSddZgdTd	d
ZhdUddZidS (V  Artifacta{  Flexible and lightweight building block for dataset and model versioning.

    Construct an empty W&B Artifact. Populate an artifacts contents with methods that
    begin with `add`. Once the artifact has all the desired files, you can call
    `wandb.log_artifact()` to log it.

    Args:
        name: A human-readable name for the artifact. Use the name to identify
            a specific artifact in the W&B App UI or programmatically. You can
            interactively reference an artifact with the `use_artifact` Public API.
            A name can contain letters, numbers, underscores, hyphens, and dots.
            The name must be unique across a project.
        type: The artifact's type. Use the type of an artifact to both organize
            and differentiate artifacts. You can use any string that contains letters,
            numbers, underscores, hyphens, and dots. Common types include `dataset` or `model`.
            Include `model` within your type string if you want to link the artifact
            to the W&B Model Registry.
        description: A description of the artifact. For Model or Dataset Artifacts,
            add documentation for your standardized team model or dataset card. View
            an artifact's description programmatically with the `Artifact.description`
            attribute or programmatically with the W&B App UI. W&B renders the
            description as markdown in the W&B App.
        metadata: Additional information about an artifact. Specify metadata as a
            dictionary of key-value pairs. You can specify no more than 100 total keys.

    Returns:
        An `Artifact` object.
    zwandb-artifactsNFnamestrtypedescription
str | Nonemetadatadict[str, Any] | Noneincrementalbooluse_asreturnNonec           
      C  s  t d|std| |dks|drtd|r td d | _tt}t	
 r/tjntj}d|i}	|j|	d| _d | _i | _i | _d | _t | _d | _d | _td	| _td	| _d | _d | _|| _d | _d | _ d | _!|| _"d | _#|| _$|| _%| &|| _'d | _(d
| _)d| _*g | _+g | _,g | _-g | _.d | _/|| _0|| _1t2j3| _4t5| j| _6d | _7d | _8d | _9d | _:d| _;| t<| j< d S )Nz^[a-zA-Z0-9_\-.]+$zeArtifact name may only contain alphanumeric characters, dashes, underscores, and dots. Invalid name: jobzwandb-z^Artifact types 'job' and 'wandb-*' are reserved for internal use. Please use a different type.z$Using experimental arg `incremental`storageLayout)config   TF)=rematch
ValueError
startswithr   _clientr/   lookup_by_namer.   r   get_use_v1_artifactsr-   V1V2from_config_storage_policy_tmp_dir_added_objs_added_local_paths_save_futureset_download_roots_base_id_idr5   rA   
_client_id_sequence_client_id_entity_project_name_version_source_entity_source_project_source_name_source_version_type_description_normalize_metadata	_metadata_ttl_duration_seconds_ttl_is_inherited_ttl_changed_aliases_saved_aliases_tags_saved_tags_distributed_id_incremental_use_asr'   PENDING_stater&   	_manifest_commit_hash_file_count_created_at_updated_at_finalr#   )
selfrE   rG   rH   rJ   rL   rN   storage_policy_clslayoutpolicy_config r   Z/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact.py__init__m   sr   	
zArtifact.__init__c                 C  s   d| j p| j dS )Nz
<Artifact >)idrE   r   r   r   r   __repr__   s   zArtifact.__repr__artifact_idclientr   Artifact | Nonec                 C  s   t |}|d ur|S tdt  }|j|d|id}|d}|d u r&d S |d }|d }|r4|d nd}	|r<|d	 nd}
d
|d	 |d }| |	|
|||S )Nz
            query ArtifactByID($id: ID!) {
                artifact(id: $id) {
                    ...ArtifactFragment
                }
            }
            r   variable_valuesartifactartifactSequenceproject
entityName rE   z{}:v{}versionIndex)r#   getrB   _gql_artifact_fragmentexecuteformat_from_attrs)clsr   r   r   queryresponseattrssrc_collectionsrc_projectentity_nameproject_namerE   r   r   r   _from_id   s*   


zArtifact._from_id)enable_trackingentityr   r   c                C  s   t   }g d}dg}|r|d |d d|}	d|}
td|	 d|
 dt  d	}|||d
}|r=||d< |j||d}|d}|sVtd| d| d|d}|sktd| d| d| d| 	|||||S )N)z$entityName: String!z$projectName: String!z$name: String!zname: $namez$enableTracking: BooleanzenableTracking: $enableTrackingz, z"
            query ArtifactByName(zh) {
                project(name: $projectName, entityName: $entityName) {
                    artifact(zr) {
                        ...ArtifactFragment
                    }
                }
            }
            
            r   projectNamerE   enableTrackingr   r   z	project 'z' not found under entity ''r   z
artifact 'z' not found in '/)
InternalApi!server_project_type_introspectionappendjoinrB   r   r   r   rW   r   )r   r   r   rE   r   r   0server_supports_enabling_artifact_usage_tracking
query_vars
query_argsvars_strargs_strr   query_variable_valuesr   project_attrsr   r   r   r   
_from_name   sF   





zArtifact._from_namer   dict[str, Any]c                 C  sR   | ddd}||_ ||_||_||_|| |  |jd us"J |t|j< |S )Nplaceholder)rG   )rY   rj   rk   rl   _assign_attrsfinalizer   r#   )r   r   r   rE   r   r   r   r   r   r   r     s   


zArtifact._from_attrsc              	     s`  |d | _ d|d  }|d }|d }|r|d nd| _|r#|d nd| _|d  d	| | _|| _| jd
u r<| j| _| jd
u rE| j| _| jd
u rN| j| _|d d | _|d | _	| j| j| j
d	^ } fdd|d D }dd |D }dd |D }|rz|\}	W n ty   tdt| d|w |}	|	| _d	| jvr| j d	|	 | _|| _t|| _dd |dg D }
|
| _t|
| _|d }| |rt|ni | _t|d| _|dd
u rdn|d | _t|d | _z
|d d d }W n ttfy   d
| _Y nw |  || _|d | _!|d | _"|d  | _#|d! | _$d
S )"z<Update this Artifact's attributes using the server response.r   vr   r   r   r   r   rE   :NartifactTyperH   c                   s`   g | ],}|d  r.|d  d r.|d  d d kr.|d  d d kr.|d  d  kr|d qS )artifactCollectionr   r   rE   aliasr   .0obj
collectionr   r   r   r   
<listcomp>E  s    
z*Artifact._assign_attrs.<locals>.<listcomp>aliasesc                 S  s   g | ]	}t |r|qS r   r   alias_is_version_indexr   r   r   r   r   r   O  
    
c                 S  s   g | ]	}t |s|qS r   r   r   r   r   r   r   R  r   z(Expected at most one version alias, got : c                 S  s   g | ]}|d  qS )rE   r   r   r   r   r   r   g      tagsrJ   ttlDurationSecondsttlIsInheritedTstatecurrentManifestfile	directUrl
commitHash	fileCount	createdAt	updatedAt)%rg   rn   ro   rp   rq   rj   rk   rl   rr   rs   splitrW   lenrm   ry   r   rz   r   r{   r|   rt   jsonloadsrJ   _ttl_duration_seconds_from_gqlrv   rw   r'   r   LookupError	TypeErrorr   _load_manifestr   r   r   r   )r   r   src_versionr   r   _r   version_aliasesother_aliasesversionr   metadata_strmanifest_urlr   r   r   r   *  s   













zArtifact._assign_attrsc                 C  sn   t | jdd | j}| j|_| j|_| j|_| j|_| j|_	| j
|_
| j|_| j|_t| j |_|S )a6  Create a new draft artifact with the same content as this committed artifact.

        The artifact returned can be extended or modified and logged as a new version.

        Returns:
            An `Artifact` object.

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
        r   r   )rD   source_namer   rG   rn   rj   ro   rk   r   rf   rY   rH   rs   rJ   ru   r$   from_manifest_jsonmanifestto_manifest_jsonr   )r   r   r   r   r   	new_draft  s   zArtifact.new_draftc                 C  s    |   rdS | jdusJ | jS )zThe artifact's ID.N)is_draftrg   r   r   r   r   r     s   zArtifact.idc                 C     | j dusJ | j S )zHThe name of the entity of the secondary (portfolio) artifact collection.N)rj   r   r   r   r   r        zArtifact.entityc                 C  r   )zIThe name of the project of the secondary (portfolio) artifact collection.N)rk   r   r   r   r   r     r   zArtifact.projectc                 C     | j S )zThe artifact name and version in its secondary (portfolio) collection.

        A string with the format `{collection}:{alias}`. Before the artifact is saved,
        contains only the name since the version is not yet known.
        )rl   r   r   r   r   rE        zArtifact.namec                 C     | j  d| j d| j S )z@The entity/project/name of the secondary (portfolio) collection.r   )r   r   rE   r   r   r   r   qualified_name     zArtifact.qualified_namec                 C  r   )z?The artifact's version in its secondary (portfolio) collection.N)rm   r   r   r   r   r     r   zArtifact.versionr   c                 C  (   | j dd }t| j| j| j|| jS )a  The collection this artifact was retrieved from.

        A collection is an ordered group of artifact versions.
        If this artifact was retrieved from a portfolio / linked collection, that
        collection will be returned rather than the collection
        that an artifact version originated from. The collection
        that an artifact originates from is known as the source sequence.
        r   r   )rE   r   r   rY   r   r   rG   r   	base_namer   r   r   r     s   zArtifact.collectionc                 C  r   )zEThe name of the entity of the primary (sequence) artifact collection.N)rn   r   r   r   r   source_entity  r   zArtifact.source_entityc                 C  r   )zFThe name of the project of the primary (sequence) artifact collection.N)ro   r   r   r   r   source_project  r   zArtifact.source_projectc                 C  r   )zThe artifact name and version in its primary (sequence) collection.

        A string with the format `{collection}:{alias}`. Before the artifact is saved,
        contains only the name since the version is not yet known.
        )rp   r   r   r   r   r     r   zArtifact.source_namec                 C  r   )z=The entity/project/name of the primary (sequence) collection.r   )r   r  r   r   r   r   r   source_qualified_name  r   zArtifact.source_qualified_namec                 C  r   )ztThe artifact's version in its primary (sequence) collection.

        A string with the format `v{number}`.
        N)rq   r   r   r   r   source_version  s   zArtifact.source_versionc                 C  r   )z-The artifact's primary (sequence) collection.r   r   )r   r   r   rY   r   r  rG   r   r   r   r   source_collection	  s   zArtifact.source_collectionc                 C  r   )z?The artifact's type. Common types include `dataset` or `model`.)rr   r   r   r   r   rG        zArtifact.typec                 C  r   )zA description of the artifact.rs   r   r   r   r   rH     r  zArtifact.descriptionc                 C  s
   || _ dS )a>  Set the description of the artifact.

        For model or dataset Artifacts, add documentation for your
        standardized team model or dataset card. In the W&B UI the
        description is rendered as markdown.

        Args:
            description: Free text that offers a description of the artifact.
        Nr  )r   rH   r   r   r   rH     s   
dictc                 C  r   )z_User-defined artifact metadata.

        Structured data associated with the artifact.
        )ru   r   r   r   r   rJ   )  s   zArtifact.metadatac                 C  s   |  || _dS )a?  User-defined artifact metadata.

        Metadata set this way will eventually be queryable and plottable in the UI; e.g.
        the class distribution of a dataset.

        Note: There is currently a limit of 100 total keys.

        Args:
            metadata: Structured data associated with the artifact.
        N)rt   ru   )r   rJ   r   r   r   rJ   1  s   timedelta | Nonec                 C  sD   | j r|  s
| jrtt| j d| | jdu rdS t| jdS )aJ  The time-to-live (TTL) policy of an artifact.

        Artifacts are deleted shortly after a TTL policy's duration passes.
        If set to `None`, the artifact deactivates TTL policies and will be not
        scheduled for deletion, even if there is a team default TTL.
        An artifact inherits a TTL policy from
        the team default if the team administrator defines a default
        TTL and there is no custom policy set on an artifact.

        Raises:
            ArtifactNotLoggedError: Unable to fetch inherited TTL if the artifact has not been logged or saved
        z.ttlN)seconds)rw   r   rx   r)   rG   __name__rv   r   r   r   r   r   ttl?  s
   
zArtifact.ttlr  timedelta | ArtifactTTL | Nonec                 C  s   | j dkr	tdd| _t|tr"|tjkrd| _dS td| d| _|du r.d| _dS | dkr=td|  t	| | _dS )	aQ  The time-to-live (TTL) policy of an artifact.

        Artifacts are deleted shortly after a TTL policy's duration passes.
        If set to `None`, the artifact has no TTL policy set and it is not
        scheduled for deletion. An artifact inherits a TTL policy from
        the team default if the team administrator defines a default
        TTL and there is no custom policy set on an artifact.

        Args:
            ttl: The duration as a positive Python `datetime.timedelta` Type
                that represents how long the artifact will remain active from its creation.

        zwandb-historyz.Cannot set artifact TTL for type wandb-historyTzUnhandled ArtifactTTL enum FNr   z/Artifact TTL Duration has to be positive. ttl: )
rG   rW   rx   
isinstancer(   INHERITrw   rv   total_secondsint)r   r  r   r   r   r  S  s   




	list[str]c                 C  r   )a  List of one or more semantically-friendly references or identifying "nicknames" assigned to an artifact version.

        Aliases are mutable references that you can programmatically reference.
        Change an artifact's alias with the W&B App UI or programmatically.
        See [Create new artifact versions](https://docs.wandb.ai/guides/artifacts/create-a-new-artifact-version)
        for more information.
        )ry   r   r   r   r   r   v  s   
zArtifact.aliasesr   c                 C     t || _dS )z.Set the aliases associated with this artifact.N)r    ry   )r   r   r   r   r   r        c                 C  r   )z;List of one or more tags assigned to this artifact version.)r{   r   r   r   r   r     s   zArtifact.tagsr   c                 C  r  )z+Set the tags associated with this artifact.N)r!   r{   )r   r   r   r   r   r     r  c                 C  r   Nr}   r   r   r   r   distributed_id     zArtifact.distributed_idr  c                 C  s
   || _ d S r  r  )r   r  r   r   r   r    s   
c                 C  r   r  )r~   r   r   r   r   rL     r  zArtifact.incrementalc                 C  r   r  )r   r   r   r   r   rN     r  zArtifact.use_asc                 C  s   | j jS )zIThe status of the artifact. One of: "PENDING", "COMMITTED", or "DELETED".)r   valuer   r   r   r   r     s   zArtifact.stater$   c                 C  sh   | j du r1td}| jdusJ | jj|| j| j| jdd}|d d }| |d d d	 | _ | j S )
zThe artifact's manifest.

        The manifest lists all of its contents, and can't be changed once the artifact
        has been logged.
        NaE  
                query ArtifactManifest(
                    $entityName: String!,
                    $projectName: String!,
                    $name: String!
                ) {
                    project(entityName: $entityName, name: $projectName) {
                        artifact(name: $name) {
                            currentManifest {
                                file {
                                    directUrl
                                }
                            }
                        }
                    }
                }
                r   r   r   r   r   r   r   )r   rB   rY   r   rj   rk   rl   r   )r   r   r   r   r   r   r   r     s"   
zArtifact.manifestc                 C  s
   | j  S )zThe logical digest of the artifact.

        The digest is the checksum of the artifact's contents. If an artifact has the
        same digest as the current `latest` version, then `log_artifact` is a no-op.
        )r   digestr   r   r   r   r       
zArtifact.digestr  c                 C  s.   d}| j j D ]}|jdur||j7 }q|S )zlThe total size of the artifact in bytes.

        Includes any references tracked by this artifact.
        r   N)r   entriesvaluessize)r   
total_sizeentryr   r   r   r    s   

zArtifact.sizec                 C  r   )z3The hash returned when this artifact was committed.N)r   r   r   r   r   commit_hash  r   zArtifact.commit_hashc                 C  r   )z+The number of files (including references).N)r   r   r   r   r   
file_count  r   zArtifact.file_countc                 C  r   )z(Timestamp when the artifact was created.N)r   r   r   r   r   
created_at  r   zArtifact.created_atc                 C  s   | j dusJ | jp| j S )z,The time when the artifact was last updated.N)r   r   r   r   r   r   
updated_at  s   zArtifact.updated_atc                 C  s
   d| _ dS )aW  Finalize the artifact version.

        You cannot modify an artifact version once it is finalized because the artifact
        is logged as a specific artifact version. Create a new artifact version
        to log more data to an artifact. An artifact is automatically finalized
        when you log the artifact with `log_artifact`.
        TN)r   r   r   r   r   r     s   
zArtifact.finalizec                 C  s   | j tjkS )zCheck if artifact is not saved.

        Returns: Boolean. `False` if artifact is saved. `True` if artifact is not saved.
        )r   r'   r   r   r   r   r   r     s   zArtifact.is_draftc                 C  s
   | j d uS r  )rc   r   r   r   r   _is_draft_save_started  s   
zArtifact._is_draft_save_startedsettingswandb.Settings | Nonec              	   C  s   | j tjkr
|  S | jr%t }d|j_W d   n1 s w   Y  t	j
du rv|du r4t	jdd}t	j| j|p<| jd|d+}| jr_tj|d}d|j_W d   n1 sZw   Y  ||  W d   dS 1 sow   Y  dS t	j
|  dS )a  Persist any changes made to the artifact.

        If currently in a run, that run will log this artifact. If not currently in a
        run, a run of type "auto" is created to track this artifact.

        Args:
            project: A project to use for the artifact in the case that a run is not
                already in context.
            settings: A settings object to use when initializing an automatic run. Most
                commonly used in testing harness.
        TNtruesilentautor   r   job_typer%  )run)r   r'   r   _updater~   r6   contextfeatureartifact_incrementalwandbr-  Settingsinitrn   ro   log_artifact)r   r   r%  telr-  r   r   r   save  s.   



"zArtifact.savesave_futurerC   c                 C  s   || _ || _d S r  )rc   rY   )r   r8  r   r   r   r   _set_save_futureC  s   
zArtifact._set_save_futuretimeout
int | Nonec                 C  sd   |   r0| jdu rtt| jj| | j|}|std|jj	}|j
r*t|j
| |j | S )zIf needed, wait for this artifact to finish logging.

        Args:
            timeout: The time, in seconds, to wait.

        Returns:
            An `Artifact` object.
        NzAArtifact upload wait timed out, failed to fetch Artifact response)r   rc   r)   rG   wait__qualname__r   r*   r   log_artifact_responseerror_messagerW   _populate_after_saver   )r   r:  resultr   r   r   r   r<  I  s   	

zArtifact.waitc                 C  sl   dt   }t|}| jd usJ | jj|d|id}z|d }W n ty.   td|w | | d S )Nz
            query ArtifactByIDShort($id: ID!) {
                artifact(id: $id) {
                    ...ArtifactFragment
                }
            }
        r   r   r   z"Unable to fetch artifact with id: )r   rB   rY   r   r   rW   r   )r   r   query_templater   r   r   r   r   r   r@  `  s   zArtifact._populate_after_savec              
     sp  d}t d} jdusJ  j|}|drst jt j }t jt j }|rLt d} jdus9J  jj| j fdd|D dd |rlt d	} jdusYJ  jj| j fd
d|D dd t j _n
 fdd jD }dt	  }t
  }	d|	v r|dddddd}n jrtd |dddddd}tt jt j }
tt jt j }d|	v r|dddddddd}n|
s|rtd |dddddddd}t |} jdusJ   } jj| j jt j||d d |
D d!d |D d"d}|d# d$ } | d% _dS )&z/Persists artifact changes to the wandb backend.Na  
            query ProbeServerAddAliasesInput {
               AddAliasesInputInfoType: __type(name: "AddAliasesInput") {
                   name
                   inputFields {
                       name
                   }
                }
            }
            AddAliasesInputInfoTypea  
                    mutation addAliases(
                        $artifactID: ID!,
                        $aliases: [ArtifactCollectionAliasInput!]!,
                    ) {
                        addAliases(
                            input: {artifactID: $artifactID, aliases: $aliases}
                        ) {
                            success
                        }
                    }
                    c                   *   g | ]} j  j jd d |dqS r   r   )r   r   artifactCollectionNamer   rj   rk   rl   r   r   r   r   r   r         z$Artifact._update.<locals>.<listcomp>)
artifactIDr   r   a  
                    mutation deleteAliases(
                        $artifactID: ID!,
                        $aliases: [ArtifactCollectionAliasInput!]!,
                    ) {
                        deleteAliases(
                            input: {artifactID: $artifactID, aliases: $aliases}
                        ) {
                            success
                        }
                    }
                    c                   rD  rE  rG  r   r   r   r   r     rH  c                   s"   g | ]} j d d |dqS )r   r   )rF  r   )rl   r   r   r   r   r   r     s    a  
            mutation updateArtifact(
                $artifactID: ID!
                $description: String
                $metadata: JSONString
                _TTL_DURATION_SECONDS_TYPE_
                _TAGS_TO_ADD_TYPE_
                _TAGS_TO_DELETE_TYPE_
                $aliases: [ArtifactAliasInput!]
            ) {
                updateArtifact(
                    input: {
                        artifactID: $artifactID,
                        description: $description,
                        metadata: $metadata,
                        _TTL_DURATION_SECONDS_VALUE_
                        _TAGS_TO_ADD_VALUE_
                        _TAGS_TO_DELETE_VALUE_
                        aliases: $aliases
                    }
                ) {
                    artifact {
                        ...ArtifactFragment
                    }
                }
            }
        r   _TTL_DURATION_SECONDS_TYPE_z$ttlDurationSeconds: Int64_TTL_DURATION_SECONDS_VALUE_z'ttlDurationSeconds: $ttlDurationSeconds_TTL_DURATION_SECONDS_FIELDS_z!ttlDurationSeconds ttlIsInheritedz_Server not compatible with setting Artifact TTLs, please upgrade the server to use Artifact TTLr   r   _TAGS_TO_ADD_TYPE_z$tagsToAdd: [TagInput!]_TAGS_TO_DELETE_TYPE_z$tagsToDelete: [TagInput!]_TAGS_TO_ADD_VALUE_ztagsToAdd: $tagsToAdd_TAGS_TO_DELETE_VALUE_ztagsToDelete: $tagsToDeletezmServer not compatible with Artifact tags. To use Artifact tags, please upgrade the server to v0.85 or higher.c                 S     g | ]}d |iqS tagNamer   r   tag_namer   r   r   r   0  r   c                 S  rQ  rR  r   rT  r   r   r   r   1  r   )rI  rH   rJ   r   r   	tagsToAddtagsToDeleteupdateArtifactr   F)rB   rY   r   r   rd   ry   rz   r   r   r   r   server_artifact_introspectionreplacerx   r   r!   r{   r|   _ttl_duration_seconds_to_gqlrH   r   json_dumps_saferrJ   r   )r   r   introspect_queryr   aliases_to_addaliases_to_deleteadd_mutationdelete_mutationmutation_templatefieldstags_to_addtags_to_deletemutationttl_duration_inputr   r   r   r   r.  x  s   





	



zArtifact._updateWBValue | Nonec                 C  s
   |  |S )ab  Get the WBValue object located at the artifact relative `name`.

        Args:
            name: The artifact relative name to get.

        Returns:
            W&B object that can be logged with `wandb.log()` and visualized in the W&B UI.

        Raises:
            ArtifactNotLoggedError: If the artifact isn't logged or the run is offline.
        )r   r   rE   r   r   r   __getitem__;  s   
zArtifact.__getitem__itemr   r%   c                 C  s   |  ||S )a  Add `item` to the artifact at path `name`.

        Args:
            name: The path within the artifact to add the object.
            item: The object to add.

        Returns:
            The added manifest entry

        Raises:
            ArtifactFinalizedError: You cannot make changes to the current artifact
            version because it is finalized. Log a new artifact version instead.
        )add)r   rE   rk  r   r   r   __setitem__I  s   zArtifact.__setitem__xmodeencodingIterator[IO]c              
   c  s    d|v}| j du rt | _ tj| j j|d}t	tj
| zt|||}|V  W d   n1 s:w   Y  W n, tyQ   td|d| tyl } ztdt|j d| d |d}~ww | j||d	d
|d dS )a`  Open a new temporary file and add it to the artifact.

        Args:
            name: The name of the new file to add to the artifact.
            mode: The file access mode to use to open the new file.
            encoding: The encoding used to open the new file.

        Returns:
            A new file object that can be written to. Upon closing, the file will be
            automatically added to the artifact.

        Raises:
            ArtifactFinalizedError: You cannot make changes to the current artifact
            version because it is finalized. Log a new artifact version instead.
        rn  Nr   zFile with name z already exists at z"Failed to open the provided file (r   z&). Please provide the proper encoding.	immutableT)rE   policy
skip_cache	overwrite)r`   tempfileTemporaryDirectoryospathr   rE   lstripr3   mkdir_exists_okdirnamer   
fsync_openFileExistsErrorrW   UnicodeEncodeErrorr   rG   r
  add_file)r   rE   ro  rp  ru  ry  fer   r   r   new_fileY  s.   



zArtifact.new_filemutable
local_pathis_tmpbool | Nonert  rs  &Literal['mutable', 'immutable'] | Noneru  c                 C  s   t j|std|t|pt j|}t|}|r>t j|\}}	|	d}
t|dd |
d< t j	|d	|
}| j
||||||dS )aI  Add a local file to the artifact.

        Args:
            local_path: The path to the file being added.
            name: The path within the artifact to use for the file being added. Defaults
                to the basename of the file.
            is_tmp: If true, then the file is renamed deterministically to avoid
                collisions.
            skip_cache: If `True`, W&B will not copy files to the cache after uploading.
            policy: By default, set to "mutable". If set to "mutable", create a temporary copy of the
                file to prevent corruption during upload. If set to "immutable", disable
                protection and rely on the user not to delete or change the file.
            overwrite: If `True`, overwrite the file if it already exists.

        Returns:
            The added manifest entry.

        Raises:
            ArtifactFinalizedError: You cannot make changes to the current artifact
            version because it is finalized. Log a new artifact version instead.
            ValueError: Policy must be "mutable" or "immutable"
        zPath is not a file: .N   r   )r  rt  rs  ru  )rx  ry  isfilerW   r>   basenamer;   r   r:   r   _add_local_file)r   r  rE   r  rt  rs  ru  r  	file_path	file_namefile_name_partsr   r   r   r    s"    
zArtifact.add_filec              	     s
  t j|std|tdt jdt j|dd t }g }t j	|ddD ]+\}}}	|	D ]#}
t j||
}t jj
||d}|d	urOt j||}|||f q3q,d fdd}d}tj|}||| |  |  tdt |  dd d	S )a  Add a local directory to the artifact.

        Args:
            local_path: The path of the local directory.
            name: The subdirectory name within an artifact. The name you specify appears
                in the W&B App UI nested by artifact's `type`.
                Defaults to the root of the artifact.
            skip_cache: If set to `True`, W&B will not copy/move files to the cache while uploading
            policy: "mutable" | "immutable". By default, "mutable"
                "mutable": Create a temporary copy of the file to prevent corruption during upload.
                "immutable": Disable protection, rely on the user not to delete or change the file.

        Raises:
            ArtifactFinalizedError: You cannot make changes to the current artifact
            version because it is finalized. Log a new artifact version instead.
            ValueError: Policy must be "mutable" or "immutable"
        zPath is not a directory: {}z%Adding directory to artifact ({})... r  F)newlineT)followlinksstartNlog_phy_pathtuple[str, str]rO   rP   c                   s   | \}}j || d d S )N)rE   ry  rt  rs  )r  )r  logical_pathphysical_pathrs  r   rt  r   r   add_manifest_file  s   
z+Artifact.add_dir.<locals>.add_manifest_file   zDone. %.1fsprefix)r  r  rO   rP   )rx  ry  isdirrW   r   r   r   normpathtimewalkrelpathr   multiprocessingdummyPoolmapclose)r   r  rE   rt  rs  
start_timepathsdirpathr   	filenamesfnamer  r  r  num_threadspoolr   r  r   add_dir  s2   	zArtifact.add_dirTuriArtifactManifestEntry | strStrPath | Nonechecksummax_objectsSequence[ArtifactManifestEntry]c           	      C  s   |durt |}t|tr| }nt|tr|}tt|}|js&td| jj	| t
||||d}|D ]}| j| q5|S )a'  Add a reference denoted by a URI to the artifact.

        Unlike files or directories that you add to an artifact, references are not
        uploaded to W&B. For more information,
        see [Track external files](https://docs.wandb.ai/guides/artifacts/track-external-files).

        By default, the following schemes are supported:

        - http(s): The size and digest of the file will be inferred by the
          `Content-Length` and the `ETag` response headers returned by the server.
        - s3: The checksum and size are pulled from the object metadata. If bucket
          versioning is enabled, then the version ID is also tracked.
        - gs: The checksum and size are pulled from the object metadata. If bucket
          versioning is enabled, then the version ID is also tracked.
        - https, domain matching `*.blob.core.windows.net` (Azure): The checksum and size
          are be pulled from the blob metadata. If storage account versioning is
          enabled, then the version ID is also tracked.
        - file: The checksum and size are pulled from the file system. This scheme
          is useful if you have an NFS share or other externally mounted volume
          containing files you wish to track but not necessarily upload.

        For any other scheme, the digest is just a hash of the URI and the size is left
        blank.

        Args:
            uri: The URI path of the reference to add. The URI path can be an object
                returned from `Artifact.get_entry` to store a reference to another
                artifact's entry.
            name: The path within the artifact to place the contents of this reference.
            checksum: Whether or not to checksum the resource(s) located at the
                reference URI. Checksumming is strongly recommended as it enables
                automatic integrity validation. Disabling checksumming will speed up
                artifact creation but reference directories will not iterated through so the
                objects in the directory will not be saved to the artifact. We recommend
                setting `checksum=False` when adding reference objects, in which case
                a new version will only be created if the reference URI changes.
            max_objects: The maximum number of objects to consider when adding a
                reference that points to directory or bucket store prefix. By default,
                the maximum number of objects allowed for Amazon S3,
                GCS, Azure, and local files is 10,000,000. Other URI schemas do not have a maximum.

        Returns:
            The added manifest entries.

        Raises:
            ArtifactFinalizedError: You cannot make changes to the current artifact
            version because it is finalized. Log a new artifact version instead.
        Nz?References must be URIs. To reference a local file, use file://)rE   r  r  )r>   r  r%   ref_urlrF   r   schemerW   r_   store_referencer@   r   	add_entry)	r   r  rE   r  r  uri_strurlmanifest_entriesr  r   r   r   add_reference  s*   8


zArtifact.add_referencer   r?   c                 C  s.  t |}|d}tjtjtjtjtjtjtj	tj
tjtjtjtjtjtjf}t||s7td|j d| t|}|| jv rG| j| d S | }|dur\| |t||d S || }||}| j|}	|st|	durt|	S |rtj| j j!t"t| |}
tj#|
\}}tj$|dd t%|
d	d
d}t&j'||dd W d   n1 sw   Y  n)|rd	nd}| j(||d
d}t&j'||dd |j!}
W d   n1 sw   Y  | )|
||}	||	f| j|< |j*du r|+| |	j |rt,-t. t/|
 W d   |	S 1 sw   Y  |	S )a  Add wandb.WBValue `obj` to the artifact.

        Args:
            obj: The object to add. Currently support one of Bokeh, JoinedTable,
                PartitionedTable, Table, Classes, ImageMask, BoundingBoxes2D, Audio,
                Image, Video, Html, Object3D
            name: The path within the artifact to add the object.
            overwrite: If True, overwrite existing objects with the same file path (if applicable).

        Returns:
            The added manifest entry

        Raises:
            ArtifactFinalizedError: You cannot make changes to the current artifact
            version because it is finalized. Log a new artifact version instead.
        zmedia/tableszFound object of type z, expected one of:    Nr   T)exist_okwzutf-8)rp  )	sort_keysrn  )ro  rp  )0r>   rX   r   BokehJoinedTablePartitionedTableTableClasses	ImageMaskBoundingBoxes2DAudioImageVideoHtmlObject3DMolecule_SavedModelr  rW   	__class__r   ra   _get_artifact_entry_ref_urlr  rG   with_suffixto_jsonr   get_entry_by_pathrx  ry  r   _TMP_DIRrE   rF   r   makedirsopenr   dumpr  r  _artifact_target_set_artifact_target
contextlibsuppressFileNotFoundErrorremove)r   r   rE   ru  is_tmp_nameallowed_typesobj_idref_pathvalr  r  folder_pathr   tmp_ffilemoder  r   r   r   rl  J  sp   






zArtifact.addry  r  B64MD5 | Nonec                 C  s   |pd}|dvrt d|d|}|dkr@tjt dd}|j}	t||	 t|	t	j
 |	}W d    n1 s;w   Y  t||pGt|tj|||d}
| jj|
|d |
| jt|< |
S )	Nr  )r  rr  zInvalid policy z.. Policy may only be `mutable` or `immutable`.F)dirdelete)ry  r  r  r  rt  )ru  )rW   rv  NamedTemporaryFiler+   rE   shutilcopyfilerx  chmodstatS_IRUSRr%   r;   ry  getsizer   r  rb   fspath)r   rE   ry  r  rt  rs  ru  upload_pathr  staging_pathr  r   r   r   r    s.   	


zArtifact._add_local_fileStrPath | ArtifactManifestEntryc                 C  s~   t |tr| j| dS tt|}| j|}|r#| j| dS | j|}|s2td| |D ]}| j| q4dS )a  Remove an item from the artifact.

        Args:
            item: The item to remove. Can be a specific manifest entry or the name of an
                artifact-relative path. If the item matches a directory all items in
                that directory will be removed.

        Raises:
            ArtifactFinalizedError: You cannot make changes to the current artifact
            version because it is finalized. Log a new artifact version instead.
            FileNotFoundError: If the item isn't found in the artifact.
        NzNo such file or directory: )	r  r%   r   remove_entryrF   r   r  get_entries_in_directoryr  )r   rk  ry  r  r  r   r   r   r    s   
zArtifact.removec                 C  s   t tjdd | |S )z"Deprecated. Use `get_entry(name)`.zLArtifact.get_path(name) is deprecated, use Artifact.get_entry(name) instead.)
field_namewarning_message)r8   r7   artifact__get_path	get_entryri  r   r   r   get_path  s
   
zArtifact.get_pathc                 C  sD   t |}| jj|p| |d }|du rtd|| |_|S )aY  Get the entry with the given name.

        Args:
            name: The artifact relative name to get

        Returns:
            A `W&B` object.

        Raises:
            ArtifactNotLoggedError: if the artifact isn't logged or the run is offline.
            KeyError: if the artifact doesn't contain an entry with the given name.
        r   Nz"Path not contained in artifact: {})r>   r   r  r   _get_obj_entryKeyErrorr   _parent_artifact)r   rE   r  r   r   r   r    s   zArtifact.get_entryc                 C  s   |  |\}}|du s|du rdS | }|r5| jdusJ | j|| jd}|dus,J |t|jS |tj	kr>| 
  | |j}|
 }d}i }	t|}
t|
}	W d   n1 s`w   Y  ||	| }|| | |S )af  Get the WBValue object located at the artifact relative `name`.

        Args:
            name: The artifact relative name to retrieve.

        Returns:
            W&B object that can be logged with `wandb.log()` and visualized in the W&B UI.

        Raises:
            ArtifactNotLoggedError: if the artifact isn't logged or the run is offline
        N)r   )r  _referenced_artifact_idrY   r   r   r   uri_from_pathrefr2  r  downloadr  ry  r  r   load	from_json_set_artifact_source)r   rE   r  wb_classreferenced_idr   rk  	item_pathrA  json_objr   r   r   r   r     s*   

zArtifact.getc                 C  s    | j |d}|du rdS |jS )zGet the artifact relative name of a file added by a local filesystem path.

        Args:
            local_path: The local path to resolve into an artifact relative name.

        Returns:
            The artifact relative name.
        N)rb   r   ry  )r   r  r  r   r   r   get_added_local_path_name3  s   	z"Artifact.get_added_local_path_name?tuple[ArtifactManifestEntry, Type[WBValue]] | tuple[None, None]c                 C  sB   t   D ]}||}| jj|}|dur||f  S qdS )a  Return an object entry by name, handling any type suffixes.

        When objects are added with `.add(obj, name)`, the name is typically changed to
        include the suffix of the object type when serializing to JSON. So we need to be
        able to resolve a name, without tasking the user with appending .THING.json.
        This method returns an entry if it exists by a suffixed name.

        Args:
            name: name used when adding
        NNN)r   type_mappingr  r  r   r  r   )r   rE   r  wandb_file_namer  r   r   r   r  A  s   
zArtifact._get_obj_entryrootallow_missing_referencespath_prefixr=   c                 C  sH   t t|p|  }| | t st rtd| j	||||dS )aj  Download the contents of the artifact to the specified root directory.

        Existing files located within `root` are not modified. Explicitly delete `root`
        before you call `download` if you want the contents of `root` to exactly match
        the artifact.

        Args:
            root: The directory W&B stores the artifact's files.
            allow_missing_references: If set to `True`, any invalid reference paths
                will be ignored while downloading referenced files.
            skip_cache: If set to `True`, the artifact cache will be skipped when
                downloading and W&B will download each file into the default root or
                specified download directory.
            path_prefix: If specified, only files with a path that starts with the given
                prefix will be downloaded. Uses unix format (forward slashes).

        Returns:
            The path to the downloaded contents.

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
            RuntimeError: If the artifact is attempted to be downloaded in offline mode.
        z*Cannot download artifacts in offline mode.r  r  rt  r  )
r=   rF   _default_root_add_download_rootr   
is_offliner   _is_offlineRuntimeError	_download)r   r  r  rt  r  r   r   r   r  W  s   

zArtifact.downloadc                 C  s  dd l }ddlm} tjd u rvddlm} | }|d usJ t }	|j	
 }
|t }t||
j_t||	 d |
j_t|d |
j_|	|
j_|j}|sRJ |j|
|	d t }||j	||d}|  |jsmJ |	|j_|  n
tjjs|J tjj}|jsJ |j| j||||}| j||||d |jd	d
}|d u r|   |d usJ |j!j"}|j#rt$d|j# t%|S )Nr   )Backend)wandb_setupz.wandbfiles)r%  run_id)r%  servicemailboxr  )r:  zError downloading artifact: )&pathlibwandb.sdk.backend.backendr  r2  r-  	wandb.sdkr  setuprA   r%  to_protoPathrv  mkdtemprF   sync_dirr  	sync_file	files_dirr  r  inform_initr<   ensure_launched	interface
_stream_idenable_keepalive_backenddeliver_download_artifactr   r  r<  abandonr   download_artifact_responser?  rW   r=   )r   r  r  rt  r  r   r  r  wl	stream_idr%  tmp_dirr  r  backendhandlerA  r   r   r   r   _download_using_core  sd   




zArtifact._download_using_corec                   s,  t | jj}tdd | jj D }d}|dks|dkr/d}td| j|d | t	 }t
|d	d$ fdd}	t|	tjtjtjd}
tjd}t }d}d }|rt }| ||}|d d }|d d }|d D ]%}| |d d }|d d |_|r|jt|r|||
| qs|}t ||krtj|D ]}|  | | t ||kr nq|sYtj|D ]}|  qW d    n1 sw   Y  |rt	 }t!|| " }t#|d }t#||d  d }||d  |d  }td | d!| d!|d"dd# t$S )%Nc                 s  s    | ]}|j pd V  qdS )r   N)r  )r   r  r   r   r   	<genexpr>  s    z%Artifact._download.<locals>.<genexpr>F  i   Tz5Downloading large artifact {}, {:.2f}MB. {} files... i   )nfilesr  r%   api_keyrI   cookiesdict | NoneheadersrO   rP   c              
     s   |t _|t _|t _z	| jd W n6 ty/ } z r*tt| W Y d }~d S  d }~w t	yH } zt
t| W Y d }~d S d }~ww   d S )N)rt  )r2   r<  r=  r?  r  r  r2  r   rF   r,   loggerdebugnotify_downloaded)r  r<  r=  r?  r  r  download_loggerr  rt  r   r   _download_entry  s"   z+Artifact._download.<locals>._download_entry)r<  r=  r?  @   pageInfohasNextPage	endCursoredgesnoderE   r   i  <   zDone. r   z.1fr  )
r  r%   r<  rI   r=  r>  r?  r>  rO   rP   )%r   r   r  sumr  r   r   rE   r   nowr"   r   r2   r<  r=  r?  
concurrentfuturesThreadPoolExecutorrd   r   &get_artifact_fetch_file_url_batch_size_fetch_file_urlsr  _download_urlry  rX   rF   rl  submitas_completedrA  r  absr  r  r=   )r   r  r  rt  r  r;  r  logr  rE  download_entryexecutoractive_futureshas_next_pagecursorfetch_url_batch_sizer   edger  max_backlogfuturerN  deltahoursminutesr	  r   rC  r   r    st   


zArtifact._download   )rd  )retry_timedeltaretryable_exceptionsr:  r]  per_pager
   c                 C  s>   t d}| jd usJ | jj|| j||ddd}|d d S )NaH  
            query ArtifactFileURLs($id: ID!, $cursor: String, $perPage: Int) {
                artifact(id: $id) {
                    files(after: $cursor, first: $perPage) {
                        pageInfo {
                            hasNextPage
                            endCursor
                        }
                        edges {
                            node {
                                name
                                directUrl
                            }
                        }
                    }
                }
            }
            )r   r]  perPagerL  )r   r:  r   r  rB   rY   r   r   )r   r]  rh  r   r   r   r   r   rS  3  s   zArtifact._fetch_file_urlsc              
   C  s   |p| j dd}t|D ].\}}}|D ]&}tj||}tjj||d}z| | W q ty:   t| Y qw q| j	|dS )a  Replace the specified root directory with the contents of the artifact.

        WARNING: This will delete all files in `root` that are not included in the
        artifact.

        Args:
            root: The directory to replace with this artifact's files.

        Returns:
           The path of the checked out contents.

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
        F)include_versionr  )r  )
r  rx  r  ry  r   r  r  r  r  r  )r   r  r  r   r  r   	full_pathartifact_pathr   r   r   checkoutT  s   	zArtifact.checkoutc           
   
   C  s   |p|   }t|D ]0\}}}|D ](}tj||}tjj||d}z| | W q ty:   td	|| j
w qd}| jj D ]!}	|	jdu rattj||	j|	jkr`td	|	jqD|d7 }qD|dkrstd	| dS dS )a  Verify that the contents of an artifact match the manifest.

        All files in the directory are checksummed and the checksums are then
        cross-referenced against the artifact's manifest. References are not verified.

        Args:
            root: The directory to verify. If None artifact will be downloaded to
                './artifacts/self.name/'

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
            ValueError: If the verification fails.
        r  z2Found file {} which is not a member of artifact {}r   NzDigest mismatch for file: {}r  z(Warning: skipped verification of {} refs)r  rx  r  ry  r   r  r  r  rW   r   rE   r   r  r  r  r;   r  print)
r   r  r  r   r  r   rl  rm  	ref_countr  r   r   r   verifyr  s2   

zArtifact.verifyc                 C  sN   |du rt jdd| j}t| jjdkrtd| t	| jjd 
|S )a  Download a single file artifact to the directory you specify with `root`.

        Args:
            root: The root directory to store the file. Defaults to
                './artifacts/self.name/'.

        Returns:
            The full path of the downloaded file.

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
            ValueError: If the artifact contains more than one file.
        Nr  	artifactsr  zxThis artifact contains more than one file, call `.download()` to get all files or call .get_entry("filename").download()r   )rx  ry  r   rE   r   r   r  rW   r  listr  )r   r  r   r   r   r     s   zArtifact.file2   nameslist[str] | Noner   c                 C  s   t | j| ||S )a  Iterate over all files stored in this artifact.

        Args:
            names: The filename paths relative to the root of the artifact you wish to
                list.
            per_page: The number of files to return per request.

        Returns:
            An iterator containing `File` objects.

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
        )r   rY   )r   ru  rh  r   r   r   r    s   zArtifact.filesrk  c                 C  sL   |r| j n| j dd }tjt |}t|pt	|}t
t|S )Nr   r   )r   r   rx  ry  r   r   get_artifact_dirr3   check_existssystem_preferred_pathr=   rF   )r   rk  rE   r  ry  r   r   r   r    s   zArtifact._default_rootdir_pathc                 C  s   | j tj| d S r  )re   rl  rx  ry  abspath)r   rz  r   r   r   r    s   zArtifact._add_download_rootr  c                 C  sn   t j|}|t j}tt|d D ] }t jjt jg|d| R  | jv r4t jj||d    S qdS )z:Convert a local file path to a path entry in the artifact.r  N)	rx  ry  r{  r   sepranger   r   re   )r   r  abs_file_pathabs_file_partsir   r   r   _local_path_to_name  s   $zArtifact._local_path_to_namedelete_aliasesc                 C  s$   | j  r| | dS |   dS )ab  Delete an artifact and its files.

        If called on a linked artifact (i.e. a member of a portfolio collection): only the link is deleted, and the
        source artifact is unaffected.

        Args:
            delete_aliases: If set to `True`, deletes all aliases associated with the artifact.
                Otherwise, this raises an exception if the artifact has existing
                aliases.
                This parameter is ignored if the artifact is linked (i.e. a member of a portfolio collection).

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
        N)r   is_sequence_delete_unlink)r   r  r   r   r   r    s   
zArtifact.deletec                 C  s2   t d}| jd usJ | jj|| j|dd d S )Nai  
            mutation DeleteArtifact($artifactID: ID!, $deleteAliases: Boolean) {
                deleteArtifact(input: {
                    artifactID: $artifactID
                    deleteAliases: $deleteAliases
                }) {
                    artifact {
                        id
                    }
                }
            }
            )rI  deleteAliasesr   rj  )r   r  rf  r   r   r   r    s   
zArtifact._deletetarget_pathc                 C  sp   t jdu r.t j| j| jdt jddd}|| || W d   dS 1 s'w   Y  dS t j| || dS )a_  Link this artifact to a portfolio (a promoted collection of artifacts).

        Args:
            target_path: The path to the portfolio inside a project.
                The target path must adhere to one of the following
                schemas `{portfolio}`, `{project}/{portfolio}` or
                `{entity}/{project}/{portfolio}`.
                To link the artifact to the Model Registry, rather than to a generic
                portfolio inside a project, set `target_path` to the following
                schema `{"model-registry"}/{Registered Model Name}` or
                `{entity}/{"model-registry"}/{Registered Model Name}`.
            aliases: A list of strings that uniquely identifies the artifact inside the
                specified portfolio.

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
        Nr*  r'  r(  r+  )r2  r-  r4  rn   ro   r3  link_artifact)r   r  r   r-  r   r   r   link  s   

"zArtifact.linkc                 C  s2   | j  rtd| jd| jjd|   dS )a,  Unlink this artifact if it is currently a member of a portfolio (a promoted collection of artifacts).

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
            ValueError: If the artifact is not linked, i.e. it is not a member of a portfolio collection.
        z	Artifact zE is not a linked artifact and cannot be unlinked.  To delete it, use z	 instead.N)r   r  rW   r   r  r=  r  r   r   r   r   unlink*  s   
	
zArtifact.unlinkc                 C  s6   t d}| jd usJ | jj|| j| jjdd d S )Nav  
            mutation UnlinkArtifact($artifactID: ID!, $artifactPortfolioID: ID!) {
                unlinkArtifact(
                    input: { artifactID: $artifactID, artifactPortfolioID: $artifactPortfolioID }
                ) {
                    artifactID
                    success
                    clientMutationId
                }
            }
            )rI  artifactPortfolioIDr   )rB   rY   r   r   r   )r   rf  r   r   r   r  ;  s   
zArtifact._unlink	list[Run]c                   sV   t d} jdusJ  jj|d jid} fdd|di di d	g D S )
zGet a list of the runs that have used this artifact.

        Returns:
            A list of `Run` objects.

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
        a  
            query ArtifactUsedBy(
                $id: ID!,
            ) {
                artifact(id: $id) {
                    usedBy {
                        edges {
                            node {
                                name
                                project {
                                    name
                                    entityName
                                }
                            }
                        }
                    }
                }
            }
            Nr   r   c                   s<   g | ]}t  j|d  d d |d  d d |d  d qS )rK  r   r   rE   )r   rY   )r   r_  r   r   r   r   w  s    
z$Artifact.used_by.<locals>.<listcomp>r   usedByrJ  )rB   rY   r   r   r   )r   r   r   r   r   r   used_byS  s   

zArtifact.used_by
Run | Nonec                 C  sv   t d}| jdusJ | jj|d| jid}|di di }|ddu r)dS t| j|d d	 |d d |d S )
zGet the W&B run that originally logged the artifact.

        Returns:
            The name of the W&B run that originally logged the artifact.

        Raises:
            ArtifactNotLoggedError: If the artifact is not logged.
        a  
            query ArtifactCreatedBy(
                $id: ID!
            ) {
                artifact(id: $id) {
                    createdBy {
                        ... on Run {
                            name
                            project {
                                name
                                entityName
                            }
                        }
                    }
                }
            }
        Nr   r   r   	createdByrE   r   r   )rB   rY   r   r   r   r   )r   r   r   creatorr   r   r   	logged_by  s"   


zArtifact.logged_byc                 C  s
   t | S )zReturns the artifact encoded to the JSON format.

        Returns:
            A `dict` with `string` keys representing attributes of the artifact.
        )r   artifact_to_jsonr   r   r   r   json_encode  r  zArtifact.json_encoder   r   c                 C  sV   t d}d|vr|d7 }|j|| ||dd}|dpi dp"i dp'i d	S )
z@Returns the expected type for a given artifact name and project.a  
            query ArtifactType(
                $entityName: String,
                $projectName: String,
                $name: String!
            ) {
                project(name: $projectName, entityName: $entityName) {
                    artifact(name: $name) {
                        artifactType {
                            name
                        }
                    }
                }
            }
            r   z:latestr   r   r   r   r   rE   )rB   r   r   )r   r   rE   r   r   r   r   r   r   _expected_type  s    	zArtifact._expected_typec              	   C  sL   | d u ri S t | tstdt|  ttttf t	t
t| S )Nzmetadata must be dict, not )r  r  r   rG   r   r   rF   r
   r   r   dumpsr   json_friendly_val)rJ   r   r   r   rt     s   
zArtifact._normalize_metadatar  c                 C  sD   t |}|  t| W  d    S 1 sw   Y  d S r  )requestsr   raise_for_statusr$   r   r   )r   r  r   r   r   r   r     s   $zArtifact._load_manifestc                 C  s&   d}d}| j s	d S | jr|S | jp|S )Nr  )rx   rw   rv   )r   r  DISABLEDr   r   r   r[    s   
z%Artifact._ttl_duration_seconds_to_gql)NNFN)rE   rF   rG   rF   rH   rI   rJ   rK   rL   rM   rN   rI   rO   rP   rO   rF   )r   rF   r   r   rO   r   )r   rF   r   rF   rE   rF   r   r   r   rM   rO   rD   )r   rF   r   rF   rE   rF   r   r   r   r   rO   rD   )r   r   rO   rP   )rO   rD   )rO   rI   )rO   r   )rH   rI   rO   rP   )rO   r  )rJ   r  rO   rP   )rO   r  )r  r  rO   rP   )rO   r  )r   r  rO   rP   )r   r  rO   rP   )r  rI   rO   rP   )rO   rM   )rO   r$   )rO   r  )rO   rP   r  )r   rI   r%  r&  rO   rP   )r8  rC   r   r   rO   rP   r  )r:  r;  rO   rD   )r   rF   rO   rP   )rE   rF   rO   rh  )rE   rF   rk  r   rO   r%   )rn  N)rE   rF   ro  rF   rp  rI   rO   rq  )NFFr  F)r  rF   rE   rI   r  r  rt  r  rs  r  ru  rM   rO   r%   )NFr  )
r  rF   rE   rI   rt  r  rs  r  rO   rP   )NTN)
r  r  rE   r  r  rM   r  r;  rO   r  )F)r   r   rE   r?   ru  rM   rO   r%   )NFr  F)rE   r?   ry  r?   r  r  rt  r  rs  r  ru  rM   rO   r%   )rk  r  rO   rP   )rE   r?   rO   r%   )r  rF   rO   rI   )rE   rF   rO   r  )NFNN)
r  r  r  rM   rt  r  r  r  rO   r=   )FFN)
r  rF   r  rM   rt  rM   r  r  rO   r=   )FNN)
r  rF   r  rM   rt  r  r  r  rO   r=   )r:  )r]  rI   rh  r;  rO   r
   )r  rI   rO   rF   )r  rI   rO   rP   )r  rI   rO   r?   )Nrt  )ru  rv  rh  r  rO   r   )T)rk  rM   rO   r=   )rz  rF   rO   rP   )r  rF   rO   rI   )r  rM   rO   rP   )r  rF   r   rv  rO   rP   )rO   r  )rO   r  )rO   r   )
r   rF   r   rF   rE   rF   r   r   rO   rI   )rJ   rK   rO   r   )r  rF   rO   r$   )rO   r;  )jr
  
__module__r=  __doc__rv  rw  r  atexitregistercleanupr   r   classmethodr   r   r   r   r   r   propertyr   r   r   rE   r   r   r   r   r  r   r  r  r  rG   rH   setterrJ   r  r   r   r  rL   rN   r   r   r  r  r   r!  r"  r#  r   r   r$  r7  r9  r<  r@  r   r.  rj  rm  r  contextmanagerr   r  r  r  r  rl  r  r  r  r  r   r
  r  r  r8  r  r4   	retriabler   r  RequestExceptionrS  rn  rq  r   r  r  r  r  r  r  r  r  r  r  r  r  staticmethodr  rt   r   r[  r   r   r   r   rD   L   s   
K 5[""
)
) C)4=R`".7O['	-+$	rD   gql_ttl_duration_secondsr;  rO   c                 C  s   | r| dkr| S d S )Nr   r   )r  r   r   r   r     s   r   rF   c                  C  sZ   t t  } d| v }d| v }|rdnd}|rdnd}|rdnd}d| d| d| d	S )
zGReturn a GraphQL query fragment with all parseable Artifact attributes.r   r   r   r   ztags {name}av  
        fragment ArtifactFragment on Artifact {
            id
            artifactSequence {
                project {
                    entityName
                    name
                }
                name
            }
            versionIndex
            artifactType {
                name
            }
            description
            metadata
            r   a  
            aliases {
                artifactCollection {
                    project {
                        entityName
                        name
                    }
                    name
                }
                alias
            }
            z
            state
            currentManifest {
                file {
                    directUrl
                }
            }
            commitHash
            fileCount
            createdAt
            updatedAt
        }
    )rd   r   rY  )allowed_fieldssupports_ttlsupports_tagsttl_duration_secondsttl_is_inheritedr   r   r   r   r    	  s   r   c                   @  s   e Zd ZdZegZdS )_ArtifactVersionTypeartifactVersionN)r
  r  r=  rE   rD   typesr   r   r   r   r  7	  s    
r  )r  r;  rO   r;  r  )r  
__future__r   r  concurrent.futuresrO  r  r   loggingmultiprocessing.dummyr  rx  rU   r  r  rv  r  r   r   r   	functoolsr   r   r   typingr   r	   r
   r   r   r   r   r   r   urllib.parser   r  r2  r   r   r   wandb.apis.normalizer   wandb.apis.publicr   r   r   r   wandb.data_typesr   wandb.errors.termr   r   r   wandb.sdk.artifacts._validatorsr   r   r    r!   ,wandb.sdk.artifacts.artifact_download_loggerr"   +wandb.sdk.artifacts.artifact_instance_cacher#   %wandb.sdk.artifacts.artifact_manifestr$   +wandb.sdk.artifacts.artifact_manifest_entryr%   ;wandb.sdk.artifacts.artifact_manifests.artifact_manifest_v1r&   "wandb.sdk.artifacts.artifact_stater'    wandb.sdk.artifacts.artifact_ttlr(   wandb.sdk.artifacts.exceptionsr)   r*   wandb.sdk.artifacts.stagingr+   0wandb.sdk.artifacts.storage_handlers.gcs_handlerr,   "wandb.sdk.artifacts.storage_layoutr-   $wandb.sdk.artifacts.storage_policiesr.   "wandb.sdk.artifacts.storage_policyr/   wandb.sdk.data_types._dtypesWBTyper0   wandb.sdk.internal.internal_apir1   r   (wandb.sdk.internal.thread_local_settingsr2   wandb.sdk.libr3   r4   r5   r6   wandb.sdk.lib.deprecater7   r8   wandb.sdk.lib.hashutilr9   r:   r;   wandb.sdk.lib.mailboxr<   wandb.sdk.lib.pathsr=   r>   r?   r@   wandb.sdk.lib.runidrA   vendor_setup
reset_path	wandb_gqlrB   	getLoggerr
  r@  "wandb.sdk.interface.message_futurerC   rD   r   r   r  rl  r   r   r   r   <module>   s    ,
                 
=
7