o
    wi/                     @  s   d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	 ddl
mZ ddl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r^ddlmZ ddlmZ G dd ded ZG dd deZdS )a  W&B Public API for Sweeps.

This module provides classes for interacting with W&B hyperparameter
optimization sweeps.

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

# Get a specific sweep
sweep = Api().sweep("entity/project/sweep_id")

# Access sweep properties
print(f"Sweep: {sweep.name}")
print(f"State: {sweep.state}")
print(f"Best Loss: {sweep.best_loss}")

# Get best performing run
best_run = sweep.best_run()
print(f"Best Run: {best_run.name}")
print(f"Metrics: {best_run.summary}")
```

Note:
    This module is part of the W&B Public API and provides read-only access
    to sweep data. For creating and controlling sweeps, use the wandb.sweep()
    and wandb.agent() functions from the main wandb package.
    )annotationsN)Mapping)TYPE_CHECKINGAnyClassVar)override)gql)Document)util)public)Attrs)SizedPaginator)ipython	GetSweeps)RetryingClientc                      s   e Zd ZU dZdZded< ded< 	d"d# fddZed$ddZe	ed%ddZ
e	ed&ddZe	ed'ddZed(ddZd d! Z  ZS ))Sweepsa  A lazy iterator over a collection of `Sweep` objects.

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

    sweeps = Api().project(name="project_name", entity="entity").sweeps()

    # Iterate over sweeps and print details
    for sweep in sweeps:
        print(f"Sweep name: {sweep.name}")
        print(f"Sweep ID: {sweep.id}")
        print(f"Sweep URL: {sweep.url}")
        print("----------")
    ```
    NzClassVar[Document | None]QUERYzGetSweeps | Nonelast_response2   clientr   entitystrprojectper_pageintreturnc                   sR   | j du rddlm} t|t| _ || _|| _| j| jd}t ||| dS )a6  An iterable collection of `Sweep` objects.

        Args:
            client: The API client used to query W&B.
            entity: The entity which owns the sweeps.
            project: The project which contains the sweeps.
            per_page: The number of sweeps to fetch per request to the API.
        Nr   )GET_SWEEPS_GQL)r   r   )	r   wandb.apis._generatedr   r   typer   r   super__init__)selfr   r   r   r   r   	variables	__class__ L/home/ubuntu/.local/lib/python3.10/site-packages/wandb/apis/public/sweeps.pyr!   I   s   
zSweeps.__init__Nonec                 C  s0   ddl m} | jj| j| jd}||| _dS )z:Fetch and validate the response data for the current page.r   r   variable_valuesN)r   r   r   executer   r#   model_validater   )r"   r   datar&   r&   r'   _update_responseb   s   zSweeps._update_responsec                 C  s,   | j du r	|   | j jj }dur|S dS )z^The total number of sweeps in the project.

        <!-- lazydoc-ignore: internal -->
        Nr   )r   
_load_pager   total_sweeps)r"   totalr&   r&   r'   _lengthj   s   
zSweeps._lengthboolc                 C     | j r
| j jjjjS dS )zcReturns whether there are more sweeps to fetch.

        <!-- lazydoc-ignore: internal -->
        T)r   r   sweeps	page_infohas_next_pager"   r&   r&   r'   morey      zSweeps.more
str | Nonec                 C  r4   )zcReturns the cursor for the next page of sweeps.

        <!-- lazydoc-ignore: internal -->
        N)r   r   r5   r6   
end_cursorr8   r&   r&   r'   cursor   r:   zSweeps.cursorlist[Sweep]c                   sx   ddl m} ddlm}  j }du s|j }du r$d j}t||jdk r+g S  fdd|| |j	
 D S )	zvConverts the last GraphQL response into a list of `Sweep` objects.

        <!-- lazydoc-ignore: internal -->
        r   )
