o
    wiN                     @  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	m
Z
mZmZ ddlmZmZmZ ddlmZ ddlZddlm  m  mZ ddlmZmZ ddlmZ dd	lmZ dd
lmZ ddlm Z! ddl"m#Z# 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/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 erddl7Z8ddl9Z:ddl;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZB ddhZCdZDdZEdZFdZGd6d%d&ZHe#d7d)d*ZIe#d7d+d,ZJe#d8d0d1ZKG d2d3 d3e%d4 ZLG d5d4 d4eZMdS )9aI  W&B Public API for Runs.

This module provides classes for interacting with W&B runs and their associated
data.

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

# Get runs matching filters
runs = Api().runs(
    path="entity/project", filters={"state": "finished", "config.batch_size": 32}
)

# Access run data
for run in runs:
    print(f"Run: {run.name}")
    print(f"Config: {run.config}")
    print(f"Metrics: {run.summary}")

    # Get history with pandas
    history_df = run.history(keys=["loss", "accuracy"], pandas=True)

    # Work with artifacts
    for artifact in run.logged_artifacts():
        print(f"Artifact: {artifact.name}")
```

Note:
    This module is part of the W&B Public API and provides read/write access
    to run data. For logging new runs, use the wandb.init() function from
    the main wandb package.
    )annotationsN)
CollectionIteratorMapping)TYPE_CHECKINGAnyLiteral)gql)envutil)nameof)public)Attrs)Api)normalize_exceptions)SizedPaginator)RETRY_TIMEDELTA)
ServiceApi)wandb_api_pb2)wandb_setup)ipython	json_utilrunid)LogicalPath)WandbApiFailedError)Self)Document)RetryingClientHTTPSummary_wandbwandb_versionaJ  fragment RunFragment on Run {
    id
    tags
    name
    displayName
    sweepName
    state
    config
    group
    jobType
    commit
    readOnly
    createdAt
    heartbeatAt
    description
    notes
    systemMetrics
    summaryMetrics
    historyLineCount
    user {
        name
        username
    }
    historyKeys
}a  fragment LightweightRunFragment on Run {
    id
    tags
    name
    displayName
    sweepName
    state
    group
    jobType
    commit
    readOnly
    createdAt
    heartbeatAt
    description
    notes
    historyLineCount
    user {
        name
        username
    }
}RunFragmentLightweightRunFragmentlazyboolwith_internal_idwith_project_idreturnr	   c              
   C  sJ   | rt nt}| r
tnt}td|rdnd d|rdnd d| d| d	S )	z8Create GraphQL query for runs with appropriate fragment.z#graphql
        query Runs($project: String!, $entity: String!, $cursor: String, $perPage: Int = 50, $order: String, $filters: JSONString) {
            project(name: $project, entityName: $entity) {
                
internalId z
                runCount(filters: $filters)
                readOnly
                runs(filters: $filters, after: $cursor, first: $perPage, order: $order) {
                    edges {
                        node {
                            	projectIdz 
                            ...z
                        }
                        cursor
                    }
                    pageInfo {
                        endCursor
                        hasNextPage
                    }
                }
            }
        }
        	
        )LIGHTWEIGHT_RUN_FRAGMENTRUN_FRAGMENTLIGHTWEIGHT_RUN_FRAGMENT_NAMERUN_FRAGMENT_NAMEr	   )r$   r&   r'   fragmentfragment_name r3   J/home/ubuntu/.local/lib/python3.10/site-packages/wandb/apis/public/runs.py_create_runs_query   s   

	
r5   clientr   c                 C  :   d}t |}| |}ddd |di di gD v S )zQReturns True if the server allows us to query the internalId field for a project.z
       query ProbeProjectInput {
            ProjectType: __type(name:"Project") {
                fields {
                    name
                }
            }
        }
    r)   c                 S     g | ]}|d  qS namer3   .0xr3   r3   r4   
<listcomp>       z<_server_provides_internal_id_for_project.<locals>.<listcomp>ProjectTypefieldsr	   executegetr6   query_stringqueryresr3   r3   r4   (_server_provides_internal_id_for_project      
rI   c                 C  r7   )zLReturns True if the server allows us to query the projectId field for a run.z
       query ProbeRunInput {
            RunType: __type(name:"Run") {
                fields {
                    name
                }
            }
        }
    r+   c                 S  r8   r9   r3   r;   r3   r3   r4   r>      r?   z7_server_provides_project_id_for_run.<locals>.<listcomp>RunTyperA   rB   rE   r3   r3   r4   #_server_provides_project_id_for_run   rJ   rL   valuer   dict[str, Any]c                 C  sl   | du ri S t | tr| S t | tttfr.zt| W S  tjjy-   tj| dd Y S w t	d|  d)zConverts a value to a dictionary.

    If the value is already a dictionary, the value is returned unchanged.
    If the value is a string, bytes, or bytearray, it is parsed as JSON.
    For any other type, a TypeError is raised.
    NF)strictzUnable to convert z
 to a dict)

isinstancedictstrbytes	bytearrayjsonloadsdecoderJSONDecodeError	TypeError)rM   r3   r3   r4   _convert_to_dict   s   
rZ   c                      s   e Zd ZdZ						d4d5 fddZed6ddZed7ddZedd Zd8dd Z	e
	!		"	#	#d9d:d-d.Zd;d/d0Zd<d2d3Z  ZS )=Runsa=  A lazy iterator of `Run` objects associated with a project and optional filter.

    Runs are retrieved in pages from the W&B server as needed.

    This is generally used indirectly using the `Api.runs` namespace.

    Args:
        client: (`wandb.apis.public.RetryingClient`) The API client to use
            for requests.
        entity: (str) The entity (username or team) that owns the project.
        project: (str) The name of the project to fetch runs from.
        filters: (Optional[Dict[str, Any]]) A dictionary of filters to apply
            to the runs query.
        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) The number of runs to fetch per request (default is 50).
        include_sweeps: (bool) Whether to include sweep information in the
            runs. Defaults to True.
    N+created_at2   Tr6   r   entityrR   projectfiltersdict[str, Any] | Noneorderper_pageintinclude_sweepsr%   r$   service_apiServiceApi | Nonec
                   s   |sd}t |t|t|d| _|| _|| _d | _|pi | _|| _i | _	|| _
|| _|	| _| j| j| jt| jd}
t ||
| d S )Nr\   r$   r&   r'   )r_   r^   rb   r`   )r5   rI   rL   QUERYr^   r_   _project_internal_idr`   rb   _sweeps_include_sweeps_lazy_service_apirU   dumpssuper__init__)selfr6   r^   r_   r`   rb   rc   re   r$   rf   	variables	__class__r3   r4   rq      s,   

