o
    wi*                     @  s  U d Z ddlm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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 e	rWddlmZ ddlmZ eee
f Zde d< 	 G dd dee Z!G dd dee Z"G dd dee Z#dS )a\  W&B Public API for Run History.

This module provides classes for efficiently scanning and sampling run
history data.

Note:
    This module is part of the W&B Public API and provides methods
    to access run history data. It handles pagination automatically and offers
    both complete and sampled access to metrics logged during training runs.
    )annotationsN)Iterator)TYPE_CHECKINGAny)Self	TypeAlias)gql)normalize_exceptions)
ServiceApiwandb_api_pb2)MailboxClosedError   )runs)RetryingClientr   _RowDictc                   @  s\   e Zd ZdZ			d$d%ddZd&ddZd'ddZd(ddZed)dd Z	ed*d"d#Z
dS )+BetaHistoryScan]Iterator for scanning complete run history.

    <!-- lazydoc-ignore-class: internal -->
    N  Tservice_apir
   runruns.Runmin_stepintmax_stepkeyslist[str] | None	page_size	use_cacheboolc                 C  s   || _ || _|| _|| _|| _|| _tj| j j| j j	| j j
| j|d}tj|d}	tj|	d}
| j|
}|jjj| _d| _g | _|| _t| | j| j| j d S )N)entityprojectrun_idr   r   )scan_run_history_initread_run_history_requestr   )r   r   r   r   r   _service_apipbScanRunHistoryInitr    r!   idReadRunHistoryRequest
ApiRequestsend_api_requestread_run_history_responser#   
request_id_scan_request_idscan_offsetrowsweakreffinalizecleanup)selfr   r   r   r   r   r   r   r#   scan_run_history_init_requestapi_requestresponse r9   M/home/ubuntu/.local/lib/python3.10/site-packages/wandb/apis/public/history.py__init__*   s>   
zBetaHistoryScan.__init__returnr   c                 C  s   d| _ | j| _g | _| S Nr   )r0   r   page_offsetr1   r5   r9   r9   r:   __iter__`   s   zBetaHistoryScan.__iter__r   c                 C  L   	 | j t| jk r| j| j  }|  j d7  _ |S | j| jkr!t |   q)NTr   r0   lenr1   r>   r   StopIteration
_load_nextr5   rowr9   r9   r:   __next__f   s   zBetaHistoryScan.__next__Nonec                   s   ddl m} t j j  j}|j|j j| jdd}|j	|d} j
|}|jj} fdd|jD  _  j j7  _d _d S )Nr   r   )r   r   r.   )scan_run_historyr$   c                   s   g | ]}  |qS r9   )_convert_history_row_to_dict.0rG   r?   r9   r:   
<listcomp>   s    
z.BetaHistoryScan._load_next.<locals>.<listcomp>)wandb.protor   minr>   r   r   r*   ScanRunHistoryr/   r+   r&   r,   r-   run_historyhistory_rowsr1   r0   )r5   r'   r   r%   r7   r8   rR   r9   r?   r:   rE   p   s$   

zBetaHistoryScan._load_nexthistory_rowpb.HistoryRowc                 C  s   dd | j D S )Nc                 S  s   i | ]
}|j t|jqS r9   )keyjsonloads
value_json)rM   itemr9   r9   r:   
<dictcomp>   s    z@BetaHistoryScan._convert_history_row_to_dict.<locals>.<dictcomp>)history_items)rT   r9   r9   r:   rK      s   z,BetaHistoryScan._convert_history_row_to_dictr.   c                 C  s\   t j|d}t j|d}ttt | t j|d W d    d S 1 s'w   Y  d S )N)r.   )scan_run_history_cleanupr$   )	r'   ScanRunHistoryCleanupr*   
contextlibsuppressConnectionResetErrorr   r,   r+   )r   r.   r]    scan_run_history_cleanup_requestr9   r9   r:   r4      s   
"zBetaHistoryScan.cleanup)Nr   T)r   r
   r   r   r   r   r   r   r   r   r   r   r   r   r<   r   r<   r   r<   rI   )rT   rU   r<   r   )r   r
   r.   r   r<   rI   )__name__
__module____qualname____doc__r;   r@   rH   rE   staticmethodrK   r4   r9   r9   r9   r:   r   $   s    
6


r   c                   @  sL   e Zd ZdZedZ	ddddZdddZdddZeZ	e
dddZdS )HistoryScanr   ak  
        query HistoryPage($entity: String!, $project: String!, $run: String!, $minStep: Int64!, $maxStep: Int64!, $pageSize: Int!) {
            project(name: $project, entityName: $entity) {
                run(name: $run) {
                    history(minStep: $minStep, maxStep: $maxStep, samples: $pageSize)
                }
            }
        }
        r   clientr   r   r   r   r   r   r   c                 C  s4   || _ || _|| _|| _|| _|| _d| _g | _dS )a  Initialize a HistoryScan instance.

        Args:
            client: The client instance to use for making API calls to the W&B backend.
            run: The run object whose history is to be scanned.
            min_step: The minimum step to start scanning from.
            max_step: The maximum step to scan up to.
            page_size: Number of history rows to fetch per page.
                Default page_size is 1000.
        r   N)rl   r   r   r   r   r>   r0   r1   )r5   rl   r   r   r   r   r9   r9   r:   r;      s   
zHistoryScan.__init__r<   r   c                 C     | j | _d| _g | _| S r=   r   r>   r0   r1   r?   r9   r9   r:   r@         zHistoryScan.__iter__r   c                 C  rA   )zrReturn the next row of history data with automatic pagination.

        <!-- lazydoc-ignore: internal -->
        Tr   rB   rF   r9   r9   r:   rH         zHistoryScan.__next__rI   c                 C  s   | j | j }|| jkr| j}| jj| jj| jjt| j t|t| jd}| jj	| j
|d}|d d d }dd |D | _|  j | j7  _ d| _d S )	N)r    r!   r   minStepmaxSteppageSizevariable_valuesr!   r   historyc                 S  s   g | ]}t |qS r9   )rW   rX   rL   r9   r9   r:   rN      s    z*HistoryScan._load_next.<locals>.<listcomp>r   )r>   r   r   r   r    r!   r)   r   rl   executeQUERYr1   r0   r5   r   	variablesresr9   r9   r:   rE      s   
	
zHistoryScan._load_nextNr   )
rl   r   r   r   r   r   r   r   r   r   rc   rd   re   rf   rg   rh   ri   r   rx   r;   r@   rH   nextr	   rE   r9   r9   r9   r:   rk      s    

rk   c                   @  sL   e Zd ZdZedZ	ddddZdddZdddZeZ	e
dddZdS ) SampledHistoryScanzYIterator for sampling run history data.

    <!-- lazydoc-ignore-class: internal -->
    a.  
        query SampledHistoryPage($entity: String!, $project: String!, $run: String!, $spec: JSONString!) {
            project(name: $project, entityName: $entity) {
                run(name: $run) {
                    sampledHistory(specs: [$spec])
                }
            }
        }
        r   rl   r   r   r   r   	list[str]r   r   r   r   c                 C  s:   || _ || _|| _|| _|| _|| _|| _d| _g | _dS )a  Initialize a SampledHistoryScan instance.

        Args:
            client: The client instance to use for making API calls to the W&B backend.
            run: The run object whose history is to be sampled.
            keys: List of keys to sample from the history.
            min_step: The minimum step to start sampling from.
            max_step: The maximum step to sample up to.
            page_size: Number of sampled history rows to fetch per page.
                Default page_size is 1000.
        r   N)	rl   r   r   r   r   r   r>   r0   r1   )r5   rl   r   r   r   r   r   r9   r9   r:   r;     s   
zSampledHistoryScan.__init__r<   r   c                 C  rm   r=   rn   r?   r9   r9   r:   r@   %  ro   zSampledHistoryScan.__iter__r   c                 C  rA   )zzReturn the next row of sampled history data with automatic pagination.

        <!-- lazydoc-ignore: internal -->
        Tr   rB   rF   r9   r9   r:   rH   +  rp   zSampledHistoryScan.__next__rI   c              
   C  s   | j | j }|| jkr| j}| jj| jj| jjt| j	t
| j t
|t
| jdd}| jj| j|d}|d d d }|d | _|  j | j7  _ d| _d S )N)r   rq   rr   samples)r    r!   r   specrt   r!   r   sampledHistoryr   )r>   r   r   r   r    r!   r)   rW   dumpsr   r   rl   rw   rx   r1   r0   ry   r9   r9   r:   rE   ;  s&   


zSampledHistoryScan._load_nextNr|   )rl   r   r   r   r   r   r   r   r   r   r   r   rc   rd   re   r}   r9   r9   r9   r:   r      s    

r   )$ri   
__future__r   r_   rW   r2   collections.abcr   typingr   r   typing_extensionsr   r   	wandb_gqlr   wandb.apis.normalizer	   wandb.apis.public.service_apir
   rO   r   r'   wandb.sdk.mailbox.mailboxr    r   apir   dictstrr   __annotations__r   rk   r   r9   r9   r9   r:   <module>   s*    yX