Connection)SweepFragmentNzCould not find project    c                   s"   g | ]}t  j j j|jqS r&   )Sweepr   r   r   name).0noder8   r&   r'   
<listcomp>   s    z*Sweeps.convert_objects.<locals>.<listcomp>)wandb._pydanticr?   r   r@   r   r   
ValueErrorr0   r,   r5   nodes)r"   r?   r@   rspr   msgr&   r8   r'   convert_objects   s   

zSweeps.convert_objectsc                 C  s   d| j  d| j dS )Nz<Sweeps />)r   r   r8   r&   r&   r'   __repr__   s   zSweeps.__repr__)r   )
r   r   r   r   r   r   r   r   r   r   )r   r(   )r   r   )r   r3   )r   r;   )r   r>   )__name__
__module____qualname____doc__r   __annotations__r!   r   r.   propertyr2   r9   r=   rL   rO   __classcell__r&   r&   r$   r'   r   4   s(   
 		r   rB   c                      s   e Zd ZdZ	d7d8 fddZed9ddZed9ddZedd Zd:d;ddZ	edd Z
d7ddZed<ddZed d! Zed"d# Zed$d% Ze					d=d>d+d,Zd?d@d1d2Zd9d3d4Zd9d5d6Z  ZS )ArB   a  The set of runs associated with the sweep.

    Attributes:
        runs (Runs): List of runs
        id (str): Sweep ID
        project (str): The name of the project the sweep belongs to
        config (dict): Dictionary containing the sweep configuration
        state (str): The state of the sweep. Can be "Finished", "Failed",
            "Crashed", or "Running".
        expected_run_count (int): The number of expected runs for the sweep
    Nr   r   r   r   r   sweep_idattrsMapping[str, Any] | Nonec                   sD   t  t|pi  || _|| _|| _|| _g | _| j| d d S )N)force)	r    r!   dictr   _entityr   idrunsload)r"   r   r   r   rW   rX   r$   r&   r'   r!      s   	zSweep.__init__r   c                 C  s   | j S )z%The entity associated with the sweep.)r\   r8   r&   r&   r'   r      s   zSweep.entityc                 C  s   t d | jS )z'Deprecated. Use `Sweep.entity` instead.z>Sweep.username is deprecated. please use Sweep.entity instead.)wandbtermwarnr\   r8   r&   r&   r'   username   s   
zSweep.usernamec                 C  s   t | jd S )z+The sweep configuration used for the sweep.config)r
   	load_yaml_attrsr8   r&   r&   r'   rc      s   zSweep.configFrZ   r3   c                 C  sJ   |s| j s"| | j| j| j| j }std| |j | _ |j| _| j S )zxFetch and update sweep data logged to the run from GraphQL database.

        <!-- lazydoc-ignore: internal -->
        zCould not find sweep )re   getr   r   r   r]   rH   r^   )r"   rZ   sweepr&   r&   r'   r_      s   
z
Sweep.loadc                 C  s\   | j dr*| jdr,| jd dd}|dkrdnd}tj|| jd d  S dS dS )	z#Return the order key for the sweep.rc   metricgoalminimize+-rC   N)re   rf   rc   r   QueryGeneratorformat_order_key)r"   
sort_orderprefixr&   r&   r'   order   s   zSweep.orderc                 C  s   |du r| j }ntj|}|du rtd ntd| dd| jigi}ztj	| j
| j| j||ddd W S  tyC   Y dS w )	zRReturn the best run sorted by the metric defined in config or the order passed in.NzVNo order specified and couldn't find metric in sweep config, returning most recent runzSorting runs by {}$andrg   rA   )rq   filtersr   r   )rq   r   rm   rn   r`   ra   termlogformatr]   Runsr   r   r   
IndexError)r"   rq   rs   r&   r&   r'   best_run   s.   zSweep.best_run
int | Nonec                 C  s   | j dS )zJReturn the number of expected runs in the sweep or None for infinite runs.runCountExpected)re   rf   r8   r&   r&   r'   expected_run_count  s   zSweep.expected_run_countc                 C  s(   t j| jt j| jt j| jgS )zoReturns the path of the project.

        The path is a list containing the entity, project name, and sweep ID.)urllibparse