zRuns.__init__r(   c                 C  s   | j s|   | j d d S )zUReturns the total number of runs.

        <!-- lazydoc-ignore: internal -->
        r_   runCount)last_response
_load_pagerr   r3   r3   r4   _length#  s   zRuns._lengthc                 C  s$   | j rt| j d d d d S dS )zaReturns whether there are more runs to fetch.

        <!-- lazydoc-ignore: internal -->
        r_   runspageInfohasNextPageT)rw   r%   ry   r3   r3   r4   more-  s
   z	Runs.morec                 C  s$   | j r| j d d d d d S dS )zoReturns the cursor position for pagination of runs results.

        <!-- lazydoc-ignore: internal -->
        r_   r{   edgescursorN)rw   ry   r3   r3   r4   r   :  s   zRuns.cursor	list[Run]c                 C  s   g }| j du s| j ddu rtd| j| j d d d D ]O}t| j| j| j|d d |d | j| j	| j
d}|| | jro|jro|j| jv rR| j|j }ntjj| j| j| j|jd	d
}|| j|j< |du rlq ||_q |S )z[Converts GraphQL edges to Runs objects.

        <!-- lazydoc-ignore: internal -->
        Nr_   zCould not find project {}r{   r   noder:   )re   r$   rf   FwithRuns)rw   rD   
ValueErrorformatr_   Runr6   r^   rl   rm   rn   append
sweep_namerk   r   Sweepsweep)rr   objsrun_responserunr   r3   r3   r4   convert_objectsE  s>   


zRuns.convert_objects  _stepdefaultsampleskeyslist[str] | Nonex_axisr   &Literal['default', 'pandas', 'polars']streamLiteral['default', 'system']2list[dict[str, Any]] | pd.DataFrame | pl.DataFramec                 C  s  |dvrt d| dg }|dkr5| D ]}|j|||d|d}|s#q|D ]}	|j|	d< q%|| q|S |dkr}tjdd	d
}
| D ]}|j|||d|d}|sQqB|
j|}|j|d< || qB|sh|
 S |
	|}|j
ddd |t|j }|S |dkrtjddd
}| D ]%}|j|||d|d}|sq||}|||jd}|| q|s| S |j	|dd}|t|j}|S dS )aQ  Return sampled history metrics for all runs that fit the filters conditions.

        Args:
            samples: The number of samples to return per run
            keys: Only return metrics for specific keys
            x_axis: Use this metric as the xAxis defaults to _step
            format: Format to return data in, options are "default", "pandas",
                "polars"
            stream: "default" for metrics, "system" for machine metrics
        Returns:
            pandas.DataFrame: If `format="pandas"`, returns a `pandas.DataFrame`
                of history metrics.
            polars.DataFrame: If `format="polars"`, returns a `polars.DataFrame`
                of history metrics.
            list of dicts: If `format="default"`, returns a list of dicts
                containing history metrics with a `run_id` key.
        )r   pandaspolarszInvalid format: z.. Must be one of 'default', 'pandas', 'polars'r   F)r   r   r   r   r   run_idr   z*Exporting pandas DataFrame requires pandas)requiredT)dropinplacer   z*Exporting polars DataFrame requires polarsvertical)howN)r   historyidextendr   
get_module	DataFramefrom_recordsr   concatreset_indexsortedcolumnswith_columnslitaliasselect)rr   r   r   r   r   r   	historiesr   history_dataentrypddfcombined_dfplr3   r3   r4   r   m  s   



zRuns.historiesc                 C  s$   dt t|  d| j d| j dS )N< />)r   typer^   r_   ry   r3   r3   r4   __repr__  s   $zRuns.__repr__Nonec                   s   | j sdS d| _ tdt| jt| jd| _dd | jD }|rWddlm} t	t
|d}||d	  fd
d|D }|D ]}|  q>W d   dS 1 sPw   Y  dS dS )a  Upgrade this Runs collection from lazy to full mode.

        This switches to fetching full run data and
        upgrades any already-loaded Run objects to have full data.
        Uses parallel loading for better performance when upgrading multiple runs.
        NFrh   c                 S  s   g | ]}|j r|qS r3   )rm   r<   r   r3   r3   r4   r>         z(Runs.upgrade_to_full.<locals>.<listcomp>r   )ThreadPoolExecutor
   )max_workersc                   s   g | ]}  |jqS r3   )submitload_full_datar   executorr3   r4   r>     s    )rm   r5   rI   r6   rL   ri   objectsconcurrent.futuresr   minlenresult)rr   	lazy_runsr   r   futuresfuturer3   r   r4   upgrade_to_full  s&   
