o
    Vh                      @   sj   d dl Zd dlZd dlZd dlmZmZmZ d dlZG dd dZ	e
dkr3e	 Zejddddd	ZdS dS )
    N)ListOptionalTuplec                   @   s   e Zd ZdZdd Zdee fddZdee fddZe	dd
ede
deeeeeef fddZ						dde
dedee
 de
deeeeeeef  f
ddZdS )
GCPRegionsa]  
    A class for managing and analyzing Google Cloud Platform (GCP) regions.

    This class provides functionality to initialize, categorize, and analyze GCP regions based on their
    geographical location, tier classification, and network latency.

    Attributes:
        regions (Dict[str, Tuple[int, str, str]]): A dictionary of GCP regions with their tier, city, and country.

    Methods:
        tier1: Returns a list of tier 1 GCP regions.
        tier2: Returns a list of tier 2 GCP regions.
        lowest_latency: Determines the GCP region(s) with the lowest network latency.

    Examples:
        >>> from ultralytics.hub.google import GCPRegions
        >>> regions = GCPRegions()
        >>> lowest_latency_region = regions.lowest_latency(verbose=True, attempts=3)
        >>> print(f"Lowest latency region: {lowest_latency_region[0][0]}")
    c                 C   s   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"i d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdI| _ dJS )KzaInitializes the GCPRegions class with predefined Google Cloud Platform regions and their details.z
asia-east1)   TaiwanChinaz
asia-east2)   z	Hong Kongr   zasia-northeast1)r   TokyoJapanzasia-northeast2)r   Osakar   zasia-northeast3)r	   SeoulzSouth Koreazasia-south1)r	   MumbaiIndiazasia-south2)r	   Delhir   zasia-southeast1)r	   zJurong West	Singaporezasia-southeast2)r	   Jakarta	Indonesiazaustralia-southeast1)r	   Sydney	Australiazaustralia-southeast2)r	   	Melbourner   zeurope-central2)r	   WarsawPolandzeurope-north1)r   HaminaFinlandzeurope-southwest1)r   MadridSpainzeurope-west1)r   zSt. GhislainBelgiumzeurope-west10)r	   BerlinGermanyzeurope-west12)r	   TurinItalyzeurope-west2)r	   LondonzUnited Kingdomzeurope-west3)r	   	Frankfurtr   zeurope-west4)r   	EemshavenNetherlandszeurope-west6)r	   ZurichSwitzerlandzeurope-west8)r   Milanr!   zeurope-west9)r   ParisFrancezme-central1)r	   DohaQatarzme-west1)r   zTel AvivIsraelznorthamerica-northeast1)r	   MontrealCanadaznorthamerica-northeast2)r	   Torontor/   zsouthamerica-east1)r	   u
   São PauloBrazilzsouthamerica-west1)r	   SantiagoChilezus-central1)r   IowaUnited Stateszus-east1)r   zSouth Carolinar5   zus-east4)r   zNorthern Virginiar5   zus-east5)r   Columbusr5   z	us-south1)r   Dallasr5   )r   Oregonr5   )r	   zLos Angelesr5   )r	   zSalt Lake Cityr5   )r	   z	Las Vegasr5   )zus-west1zus-west2zus-west3zus-west4N)regionsself r<   S/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/hub/google/__init__.py__init__!   s   	
 !"#zGCPRegions.__init__returnc                 C      dd | j  D S )zPReturns a list of GCP regions classified as tier 1 based on predefined criteria.c                 S       g | ]\}}|d  dkr|qS )r   r   r<   .0regioninfor<   r<   r=   
