o
    wiO                     @  s   d Z ddlmZ ddlZddlZddlZddlZddlmZm	Z	 ddl
mZ ddl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rVddlmZ ddlmZ G dd ded ZG dd deZG dd dZG dd dZdS )zW&B Public API for Report objects.

This module provides classes for interacting with W&B reports and
managing report-related data.
    )annotationsN)TYPE_CHECKINGAny)gql)nameof)public)Attrs)SizedPaginator)ipython   )RetryingClient)Projectc                      sz   e Zd ZdZedZ			d"d# fddZed$ddZed%ddZ	ed&ddZ
d'ddZd(ddZd)d d!Z  ZS )*Reportsa  Reports is a lazy iterator of `BetaReport` objects.

    Args:
        client (`wandb.apis.internal.Api`): The API client instance to use.
        project (`wandb.sdk.internal.Project`): The project to fetch reports from.
        name (str, optional): The name of the report to filter by. If `None`,
            fetches all reports.
        entity (str, optional): The entity name for the project. Defaults to
            the project entity.
        per_page (int): Number of reports to fetch per page (default is 50).
    aV  
        query ProjectViews($project: String!, $entity: String!, $reportCursor: String,
            $reportLimit: Int!, $viewType: String = "runs", $viewName: String) {
            project(name: $project, entityName: $entity) {
                allViews(viewType: $viewType, viewName: $viewName, first:
                    $reportLimit, after: $reportCursor) {
                    edges {
                        node {
                            id
                            name
                            displayName
                            description
                            user {
                                username
                                photoUrl
                                email
                            }
                            spec
                            updatedAt
                            createdAt
                        }
                        cursor
                    }
                    pageInfo {
                        endCursor
                        hasNextPage
                    }

                }
            }
        }
        N2   clientr   projectr   name
str | Noneentityper_pageintc                   s2   || _ || _|j|j| jd}t ||| d S )N)r   r   viewName)r   r   r   super__init__)selfr   r   r   r   r   	variables	__class__ M/home/ubuntu/.local/lib/python3.10/site-packages/wandb/apis/public/reports.pyr   M   s   zReports.__init__return
int | Nonec                 C  s   | j rt| jS dS )zYThe number of reports in the project.

        <!-- lazydoc-ignore: internal -->
        N)last_responselenobjectsr   r   r   r   _length^   s   
zReports._lengthboolc                 C  s$   | j rt| j d d d d S dS )zbReturns whether there are more files to fetch.

        <!-- lazydoc-ignore: internal -->
        r   allViewspageInfohasNextPageT)r"   r'   r%   r   r   r   morei   s
   zReports.morec                 C  s$   | j r| j d d d d d S dS )zoReturns the cursor position for pagination of file results.

        <!-- lazydoc-ignore: internal -->
        r   r(   edgescursorN)r"   r%   r   r   r   r.   u   s   zReports.cursorNonec                 C  s   | j | j| jd dS )z3Updates the GraphQL query variables for pagination.)reportCursorreportLimitN)r   updater.   r   r%   r   r   r   update_variables   s   zReports.update_variableslist[BetaReport]c                   sN    j d du rtd jd  d jd   fdd j d d d	 D S )
z'Converts GraphQL edges to File objects.r   NzProject z does not exist under entity r   c                   s*   g | ]}t  j|d   jj jjdqS )node)r   r   )
BetaReportr   r   r   r   ).0rr%   r   r   
<listcomp>   s    z+Reports.convert_objects.<locals>.<listcomp>r(   r,   )r"   
ValueErrorr   r%   r   r%   r   convert_objects   s   
zReports.convert_objectsstrc                 C  s$   dt t|  dd| jj dS )N< />)r   typejoinr   pathr%   r   r   r   __repr__   s   $zReports.__repr__)NNr   )
r   r   r   r   r   r   r   r   r   r   )r    r!   )r    r'   r    r   )r    r/   )r    r4   r    r<   )__name__
__module____qualname____doc__r   QUERYr   propertyr&   r+   r.   r3   r;   rD   __classcell__r   r   r   r   r      s$    '

	
r   r6   c                      s   e Zd ZdZ		d5d6 fd
dZed7ddZedd Z		d8d9ddZed:ddZ	ed;dd Z
ed;d!d"Zed;d#d$Zed%d& Zed'd( Zed)d* Zed;d+d,Zd<d=d1d2Zd:d3d4Z  ZS )>r6   ag  BetaReport is a class associated with reports created in W&B.

    Provides access to report attributes (name, description, user, spec,
    timestamps) and methods for retrieving associated runs,
    sections, and for rendering the report as HTML.

    Attributes:
        id (string): Unique identifier of the report.
        display_name (string): Human-readable display name of the report.
        name (string): The name of the report. Use `display_name` for a more user-friendly name.
        description (string): Description of the report.
        user (User): Dictionary containing user info (username, email) who
            created the report.
        spec (dict): The spec of the report.
        url (string): The URL of the report.
        updated_at (string): Timestamp of last update.
        created_at (string): Timestamp when the report was created.
    Nr   r   attrsdictr   r   r   c                   sr   || _ || _|| _t | _t t| d| j	v r2t