"zRuns.upgrade_to_full)Nr\   r]   TTN)r6   r   r^   rR   r_   rR   r`   ra   rb   rR   rc   rd   re   r%   r$   r%   rf   rg   r(   rd   )r(   r%   )r(   r   )r   Nr   r   r   )r   rd   r   r   r   rR   r   r   r   r   r(   r   r(   rR   r(   r   )__name__
__module____qualname____doc__rq   propertyrz   r~   r   r   r   r   r   r   __classcell__r3   r3   rt   r4   r[      s2    &	


(
dr[   r   c                      s  e Zd ZdZ				dd fddZedddZedddZedddZedddZ	edddZ
e
jdd dZ
edd"d#Zejdd%d#Ze				&ddd,d-Z	.ddd3d4Zdd5d6Zddd7d8Zedd9d:Zedd;d<Zeddd>d?Zdd@dAZeddCdDZeddEdFZddKdLZ	M	NdddUdVZ	N	WdddZd[Ze			\dddbdcZeddfdgZedddkdlZe	N		M		WdddodpZe		q		dddwdxZ eddd{d|Z!eddd}d~Z"e	ddddZ#e		ddddZ$ddddZ%edddZ&edddZ'edddZ(edddZ)edddZ*edddZ+edddZ,edddZ-edddZ.edddZ/ddddZ0dddZ1dddZ2dddZ3		q			ddddZ4	ddddZ5  Z6S )r   ab  A single run associated with an entity and project.

    Args:
        client: The W&B API client.
        entity: The entity associated with the run.
        project: The project associated with the run.
        run_id: The unique identifier for the run.
        attrs: The attributes of the run.
        include_sweeps: Whether to include sweeps in the run.

    Attributes:
        tags ([str]): a list of tags associated with the run
        url (str): the url of this run
        id (str): unique identifier for the run (defaults to eight characters)
        name (str): the name of the run
        state (str): one of: running, finished, crashed, killed, preempting, preempted
        config (dict): a dict of hyperparameters associated with the run
        created_at (str): ISO timestamp when the run was started
        system_metrics (dict): the latest system metrics recorded for the run
        summary (dict): A mutable dict-like property that holds the current summary.
                    Calling update will persist any changes.
        project (str): the project associated with the run
        entity (str): the name of the entity associated with the run
        project_internal_id (int): the internal id of the project
        user (str): the name of the user who created the run
        path (str): Unique identifier [entity]/[project]/[run_id]
        notes (str): Notes about the run
        read_only (boolean): Whether the run is editable
        history_keys (str): History metric keys logged with `wandb.Run.log({"key": "value"})`
        metadata (str): Metadata about the run from wandb-metadata.json
    NTr6   r   r^   rR   r_   r   attrsMapping | Nonere   r%   r$   rf   rg   c	           
        s   |pi }	t  t|	 || _|| _|| _i | _tt	
 | _|| _d| _|| _|| _d| _tjj| jg| jR  | _zt| j W n	 tyM   Y nw d| _d| _|	dd| _d| _d| _d| _|| _| j|	 d dS )zInitialize a Run object.

        Run is always initialized by calling api.runs() where api is an instance of
        wandb.Api.
        NFstatez	not foundforce) rp   rq   rQ   r6   _entityr_   _filesr
   get_dirtempfile
gettempdir	_base_dirr   r   rl   rm   _full_data_loadedospathjoindirmakedirsOSError_summary	_metadatarD   _state!server_provides_internal_id_field!_server_provides_project_id_field
_is_loadedrn   load)
rr   r6   r^   r_   r   r   re   r$   rf   _attrsrt   r3   r4   rq     s4   zRun.__init__r(   c                 C     | j S )zKThe state of the run. Can be one of: Finished, Failed, Crashed, or Running.)r   ry   r3   r3   r4   r   C     z	Run.statec                 C  r   )z#The entity associated with the run.)r   ry   r3   r3   r4   r^   H  r   z
Run.entityc                 C  s   t d | jS )z-This API is deprecated. Use `entity` instead.z:Run.username is deprecated. Please use Run.entity instead.)wandbtermwarnr   ry   r3   r3   r4   usernameM  s   
zRun.usernamec                 C     | j dS )z*The unique storage identifier for the run.r   r   rD   ry   r3   r3   r4   
storage_idS  s   zRun.storage_idc                 C  r   )z"The unique identifier for the run.r:   r   ry   r3   r3   r4   r   [     zRun.idnew_idr   c                 C     || j d< dS )z&Set the unique identifier for the run.r:   Nr   )rr   r   r3   r3   r4   r   `     
str | Nonec                 C  r   )zThe name of the run.displayNamer   ry   r3   r3   r4   r:   e  r   zRun.namenew_namec                 C  r   )zSet the name of the run.r  Nr   )rr   r  r3   r3   r4   r:   j  r  runningapi
public.Apir   Literal['running', 'pending']r   c           	      C  s   |j jddd |pt }|p|jdpd}td}||||d}|jj||d}|d	 d
 }| |j|d d d |d d |d |d dddg dd|dddS )a  Create a run for the given project.

        For most use cases, use `wandb.init()`. `wandb.init()` provides more robust
        logic for creating and updating runs. `wandb.apis.public.Run.create`
        is intended for specific scenarios such as creating runs in
        a "pending" state for jobs that may be unschedulable
        (for example, in a Kubernetes cluster with insufficient GPUs or high
        contention). These pending runs can later be resumed and tracked by W&B.

        Runs created with this method have limited functionality. Calling
        `update()` on a run created this way may not work as expected.

        Args:
            api: The W&B API instance.
            run_id: Optional run ID. If not provided, a random ID will be generated.
            project: Optional project name. Defaults to the project in API settings
                or "uncategorized".
            entity: Optional entity (user or team) name.
            state: Initial state of the run. Use "pending" for runs that will be
                resumed later, or "running" for immediate execution.

        Returns:
            A Run object representing the created run.

        Example:
        Creating a pending run for later execution

        ```python
        import wandb

        api = wandb.Api()

        run_name = "my-pending-run"

        run = Run.create(
            api=api,
            project="project",
            entity="entity",
            state="pending",
            run_id=run_name,
        )
        ```
        zInvoking Run.createinfo)levelr_   uncategorizeda  
        mutation UpsertBucket($project: String, $entity: String, $name: String!, $state: String) {
            upsertBucket(input: {modelName: $project, entityName: $entity, name: $name, state: $state}) {
                bucket {
                    project {
                        name
                        entity { name }
                    }
                    id
                    name
                }
                inserted
            }
        }
        )r^   r_   r:   r   variable_valuesupsertBucketbucketr^   r:   r   z{}N)r   configsystemMetricssummaryMetricstagsdescriptionnotesr   F)r$   )	_sentrymessager   generate_idsettingsrD   r	   r6   rC   )	clsr  r   r_   r^   r   mutationrs   rH   r3   r3   r4   createo  s:   4

