
    |h                     Z    d dl Z d dlmZmZmZmZ d dlmZmZm	Z	m
Z
 e dZ G d d      Zy)    N)HUB_API_ROOTHUB_WEB_ROOTPREFIXrequest_with_credentials)IS_COLABLOGGERSETTINGSemojisz/settings?tab=api+keysc                   ^    e Zd ZdZdxZxZZddedefdZ	dde
defdZdefd	Zdefd
Zd Zy)Authaz  
    Manages authentication processes including API key handling, cookie-based authentication, and header generation.

    The class supports different methods of authentication:
    1. Directly using an API key.
    2. Authenticating using browser cookies (specifically in Google Colab).
    3. Prompting the user to enter an API key.

    Attributes:
        id_token (str | bool): Token used for identity verification, initialized as False.
        api_key (str | bool): API key for authentication, initialized as False.
        model_key (bool): Placeholder for model key, initialized as False.

    Methods:
        authenticate: Attempt to authenticate with the server using either id_token or API key.
        auth_with_cookies: Attempt to fetch authentication via cookies and set id_token.
        get_auth_header: Get the authentication header for making API requests.
        request_api_key: Prompt the user to input their API key.

    Examples:
        Initialize Auth with an API key
        >>> auth = Auth(api_key="your_api_key_here")

        Initialize Auth without API key (will prompt for input)
        >>> auth = Auth()
    Fapi_keyverbosec                 H   |j                  dd      d   }|xs t        j                  dd      | _        | j                  rR| j                  t        j                  d      k(  r|rt	        j
                  t         d       y| j                         }n't        r| j                         }n| j                         }|rAt        j                  d| j                  i       |rt	        j
                  t         d       yy|r$t	        j
                  t         d	t         d
       yy)aP  
        Initialize Auth class and authenticate user.

        Handles API key validation, Google Colab authentication, and new key requests. Updates SETTINGS upon successful
        authentication.

        Args:
            api_key (str): API key or combined key_id format.
            verbose (bool): Enable verbose logging.
        _   r   r    u   Authenticated ✅Nu!   New authentication successful ✅zGet API key from z" and then run 'yolo login API_KEY')splitr	   getr   r   infor   authenticater   auth_with_cookiesrequest_api_keyupdateAPI_KEY_URL)selfr   r   successs       S/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/hub/auth.py__init__zAuth.__init__)   s     --Q'* =(,,y""= <<||x||I66KK6(*; <= ++-,,.G **,G OOY56vh&GHI KK6("3K=@bcd     max_attemptsreturnc                 2   ddl }t        |      D ]k  }t        j                  t         d|dz    d|        |j                  dt
         d      }|j                  dd      d   | _        | j                         sk y	 t        t        t         d
            )z
        Prompt the user to input their API key.

        Args:
            max_attempts (int): Maximum number of authentication attempts.

        Returns:
            (bool): True if authentication is successful, False otherwise.
        r   NzLogin. Attempt r   z of zEnter API key from  r   Tu   Failed to authenticate ❌)getpassranger   r   r   r   r   r   r   ConnectionErrorr
   )r   r    r$   attempts	input_keys        r   r   zAuth.request_api_keyV   s     	l+ 	HKK6(/(Q,tL>RS*=k]!(LMI$??3215DL  "	 fx/I%JKLLr   c                 D   	 | j                         x}rJt        j                  t         d|      }|j	                         j                  dd      st        d      yt        d      # t        $ r- dx| _        | _        t        j                  t         d       Y yw xY w)	z
        Attempt to authenticate with the server using either id_token or API key.

        Returns:
            (bool): True if authentication is successful, False otherwise.
        z/v1/auth)headersr   FzUnable to authenticate.Tz#User has not authenticated locally.zInvalid API key)get_auth_headerrequestspostr   jsonr   r&   id_tokenr   r   warningr   )r   headerrs      r   r   zAuth.authenticatej   s    
	--//v/MM\N(";VLvvx||Iu5)*CDD!"GHH 	+00DMDLNNfX_56	s   AA) A) )3BBc                    t         sy	 t        t         d      }|j                  dd      r8|j                  di       j                  dd      | _        | j                          yt        d      # t        $ r
 d| _        Y yw xY w)	z
        Attempt to fetch authentication via cookies and set id_token.

        User must be logged in to HUB and running in a supported browser.

        Returns:
            (bool): True if authentication is successful, False otherwise.
        Fz/v1/auth/autor   dataidTokenNTz/Unable to fetch browser authentication details.)r   r   r   r   r/   r   r&   )r   authns     r   r   zAuth.auth_with_cookies}   s     		,~]-KLEyyE* %		&" 5 9 9)T J!!#!"STT 	!DM	s   AA0 %A0 0BBc                 r    | j                   rdd| j                    iS | j                  rd| j                  iS y)z
        Get the authentication header for making API requests.

        Returns:
            (dict | None): The authentication header if id_token or API key is set, None otherwise.
        authorizationzBearer z	x-api-keyN)r/   r   )r   s    r   r+   zAuth.get_auth_header   s<     ==#wt}}o%>??\\.. r   N)r   F)   )__name__
__module____qualname____doc__r/   r   	model_keystrboolr   intr   r   r   r+    r   r   r   r      sb    6 &+*H*w+e +e4 +eZMC M M(d &4 ,
/r   r   )r,   ultralytics.hub.utilsr   r   r   r   ultralytics.utilsr   r   r	   r
   r   r   rB   r   r   <module>rE      s/     ^ ^ @ @45R/ R/r   