<listcomp>N        z$GCPRegions.tier1.<locals>.<listcomp>r9   itemsr:   r<   r<   r=   tier1L      zGCPRegions.tier1c                 C   r@   )zPReturns a list of GCP regions classified as tier 2 based on predefined criteria.c                 S   rA   )r   r	   r<   rB   r<   r<   r=   rF   R   rG   z$GCPRegions.tier2.<locals>.<listcomp>rH   r:   r<   r<   r=   tier2P   rK   zGCPRegions.tier2r   rD   attemptsc              	   C   s   d|  d}g }t |D ],}z t }tj|dd}t | d }|tdkr-|| W q tjy8   Y qw |sJ| tdtdtdtdfS t|dkrUt	|nd}| t
||t|t|fS )	a  
        Ping a specified GCP region and measure network latency statistics.

        Args:
                region (str): The GCP region identifier to ping (e.g., 'us-central1').
                attempts (int): Number of ping attempts to make for calculating statistics.

        Returns:
                region (str): The GCP region identifier that was pinged.
                mean_latency (float): Mean latency in milliseconds, or infinity if all pings failed.
                min_latency (float): Minimum latency in milliseconds, or infinity if all pings failed.
                max_latency (float): Maximum latency in milliseconds, or infinity if all pings failed.
                std_dev (float): Standard deviation of latencies in milliseconds, or infinity if all pings failed.

        Examples:
                >>> region, mean, min_lat, max_lat, std = GCPRegions._ping_region("us-central1", attempts=3)
                >>> print(f"Region {region} has mean latency: {mean:.2f}ms")
        zhttps://z-docker.pkg.dev   )timeouti  infr   r   )rangetimerequestsheadfloatappendRequestExceptionlen
statisticsstdevmeanminmax)rD   rM   url	latencies_
start_timelatencystd_devr<   r<   r=   _ping_regionT   s"   
zGCPRegions._ping_regionFNtopverbosetierc                    s  |rt d  d dkrdnd d r!fddj D ntj }tjjd	d
}t| fdd|}W d   n1 sGw   Y  t	|dd d}|rt ddddddddd |D ]M\}	}
}}}j|	 \}}| d| }|
t
dkrt |	dd|dddd qht |	dd|dddd|
dd|dd|dd|dd qht d|dkrd nd! d" |d| D ]0\}	}
}}}j|	 \}}| d| }t |	 d| d|
dd|dd#|dd|dd$ q|d| S )%ax  
        Determines the GCP regions with the lowest latency based on ping tests.

        Args:
            top (int): Number of top regions to return.
            verbose (bool): If True, prints detailed latency information for all tested regions.
            tier (int | None): Filter regions by tier (1 or 2). If None, all regions are tested.
            attempts (int): Number of ping attempts per region.

        Returns:
            (List[Tuple[str, float, float, float, float]]): List of tuples containing region information and
            latency statistics. Each tuple contains (region, mean_latency, std_dev, min_latency, max_latency).

        Examples:
            >>> regions = GCPRegions()
            >>> results = regions.lowest_latency(top=3, verbose=True, tier=1, attempts=2)
            >>> print(results[0][0])  # Print the name of the lowest latency region
        z&Testing GCP regions for latency (with  r   retryrM   z)...c                    s    g | ]\}}|d   kr|qS )r   r<   )rC   kv)rg   r<   r=   rF      rG   z-GCPRegions.lowest_latency.<locals>.<listcomp>2   )max_workersc                    s    |  S )N)rd   )r)rM   r;   r<   r=   <lambda>   s    z+GCPRegions.lowest_latency.<locals>.<lambda>Nc                 S   s   | d S )Nr   r<   )xr<   r<   r=   ro      s    )keyRegionz<25Locationz<35Tierz<5z Latency (ms)z, rP   z Timeoutz.0fu    ± z (z - )z
Lowest latency regions :z ms (z)))printr9   rI   listkeys
concurrentfuturesThreadPoolExecutormapsortedrU   )r;   re   rf   rg   rM   regions_to_testexecutorresultssorted_resultsrD   r[   stdmin_max_citycountrylocationr<   )rM   r;   rg   r=   lowest_latencyy   s*   "* "B6zGCPRegions.lowest_latency)r   )r   FNr   )__name__
__module____qualname____doc__r>   r   strrJ   rL   staticmethodintr   rU   rd   boolr   r   r<   r<   r<   r=   r      s,    +(&r   __main__   Tr   )re   rf   rg   rM   )concurrent.futuresr|   rY   rR   typingr   r   r   rS   r   r   r9   r   top_3_latency_tier1r<   r<   r<   r=   <module>   s    $