z
Run.createFr1   r2   r   rN   c                 C  sb  | j du rt| j| _ td| j rdnd d| d| d}|s#| jsz| |}|du s<|ddu s<|d d	du rCtd
| |d d	 | _| jd | _	| jdrat
| j| jd | _| jrz| jrz| jszt
jj| j| j| j| jdd| _| jr|rd| jv rt| jd | _nd| _|tksd| jv sd| jv sd| jv r|   |tkrd| _| jS )z/Load run data using specified GraphQL fragment.Nz#graphql
        query Run($project: String!, $entity: String!, $name: String!) {
            project(name: $project, entityName: $entity) {
                run(name: $name) {
                    r+   r*   z
                    ...z3
                }
            }
        }
        r,   r_   r   zCould not find run {}r   userFr   r  r  r  T)r   rL   r6   r	   r   _execrD   r   r   r   r   Userr  rl   r   r   r   r^   r_   r   rd   rj   r0   _load_from_attrsr/   )rr   r1   r2   r   rG   responser3   r3   r4   _load_with_fragment  sT   
	






zRun._load_with_fragmentc              	   C  sv  | j dd | _d| j v rt| j d| j d< d| j v r(t| j d| j d< d| j v r8t| j d| j d< | jrV| j drV| jsVtjj| j| j	| j
| j d dd| _i i }}| j drz,| j di  D ] \}}|tv ru|n|}t|trd|v r|d ||< qk|||< qkW n ttfy   Y nw || || j d< || j d	< d
| j v rt| j| j d
 | _| j S )Nr   r  r  r  	sweepNameFr   rM   	rawconfigr  )r   rD   r   rZ   rl   r   r   r   r6   r^   r_   itemsWANDB_INTERNAL_KEYSrP   rQ   rY   AttributeErrorupdater  r  )rr   config_user
config_rawkeyrM   r  r3   r3   r4   r     sJ   












zRun._load_from_attrsc                 C  s0   | j r|   | jr| tt|S | tt|S )z<Load run data using appropriate fragment based on lazy mode.)r   r   rm   r"  r-   r/   r.   r0   )rr   r   r3   r3   r4   r   H  s   zRun.loadc                 C  sL   t d}	 | |}|d d d }|dv r || jd< || _dS td q)	z0Check the state of the run until it is finished.a  
            query RunState($project: String!, $entity: String!, $name: String!) {
                project(name: $project, entityName: $entity) {
                    run(name: $name) {
                        state
                    }
                }
            }
        Tr_   r   r   )finishedcrashedfailedN   )r	   r  r   r   timesleep)rr   rG   rH   r   r3   r3   r4   wait_until_finishedU  s   


zRun.wait_until_finishedc                 C  sH   t dt}| j|| j| j| j| j| j| j	| j
| jd	}| j  dS )z7Persist changes to the run object to the wandb backend.a  
        mutation UpsertBucket($id: String!, $description: String, $display_name: String, $notes: String, $tags: [String!], $config: JSONString!, $groupName: String, $jobType: String) {{
            upsertBucket(input: {{id: $id, description: $description, displayName: $display_name, notes: $notes, tags: $tags, config: $config, groupName: $groupName, jobType: $jobType}}) {{
                bucket {{
                    ...RunFragment
                }}
            }}
        }}
        {}
        )r   r  r  r  display_namer  	groupNamejobTypeN)r	   r   r.   r  r   r  r  r  r3  json_configgroupjob_typesummaryr(  )rr   r  _r3   r3   r4   r(  l  s    	z
Run.updatedelete_artifactsc                 C  s<   t d|rdnd|rdnd}| jj|| j|dd dS )zDelete the given run from the wandb backend.

        Args:
            delete_artifacts (bool, optional): Whether to delete the artifacts
                associated with the run.
        a  
            mutation DeleteRun(
                $id: ID!,
                {}
            ) {{
                deleteRun(input: {{
                    id: $id,
                    {}
                }}) {{
                    clientMutationId
                }}
            }}
        z$deleteArtifacts: Booleanr*   z!deleteArtifacts: $deleteArtifacts)r   deleteArtifactsr  N)r	   r   r6   rC   r   )rr   r;  r  r3   r3   r4   delete  s   