| j	d tr0t| j	d | j	d< d S d S i | j	d< d S Nspec)r   r   r   r   QueryGeneratorquery_generatorr   r   rO   _attrs
isinstancer<   jsonloads)r   r   rN   r   r   r   r   r   r      s   

zBetaReport.__init__r    dict[str, Any]c                 C  
   | j d S rP   )rT   r%   r   r   r   rQ      s   
zBetaReport.specc                 C  rY   )z0Get the panel sections (groups) from the report.panelGroups)rQ   r%   r   r   r   sections   s   
zBetaReport.sectionsr   Tsectionr   r   only_selectedr'   public.Runsc                 C  s   | dd}|d | }| j|d d }|d  dr"d| }nd| }| j|d	 }|rC|d
 d d dd|d d ii tj| j| j| j	|||dS )z1Get runs associated with a section of the report.
openRunSetr   runSetssortkey	ascending+-filters$or$andr   $in
selectionstree)rf   orderr   )
getrS   key_to_server_pathfilter_to_mongoappendr   Runsr   r   r   )r   r\   r   r]   run_set_idxrun_setrl   rf   r   r   r   runs   s&   
zBetaReport.runsr<   c                 C     | j dS )NidrT   rm   r%   r   r   r   rv         zBetaReport.idc                 C  ru   )Nr   rw   r%   r   r   r   r      rx   zBetaReport.namec                 C  ru   )NdisplayNamerw   r%   r   r   r   display_name   rx   zBetaReport.display_namec                 C  ru   )Ndescriptionrw   r%   r   r   r   r{      rx   zBetaReport.descriptionc                 C  ru   )Nuserrw   r%   r   r   r   r|      rx   zBetaReport.userc                 C  ru   )N	updatedAtrw   r%   r   r   r   
updated_at   rx   zBetaReport.updated_atc                 C  ru   )N	createdAtrw   r%   r   r   r   
created_at   rx   zBetaReport.created_atc                 C  sx   | j r| jr| jr| jr| jsd S | j jd| j| jddtj	t
ddt
dd| jd| jddgg S )	Nr?   reportsz--z-+re   z\W= )r   r   r   rz   rv   app_urlrB   urllibparsequoteresubstripreplacer%   r   r   r   url  s6   
zBetaReport.url   Fheighthiddenc                 C  sV   | j }|du r	dS |d }d| d}d}|r |d7 }td}|d	|d
|d S )z:Generate HTML containing an iframe displaying this report.Nz#<div>Report URL not available</div>z?jupyter=truezborder:none;width:100%;height:zpx;r   zdisplay:none;reportz<iframe src=z style=z
></iframe>)r   r
   toggle_button)r   r   r   r   styleprefixr   r   r   to_html  s   