quote_plusr   r   r]   r8   r&   r&   r'   path  s   z
Sweep.pathc                 C  s$   | j }|dd | jjd| S )zThe URL of the sweep.

        The sweep URL is generated from the entity, project, the term
        "sweeps", and the sweep ID.run_id. For
        SaaS users, it takes the form
        of `https://wandb.ai/entity/project/sweeps/sweeps_ID`.
           r5   rM   )r   insertr   app_urljoin)r"   r   r&   r&   r'   url  s   	z	Sweep.urlc                 C  s   | j dp| jdp| jS )zThe name of the sweep.

        Returns the first name that exists in the following priority order:

        1. User-edited display name
        2. Name configured at creation time
        3. Sweep ID
        displayNamerC   )re   rf   rc   r]   r8   r&   r&   r'   rC   (  s   
z
Sweep.namer;   sidrq   queryDocument | Nonec              	   K  s   ddl m}m}	 |sd}|||d|}
|du rt|}z	|j||
d}W n ty9   t|	}|j||
d}Y nw |rJ|d }rJ|d }sLdS | |||||d	}tj||||d
dd|j	igid|_
|S )a  Execute a query against the cloud backend.

        Args:
            client: The client to use to execute the query.
            entity: The entity (username or team) that owns the project.
            project: The name of the project to fetch sweep from.
            sid: The sweep ID to query.
            order: The order in which the sweep's runs are returned.
            query: The query to use to execute the query.
            **kwargs: Additional keyword arguments to pass to the query.
        r   )GET_SWEEP_GQLGET_SWEEP_LEGACY_GQLz+created_at)r   r   rC   Nr)   r   rg   )rX   
   rr   )rq   r   rs   )r   r   r   r   r+   	Exceptionrf   r   rv   r]   r^   )clsr   r   r   r   rq   r   kwargsr   r   r#   r-   	proj_dict
sweep_dictrg   r&   r&   r'   rf   4  s:   	z	Sweep.get  heightr   hiddenc                 C  sF   | j d }d| d}d}|r|d7 }td}|d|d|d	 S )
z9Generate HTML containing an iframe displaying this sweep.z?jupyter=truezborder:none;width:100%;height:zpx; zdisplay:none;rg   z<iframe src=z style=z
></iframe>)r   r   toggle_button)r"   r   r   r   stylerp   r&   r&   r'   to_htmlm  s   

zSweep.to_htmlc                 C  s   |   S N)r   r8   r&   r&   r'   _repr_html_w  s   zSweep._repr_html_c                 C  s,   d | j}| jdd}d| d| dS )NrM   statezUnknown Statez<Sweep z (z)>)r   r   re   rf   )r"   pathstrr   r&   r&   r'   rO   z  s   zSweep.__repr__r   )
r   r   r   r   r   r   rW   r   rX   rY   )r   r   )F)rZ   r3   )r   ry   )NNNNN)r   r   r   r;   r   r;   r   r;   rq   r;   r   r   )r   F)r   r   r   r3   r   r   )rP   rQ   rR   rS   r!   rU   r   rb   rc   r_   rq   rx   r{   r   r   rC   classmethodrf   r   r   rO   rV   r&   r&   r$   r'   rB      s@    


	



8

) rS   
__future__r   r|   collections.abcr   typingr   r   r   typing_extensionsr   	wandb_gqlr   wandb_graphql.language.astr	   r`   r
   
wandb.apisr   wandb.apis.attrsr   wandb.apis.paginatorr   wandb.sdk.libr   r   r   wandb.apis.public.apir   r   rB   r&   r&   r&   r'   <module>   s&    x