z
Run.deletec                 C  s   |    dS )z5Persist changes to the run object to the W&B backend.N)r(  ry   r3   r3   r4   save  s   zRun.saveLiteral['pending']c              
   C  s   t d}z| jj|d| j|did}W n3 tyG } z't|}d|v s(d|v r.td|d| v rBtd	| j	 d
| d| d}~ww |
di 
dr[|| jd< || _dS dS )a  Update the state of a run.

        Allows transitioning runs from 'failed' or 'crashed' to 'pending'.

        Args:
            state: The target run state. Only `"pending"` is supported.

        Returns:
            `True` if the state was successfully updated.

        Raises:
            `wandb.Error`: If the requested state transition is not allowed, or the server
                does not support this operation.
        z
            mutation UpdateRunState($input: UpdateRunStateInput!) {
                updateRunState(input: $input) {
                    success
                }
            }
            input)r   r   r  UpdateRunStateInputupdateRunStatezThe server does not support the update_state operation. Please ensure your W&B server is updated to a version that supports run state transitions.zinvalid state transitionz2Invalid state transition: cannot change run from 'z' to 'zM'. Only runs in 'failed' or 'crashed' state can be transitioned to 'pending'.Nsuccessr   TF)r	   r6   rC   r   	ExceptionrR   r   Errorlowerr   rD   r   r   )rr   r   r  r   e	error_msgr3   r3   r4   update_state  sH   

	

zRun.update_statec                 C  sN   i }d| j v r| j d dd|d< | j D ]\}}|dd||< qt|S )z[Return the run config as a JSON string.

        <!-- lazydoc-ignore: internal -->
        r    N)rM   desc)r$  r  r%  rU   ro   )rr   r  kvr3   r3   r4   r6    s   

zRun.json_configrG   r   kwargsr   c                 K  s,   | j | j| jd}|| | jj||dS )z*Execute a query against the cloud backend.)r^   r_   r:   r  )r^   r_   r   r(  r6   rC   )rr   rG   rM  rs   r3   r3   r4   r    s   
z	Run._execr   r   r   	list[str]r   r   rd   list[dict[str, Any]]c                 C  sB   |g| |d}t d}| j|t|gd}|d d d d S )N)r   r   a  
        query RunSampledHistory($project: String!, $entity: String!, $name: String!, $specs: [JSONString!]!) {
            project(name: $project, entityName: $entity) {
                run(name: $name) { sampledHistory(specs: $specs) }
            }
        }
        )specsr_   r   sampledHistoryr   )r	   r  rU   ro   )rr   r   r   r   specrG   r!  r3   r3   r4   _sampled_history  s   
zRun._sampled_historyr   r   r   c                 C  sF   |dkrdnd}t d|}| j||d}dd |d d	 | D S )
Nr   r   eventsa   
        query RunFullHistory($project: String!, $entity: String!, $name: String!, $samples: Int) {{
            project(name: $project, entityName: $entity) {{
                run(name: $name) {{ {}(samples: $samples) }}
            }}
        }}
        )r   c                 S  s   g | ]}t |qS r3   )rU   rV   )r<   liner3   r3   r4   r>   "  r   z%Run._full_history.<locals>.<listcomp>r_   r   )r	   r   r  )rr   r   r   r   rG   r!  r3   r3   r4   _full_history  s   
zRun._full_historyr]   namesr   patternrc   public.Filesc                 C  s   t j| j| |pg ||dS )a  Returns a `Files` object for all files in the run which match the given criteria.

        You can specify a list of exact file names to match, or a pattern to match against.
        If both are provided, the pattern will be ignored.

        Args:
            names (list): names of the requested files, if empty returns all files
            pattern (str, optional): Pattern to match when returning files from W&B.
                This pattern uses mySQL's LIKE syntax,
                so matching all files that end with .json would be "%.json".
                If both names and pattern are provided, a ValueError will be raised.
            per_page (int): number of results per page.

        Returns:
            A `Files` object, which is an iterator over `File` objects.
        )rX  rc   r   Filesr6   )rr   rW  rX  rc   r3   r3   r4   files$  s   z	Run.filesr:   public.Filec                 C  s   t | j| |gd S )zReturn the path of a file with a given name in the artifact.

        Args:
            name (str): name of requested file.

        Returns:
            A `File` matching the name argument.
        r   rZ  )rr   r:   r3   r3   r4   fileC  s   