zBetaReport.to_htmlc                 C  s   |   S N)r   r%   r   r   r   _repr_html_,  s   zBetaReport._repr_html_)NN)r   r   rN   rO   r   r   r   r   )r    rX   )r   T)r\   rX   r   r   r]   r'   r    r^   rF   rE   )r   F)r   r   r   r'   r    r<   )rG   rH   rI   rJ   r   rL   rQ   r[   rt   rv   r   rz   r{   r|   r~   r   r   r   r   rM   r   r   r   r   r6      s<    



c                   @  sb  e Zd ZdZdZdZi dddddd	d
dddddddddddddddddddddd d!d"d#d$d%Zd&d' e D Ze	j
d(e	jd)e	jd*e	jd+e	jd,e	jd,e	jd-e	jd-e	jd.e	jd/e	jd0e	jd1e	jd2iZe	jd3e	jd4e	jd5e	jd5iZd6d7 Zd8d9 Zd:d; Zd<d= Z d>d? Z!d@dA Z"dBdC Z#dDdE Z$dFdG Z%dHdI Z&dJdK Z'dLdM Z(dNS )OPythonMongoishQueryGeneratorConverts Python-style query expressions to MongoDB-style queries for W&B reports.

    <!-- lazydoc-ignore-class: internal -->
    z
----------z;;;IDr   Namery   TagstagsStatestateCreatedTimestampr   RuntimedurationUserusernameSweepsweepGroupgroupJobTypejobTypeHostnamehostUsingArtifactinputArtifactsOutputtingArtifactoutputArtifactsStep_stepRelative Time (Wall)_absolute_runtimeRelative Time (Process)_runtime	Wall Time
_timestampc                 C     i | ]\}}||qS r   r   r7   kvr   r   r   
<dictcomp>L      z'PythonMongoishQueryGenerator.<dictcomp>z$ltz$ltez$gtz$gter   z$neri   z$ninrh   rg   z$notvaluerv   eltsc                 C  s   || _ t | _d S r   )rs   PanelMetricsHelperpanel_metrics_helper)r   rs   r   r   r   r   d  s   z%PythonMongoishQueryGenerator.__init__c                 C  sN   |  | |j}| |jd }| |jd }|dkr!||iS |||iiS )Nr   r   )front_to_back_handle_fieldsleft_handle_opsopscomparators)r   r5   r   oprightr   r   r   _handle_compareh  s   z,PythonMongoishQueryGenerator._handle_comparec                   sJ   t | jt|}t|tr fdd|D S t|tr# |S |S )Nc                      g | ]}  |qS r   )r   )r7   r5   r%   r   r   r9   w  r   z?PythonMongoishQueryGenerator._handle_fields.<locals>.<listcomp>)getattr
AST_FIELDSrm   rA   rU   listr<   
_unconvert)r   r5   resultr   r%   r   r   t  s   


z+PythonMongoishQueryGenerator._handle_fieldsc                 C  s   | j t|S r   )AST_OPERATORSrm   rA   )r   r5   r   r   r   r   |  s   z(PythonMongoishQueryGenerator._handle_opsc           
      C  s  g }t t||dd  |dd  dD ](\}\}}}|dkr;| r&| s6| r.|dks6|dkr;| r;|| q|d  rQ|d dkrQ|t|d  dg| t|g }g }t||dd  D ]\}}	|||d |	  || j qf|d d }d|S )Nr      .r>   r-   r   )	enumeratezipisdigitrp   r#   DECIMAL_SPACERrB   )
r   snumeric_dotsir   midr   substrsstartstopr   r   r   _replace_numeric_dots  s0   0

z2PythonMongoishQueryGenerator._replace_numeric_dotsc                 C  s*   |  |d| j| jd}d| d S )Nr   ())r   r   SPACERr   )r   	filterstr_conversionr   r   r   _convert  s
   

z%PythonMongoishQueryGenerator._convertc                 C  s   | | jdS )Nr   )r   r   )r   
field_namer   r   r   r     s   z'PythonMongoishQueryGenerator._unconvertc              
     s   zt j |dd}W n ty } ztd|d}~ww t|jd}|r< jt	|jj
} fdd|jjD }n	d} |jg}d	||igiS )
z_Convert Python expresion to MongoDB filter.

        <!-- lazydoc-ignore: internal -->
        eval)modezIInvalid python comparison expression; form something like `my_col == 123`Nr   c                   r   r   )r   )r7   r   r%   r   r   r9     r   z@PythonMongoishQueryGenerator.python_to_mongo.<locals>.<listcomp>rh   rg   )astr   r   SyntaxErrorr:   hasattrbodyr   rm   rA   r   valuesr   )r   r   rk   emultiple_filtersr   r   r   r%   r   python_to_mongo  s"   z,PythonMongoishQueryGenerator.python_to_mongoc                 C  sp   | d^}}|rdd| nd}|| jv r| j| S || jv r#|S || jjv r1d| d| S d| | S )iConvert frontend metric names to backend field names.

        <!-- lazydoc-ignore: internal -->
        r   r   config..valuesummary_metrics.)splitrB   FRONTEND_NAME_MAPPINGFRONTEND_NAME_MAPPING_REVERSEDrs   _runs_configr   r   restr   r   r   r     s   