zRun.file.r   rootc                 C  s   t | j| jdtd}|| j tj|}tj	||}t
|}ttj||d}|t||i W d   n1 sAw   Y  t| j| |gd S )a  Upload a local file to W&B, associating it with this run.

        Args:
            path (str): Path to the file to upload. Can be absolute or relative.
            root (str): The root path to save the file relative to. For example,
                if you want to have the file saved in the run as "my_dir/file.txt"
                and you're currently in "my_dir" you would set root to "../".
                Defaults to current directory (".").

        Returns:
            A `File` object representing the uploaded file.
        r^   r_   default_settingsretry_timedeltarbNr   )InternalApir^   r_   r   set_current_run_idr   r   r   abspathrelpathr   make_file_path_upload_safeopenr   pushr   r   r[  r6   )rr   r   r`  r  r:   upload_pathfr3   r3   r4   upload_fileO  s   
zRun.upload_filer   #list[dict[str, Any]] | pd.DataFramec                 C  s   |durt |tstd g S |dur(t|dkr(t |d ts(td g S |r5|dkr5td g S |r@| j|||d}n| j||d}|r]t	d	}|rX|j
|}|S td
 |S )a  Return sampled history metrics for a run.

        This is simpler and faster if you are ok with the history records being sampled.

        Args:
            samples : (int, optional) The number of samples to return
            pandas : (bool, optional) Return a pandas dataframe
            keys : (list, optional) Only return metrics for specific keys
            x_axis : (str, optional) Use this metric as the xAxis defaults to _step
            stream : (str, optional) "default" for metrics, "system" for machine metrics

        Returns:
            pandas.DataFrame: If pandas=True returns a `pandas.DataFrame` of history
                metrics.
            list of dicts: If pandas=False returns a list of dicts of history metrics.
        N keys must be specified in a listr   'keys argument must be a list of stringsr   z+stream must be default when specifying keys)r   r   r   )r   r   r   z5Unable to load pandas, call history with pandas=False)rP   listr   	termerrorr   rR   rS  rV  r   r   r   r   r   )rr   r   r   r   r   r   linesr   r3   r3   r4   r   i  s&   
"



zRun.history  	page_sizemin_step
int | Nonemax_stepIterator[dict[str, Any]]c                 C  s   |durt |tstd g S |dur(t|dkr(t |d ts(td g S | j}|du r1d}|du r9|d }||krA|d }|du rPtj| | j	|||dS tj
| | j	||||dS )a  Returns an iterable collection of all history records for a run.

        Args:
            keys ([str], optional): only fetch these keys, and only fetch rows that have all of keys defined.
            page_size (int, optional): size of pages to fetch from the api.
            min_step (int, optional): the minimum number of pages to scan at a time.
            max_step (int, optional): the maximum number of pages to scan at a time.

        Returns:
            An iterable collection over history records (dict).

        Example:
        Export all the loss values for an example run

        ```python
        run = api.run("entity/project-name/run-id")
        history = run.scan_history(keys=["Loss"])
        losses = [row["Loss"] for row in history]
        ```
        Nrq  r   rr     )r   r6   rw  rx  rz  )r   r6   r   rw  rx  rz  )rP   rs  r   rt  r   rR   lastHistoryStepr   HistoryScanr6   SampledHistoryScan)rr   r   rw  rx  rz  	last_stepr3   r3   r4   scan_history  s:   
"
zRun.scan_historyd   public.RunArtifactsc                 C     t j| j| d|dS )aD  Fetches all artifacts logged by this run.

        Retrieves all output artifacts that were logged during the run. Returns a
        paginated result that can be iterated over or collected into a single list.

        Args:
            per_page: Number of artifacts to fetch per API request.

        Returns:
            An iterable collection of all Artifact objects logged as outputs during this run.

        Example:
        ```python
        import wandb
        import tempfile

        with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as tmp:
            tmp.write("This is a test artifact")
            tmp_path = tmp.name
        run = wandb.init(project="artifact-example")
        artifact = wandb.Artifact("test_artifact", type="dataset")
        artifact.add_file(tmp_path)
        run.log_artifact(artifact)
        run.finish()

        api = wandb.Api()

        finished_run = api.run(f"{run.entity}/{run.project}/{run.id}")

        for logged_artifact in finished_run.logged_artifacts():
            print(logged_artifact.name)
        ```

        loggedmoderc   r   RunArtifactsr6   rr   rc   r3   r3   r4   logged_artifacts  s   $zRun.logged_artifactsc                 C  r  )a  Fetches artifacts explicitly used by this run.

        Retrieves only the input artifacts that were explicitly declared as used
        during the run, typically via `run.use_artifact()`. Returns a paginated
        result that can be iterated over or collected into a single list.

        Args:
            per_page: Number of artifacts to fetch per API request.

        Returns:
            An iterable collection of Artifact objects explicitly used as inputs in this run.

        Example:
        ```python
        import wandb

        run = wandb.init(project="artifact-example")
        run.use_artifact("test_artifact:latest")
        run.finish()

        api = wandb.Api()
        finished_run = api.run(f"{run.entity}/{run.project}/{run.id}")
        for used_artifact in finished_run.used_artifacts():
            print(used_artifact.name)
        test_artifact
        ```
        usedr  r  r  r3   r3   r4   used_artifacts  s   zRun.used_artifactsartifactwandb.Artifactuse_asc                 C  s|   t | j| jdtd}|| j t|tjr,|	 s,|j
|j|p#|j|j|jd |S t|tjr:|	 r:tdtd)a  Declare an artifact as an input to a run.

        Args:
            artifact (`Artifact`): An artifact returned from
                `wandb.Api().artifact(name)`
            use_as (string, optional): A string identifying
                how the artifact is used in the script. Used
                to easily differentiate artifacts used in a
                run, when using the beta wandb launch
                feature's artifact swapping functionality.

        Returns:
            An `Artifact` object.
        ra  rb  )r  artifact_entity_nameartifact_project_name_Only existing artifacts are accepted by this api. Manually create one with `wandb artifact put`6You must pass a wandb.Api().artifact() to use_artifact)rf  r^   r_   r   rg  r   rP   r   Artifactis_draftuse_artifactr:   r   )rr   r  r  r  r3   r3   r4   r    s$   zRun.use_artifactaliasesCollection[str] | Noner  c              	   C  s   t | j| jdtd}|| j t|tjst	d|
 r#td| j|jks/| j|jkr3td|jdd }|j|j||j| j| j||d |S )	aq  Declare an artifact as output of a run.

        Args:
            artifact (`Artifact`): An artifact returned from
                `wandb.Api().artifact(name)`.
            aliases (list, optional): Aliases to apply to this artifact.
            tags: (list, optional) Tags to apply to this artifact, if any.

        Returns:
            A `Artifact` object.
        ra  rb  r  r  z3A run can't log an artifact to a different project.:r   )entity_nameproject_namer  r  )rf  r^   r_   r   rg  r   rP   r   r  rY   r  r   source_entitysource_projectsource_namesplitcreate_artifactr   digest)rr   r  r  r  r  artifact_collection_namer3   r3   r4   log_artifactE  s2   	zRun.log_artifactc                 C  s*   | j s|s| jS | jttdd}d| _|S )as  Load full run data including heavy fields like config, systemMetrics, summaryMetrics.

        This method is useful when you initially used lazy=True for listing runs,
        but need access to the full data for specific runs.

        Args:
            force: Force reload even if data is already loaded

        Returns:
            The loaded run attributes
        Tr   )rm   r   r"  r.   r0   r   )rr   r   r   r3   r3   r4   r   v  s
   
zRun.load_full_datac                 C  B   | j r| jsd| jvr|   | jdi }t|}|| jd< |S )z5Get run config. Auto-loads full data if in lazy mode.r  rm   r   r   r   rD   rZ   )rr   config_valuer3   r3   r4   r    s   
z
Run.configr   c                 C  sN   | j r| jsd| jvr|   | jdu r$ddlm} || | j| jd| _| jS )>Get run summary metrics. Auto-loads full data if in lazy mode.r  Nr   r   )r9  )	rm   r   r   r   r   wandb.old.summaryr   r6   summary_metrics)rr   r   r3   r3   r4   r9    s   

zRun.summaryc                 C  r  )z=Get run system metrics. Auto-loads full data if in lazy mode.r  r  )rr   system_metrics_valuer3   r3   r4   system_metrics     

zRun.system_metricsc                 C  r  )r  r  r  )rr   summary_metrics_valuer3   r3   r4   r    r  zRun.summary_metricsc                 C  s,   | j r| jsd| jvr|   | jdi S )zQGet raw run config including internal keys. Auto-loads full data if in lazy mode.r$  )rm   r   r   r   rD   ry   r3   r3   r4   r$    s   zRun.rawconfigc                 C  r   )zLGet sweep name. Always available since sweepName is in lightweight fragment.r#  r   ry   r3   r3   r4   r     s   zRun.sweep_namec                 C  s4   t jt| jt jt| jt jt| jgS )zSThe path of the run. The path is a list containing the entity, project, and run_id.)urllibparse
quote_plusrR   r^   r_   r   ry   r3   r3   r4   r     s   zRun.pathc                 C  s$   | j }|dd | jjd| S )zThe URL of the run.

        The run URL is generated from the entity, project, and run_id. For
        SaaS users, it takes the form of `https://wandb.ai/entity/project/run_id`.
           r{   r   )r   insertr6   app_urlr   )rr   r   r3   r3   r4   url  s   zRun.urlra   c                 C  sh   | j du r1z$| d}| jjjj}|j|jdd}|  |j	}t
|| _ W | j S    Y | j S | j S )zMetadata about the run from wandb-metadata.json.

        Metadata includes the run's description, tags, start time, memory
        usage and more.
        Nzwandb-metadata.jsonr/  )timeout)r   r^  r6   _client	transportsessionrD   r  raise_for_statuscontentr   rV   )rr   rn  r  r!  contentsr3   r3   r4   metadata  s   

zRun.metadatac                 C  sp   t d}| |}|du s(|ddu s(|d ddu s(|d d ddu r*dS |d d d }|ddS )z2Returns the last step logged in the run's history.z
        query RunHistoryKeys($project: String!, $entity: String!, $name: String!) {
            project(name: $project, entityName: $entity) {
                run(name: $name) { historyKeys }
            }
        }
        Nr_   r   historyKeysr   lastStep)r	   r  rD   )rr   rG   r!  history_keysr3   r3   r4   r}    s   
	zRun.lastHistoryStep  heighthiddenc                 C  sD   | j d }d| d}d}|r|d7 }t }|d|d|d S )	z7Generate HTML containing an iframe displaying this run.z?jupyter=truezborder:none;width:100%;height:zpx;r*   zdisplay:none;z<iframe src=z style=z
></iframe>)r  r   toggle_button)rr   r  r  r  styleprefixr3   r3   r4   to_html  s   
zRun.to_htmlc                 C  s&   t  rdd l}||  S |  S )Nr   )r   in_vscode_notebookhtmlescape_string_representationr  )rr   r  r3   r3   r4   _repr_html_   s   zRun._repr_html_c                 C  s   |   S N)r  ry   r3   r3   r4   r   (  s   zRun.__repr__c                 C  s*   dt t|  dd| j d| j dS )Nr   r   r   z (z)>)r   r   r   r   r   ry   r3   r3   r4   r  +  s   *zRun._string_representationr   	use_cachepublic.BetaHistoryScanc              	   C  sL   | j du rt j }t|d| _ tj| j | ||p| jd |||d}|S )a  Returns an iterable collection of all history records for a run.

        This function is still in development and may not work as expected.
        It uses wandb-core to read history from a run's exported
        parquet history locally.

        Args:
            keys: list of metrics to read from the run's history.
                if no keys are provided then all metrics will be returned.
            page_size: the number of history records to read at a time.
            min_step: The minimum step to start reading history from (inclusive).
            max_step: The maximum step to read history up to (exclusive).
            use_cache: When set to True, checks the WANDB_CACHE_DIR for a run history.
                If the run history is not found in the cache, it will be downloaded from the server.
                If set to False, the run history will be downloaded every time.

        Returns:
            A BetaHistoryScan object,
            which can be iterator over to get history records.
        Nr  r|  )rf   r   rx  rz  r   rw  r  )	rn   r   	singletonr  