z*PythonMongoishQueryGenerator.front_to_backc                 C  sr   || j v r
| j | S || jv r|S |dr$d|v r$|ddddS |dr/|ddS td|  |S )iConvert backend field names to frontend metric names.

        <!-- lazydoc-ignore: internal -->
        r   r   r   r   zUnknown token: )r   r   
startswithr   wandb	termerrorr   r   r   r   r   back_to_front  s   



z*PythonMongoishQueryGenerator.back_to_frontc                 C  s   | d^}}|rdd| nd}|du rdS || jjv r&d| jj|  S || jv r0| j| S || jv r7|S || jjv rEd| d| S d| | S )zkConvert ParallelCoordinatesPlot to backend field names.

        <!-- lazydoc-ignore: internal -->
        r   r   Nsummary:config:r   )r   rB   r   r   r   rs   r   r   r   r   r   pc_front_to_back  s   


z-PythonMongoishQueryGenerator.pc_front_to_backc                 C  s   |du rdS d|v r| dd}| jj||S || jv r"| j| S || jv r)|S |dr<d|v r<| dd ddS |drG| ddS |S )zyConvert backend backend field names to ParallelCoordinatesPlot names.

        <!-- lazydoc-ignore: internal -->
        Nr  r   r  r   r   )r   r   r   rm   r   r   r   r   r   r   pc_back_to_front  s    



z-PythonMongoishQueryGenerator.pc_back_to_frontN))rG   rH   rI   rJ   r   r   r   itemsr   r   LtLtEGtGtEEqIsNotEqIsNotInNotInAndOrNotr   Constantr   ListTupler   r   r   r   r   r   r   r   r   r   r  r  r  r   r   r   r   r   0  s    	
r   c                   @  sl   e Zd ZdZdddddZdd e D Zd	d
dZdd e D Zdd Z	dd Z
dd Zdd ZdS )r   r   r   r   r   r   )r   r   r   r   c                 C  r   r   r   r   r   r   r   r     r   zPanelMetricsHelper.<dictcomp>r   heartbeatAt)zCreated TimestampzLatest Timestampc                 C  r   r   r   r   r   r   r   r     r   c                 C     || j v r
| j | S |S )r   )r   r   r   r   r   r        

z PanelMetricsHelper.front_to_backc                 C  r  )r   )r   r   r   r   r   r  "  r  z PanelMetricsHelper.back_to_frontc                 C  s   |du r|S | d^}}|rdd| nd}|dr+|dd }d| d| S |dr=|dd | }d	| S || }|| jv rMd
| j|  S || jv rYd	| j|  S |dkr_|S d	| S )r   Nr   r   c::   r  r   s::r  run:Index)r   rB   r   RUN_MAPPINGr   r   r   r   r   special_front_to_back,  s$   




z(PanelMetricsHelper.special_front_to_backc                 C  s   |durT| dd\}}|dkrI| d}t|dkr"td| t|dkr-|d }nt|d	krD|dd |dd  }d|}d
| S |dkrT|}d| S |du rZ|S d|v rk|dd}| j||S d|v rz|dd}| j| S |S )r   N:r   configr   zInvalid name: r   r   r  r  summaryr  r  r   r  )r   r#   r:   rB   r   r   rm   RUN_MAPPING_REVERSED)r   r   kindr   piecesr   r   r   special_back_to_frontJ  s0   





z(PanelMetricsHelper.special_back_to_frontN)rG   rH   rI   rJ   r   r  r   r  r$  r   r  r   r'  r   r   r   r   r     s    
	
r   )rJ   
__future__r   r   rV   r   r   typingr   r   	wandb_gqlr   r   wandb._strutilsr   
wandb.apisr   wandb.apis.attrsr   wandb.apis.paginatorr	   wandb.sdk.libr
   apir   projectsr   r   r6   r   r   r   r   r   r   <module>   s.    |  Y