model_copyr   r   BetaHistoryScanr}  )rr   r   rw  rx  rz  r  r  beta_history_scanr3   r3   r4   beta_scan_history.  s   
	zRun.beta_scan_historydownload_dirpathlib.Path | strrequire_complete_history runhistory.DownloadHistoryResultc              
     s   t jjjjt||d}t jt j|dd}jdu r+t	
 j }t|d_zj|}W n# tyV } z|jdurM|jjt jjkrMt dtd|d}~ww |jjj |jjjt	
 j fddS )	a  Download any parquet history files for the run to the provided directory.

        Args:
            download_dir: The directory to download the history files to.
            require_complete_history: Whether to require the complete history to be downloaded.
                If true, and the run contains data that has not been exported to parquet files yet,
                an IncompleteRunHistoryError will be raised.

        Returns:
            A DownloadHistoryResult.

        Raises:
            IncompleteRunHistoryError: If require_complete_history is True
                and the run contains data not yet exported to parquet files.
            WandbApiFailedError: If the API request fails for reasons other than
                incomplete history.
        )r^   r_   r   r  r  )download_run_history_init)read_run_history_requestNr  zFailed to download historyc                     s   t j S r  )
runhistorywait_for_download_with_progressrn   r3   contains_live_data
request_idrr   r3   r4   <lambda>  s
    z.Run.download_history_exports.<locals>.<lambda>)apbDownloadRunHistoryInitr^   r_   r   rR   
ApiRequestReadRunHistoryRequestrn   r   r  r  r  r   send_api_requestr   r!  
error_type	ErrorTypeINCOMPLETE_RUN_HISTORY_ERRORr  IncompleteRunHistoryErrorread_run_history_responser  r  r  asyncerr   )rr   r  r  init_download_requestapi_requestr  r!  rG  r3   r  r4   download_history_exportsY  s<   




	
zRun.download_history_exports)NTTN)r6   r   r^   rR   r_   rR   r   rR   r   r   re   r%   r$   r%   rf   rg   r   )r   rR   r(   r   )r(   r  )r  rR   r(   r   )NNNr  )r  r  r   r  r_   r  r^   r  r   r  r(   r   )F)r1   rR   r2   rR   r   r%   r(   rN   )r(   rN   )r   r%   r(   rN   r   )r;  r%   r(   r   )r   r?  r(   r%   )rG   r   rM  r   r(   rN   )r   r   )r   rN  r   rR   r   rd   r(   rO  )r   r   )r   rd   r   r   r(   rO  )NNr]   )rW  r   rX  r  rc   rd   r(   rY  )r:   rR   r(   r]  )r_  )r   rR   r`  rR   r(   r]  )r   Nr   Tr   )r   rd   r   r   r   rR   r   r%   r   r   r(   rp  )Nrv  NN)
r   r   rw  rd   rx  ry  rz  ry  r(   r{  )r  )rc   rd   r(   r  r  )r  r  r  r  r(   r  )NN)r  r  r  r  r  r  r(   r  )r(   r   )r(   rN  )r(   ra   r   )r  F)r  rd   r  r%   r(   rR   )Nrv  r   NT)r   r   rw  rd   rx  rd   rz  ry  r  r%   r(   r  )T)r  r  r  r%   r(   r  )7r   r   r   r   rq   r   r   r^   r   r   r   setterr:   classmethodr  r"  r   r   r   r2  r(  r=  r>  rI  r6  r  rS  rV  r\  r^  ro  r   r  r  r  r  r  r   r  r9  r  r  r$  r   r   r  r  r}  r  r  r   r  r  r  r   r3   r3   rt   r4   r     s    &+b
F1
"9
	.=%)0




.)r$   r%   r&   r%   r'   r%   r(   r	   )r6   r   r(   r%   )rM   r   r(   rN   )Nr   
__future__r   rU   r   pathlibr   r0  r  collections.abcr   r   r   typingr   r   r   	wandb_gqlr	   r   wandb.apis.public.runhistoryapisr   r  r
   r   wandb._strutilsr   
wandb.apiswandb.apis.attrsr   wandb.apis.internalr   rf  wandb.apis.normalizer   wandb.apis.paginatorr   wandb.apis.public.constr   wandb.apis.public.service_apir   wandb.protor   r  	wandb.sdkr   wandb.sdk.libr   r   r   wandb.sdk.lib.pathsr   (wandb.sdk.lib.service.service_connectionr   r   r   r   r   typing_extensionsr   wandb_graphql.language.astr   wandb.apis.publicr   r  r   r&  r.   r-   r0   r/   r5   rI   rL   rZ   r[   r   r3   r3   r3   r4   <module>   sd    "
"  