ΠŸΠ΅Ρ€Π΅ΠΉΡ‚ΠΈ ΠΊ содСрТимому

Бсылка для ultralytics/hub/auth.py

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΠ΅

Π­Ρ‚ΠΎΡ‚ Ρ„Π°ΠΉΠ» доступСн ΠΏΠΎ адрСсу https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/hub/auth .py. Если Ρ‚Ρ‹ Π·Π°ΠΌΠ΅Ρ‚ΠΈΠ» ΠΏΡ€ΠΎΠ±Π»Π΅ΠΌΡƒ, поТалуйста, ΠΏΠΎΠΌΠΎΠ³ΠΈ ΠΈΡΠΏΡ€Π°Π²ΠΈΡ‚ΡŒ Π΅Π΅, создав Pull Request πŸ› οΈ. Бпасибо πŸ™!



ultralytics.hub.auth.Auth

УправляСт процСссами Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ†ΠΈΠΈ, Π²ΠΊΠ»ΡŽΡ‡Π°Ρ Ρ€Π°Π±ΠΎΡ‚Ρƒ с API-ΠΊΠ»ΡŽΡ‡Π°ΠΌΠΈ, Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ†ΠΈΡŽ Π½Π° основС ΠΊΡƒΠΊΠΈ ΠΈ Π³Π΅Π½Π΅Ρ€Π°Ρ†ΠΈΡŽ Π·Π°Π³ΠΎΠ»ΠΎΠ²ΠΊΠΎΠ².

Класс ΠΏΠΎΠ΄Π΄Π΅Ρ€ΠΆΠΈΠ²Π°Π΅Ρ‚ Ρ€Π°Π·Π»ΠΈΡ‡Π½Ρ‹Π΅ ΠΌΠ΅Ρ‚ΠΎΠ΄Ρ‹ Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ†ΠΈΠΈ: 1. НСпосрСдствСнно с ΠΏΠΎΠΌΠΎΡ‰ΡŒΡŽ ΠΊΠ»ΡŽΡ‡Π° API. 2. АутСнтификация с ΠΏΠΎΠΌΠΎΡ‰ΡŒΡŽ ΠΊΡƒΠΊΠΈ-Ρ„Π°ΠΉΠ»ΠΎΠ² Π±Ρ€Π°ΡƒΠ·Π΅Ρ€Π° (ΡΠΏΠ΅Ρ†ΠΈΠ°Π»ΡŒΠ½ΠΎ Π² Google Colab). 3. ΠŸΡ€Π΅Π΄Π»ΠΎΠΆΠ΅Π½ΠΈΠ΅ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŽ ввСсти API-ΠΊΠ»ΡŽΡ‡.

Атрибуты:

Имя Вип ОписаниС
id_token str or bool

Π’ΠΎΠΊΠ΅Π½, ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅ΠΌΡ‹ΠΉ для ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ личности, инициализируСтся ΠΊΠ°ΠΊ False.

api_key str or bool

API-ΠΊΠ»ΡŽΡ‡ для Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ†ΠΈΠΈ, ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΠΎΠ²Π°Π½Π½Ρ‹ΠΉ ΠΊΠ°ΠΊ False.

model_key bool

Π—Π°ΠΏΠΎΠ»Π½ΠΈΡ‚Π΅Π»ΡŒ для ΠΊΠ»ΡŽΡ‡Π° ΠΌΠΎΠ΄Π΅Π»ΠΈ, ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΠΎΠ²Π°Π½Π½Ρ‹ΠΉ ΠΊΠ°ΠΊ False.

Π˜ΡΡ…ΠΎΠ΄Π½Ρ‹ΠΉ ΠΊΠΎΠ΄ Π² ultralytics/hub/auth.py
class Auth:
    """
    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 or bool): Token used for identity verification, initialized as False.
        api_key (str or bool): API key for authentication, initialized as False.
        model_key (bool): Placeholder for model key, initialized as False.
    """

    id_token = api_key = model_key = False

    def __init__(self, api_key="", verbose=False):
        """
        Initialize the Auth class with an optional API key.

        Args:
            api_key (str, optional): May be an API key or a combination API key and model ID, i.e. key_id
        """
        # Split the input API key in case it contains a combined key_model and keep only the API key part
        api_key = api_key.split("_")[0]

        # Set API key attribute as value passed or SETTINGS API key if none passed
        self.api_key = api_key or SETTINGS.get("api_key", "")

        # If an API key is provided
        if self.api_key:
            # If the provided API key matches the API key in the SETTINGS
            if self.api_key == SETTINGS.get("api_key"):
                # Log that the user is already logged in
                if verbose:
                    LOGGER.info(f"{PREFIX}Authenticated βœ…")
                return
            else:
                # Attempt to authenticate with the provided API key
                success = self.authenticate()
        # If the API key is not provided and the environment is a Google Colab notebook
        elif IS_COLAB:
            # Attempt to authenticate using browser cookies
            success = self.auth_with_cookies()
        else:
            # Request an API key
            success = self.request_api_key()

        # Update SETTINGS with the new API key after successful authentication
        if success:
            SETTINGS.update({"api_key": self.api_key})
            # Log that the new login was successful
            if verbose:
                LOGGER.info(f"{PREFIX}New authentication successful βœ…")
        elif verbose:
            LOGGER.info(f"{PREFIX}Get API key from {API_KEY_URL} and then run 'yolo hub login API_KEY'")

    def request_api_key(self, max_attempts=3):
        """
        Prompt the user to input their API key.

        Returns the model ID.
        """
        import getpass

        for attempts in range(max_attempts):
            LOGGER.info(f"{PREFIX}Login. Attempt {attempts + 1} of {max_attempts}")
            input_key = getpass.getpass(f"Enter API key from {API_KEY_URL} ")
            self.api_key = input_key.split("_")[0]  # remove model id if present
            if self.authenticate():
                return True
        raise ConnectionError(emojis(f"{PREFIX}Failed to authenticate ❌"))

    def authenticate(self) -> bool:
        """
        Attempt to authenticate with the server using either id_token or API key.

        Returns:
            (bool): True if authentication is successful, False otherwise.
        """
        try:
            if header := self.get_auth_header():
                r = requests.post(f"{HUB_API_ROOT}/v1/auth", headers=header)
                if not r.json().get("success", False):
                    raise ConnectionError("Unable to authenticate.")
                return True
            raise ConnectionError("User has not authenticated locally.")
        except ConnectionError:
            self.id_token = self.api_key = False  # reset invalid
            LOGGER.warning(f"{PREFIX}Invalid API key ⚠️")
            return False

    def auth_with_cookies(self) -> bool:
        """
        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.
        """
        if not IS_COLAB:
            return False  # Currently only works with Colab
        try:
            authn = request_with_credentials(f"{HUB_API_ROOT}/v1/auth/auto")
            if authn.get("success", False):
                self.id_token = authn.get("data", {}).get("idToken", None)
                self.authenticate()
                return True
            raise ConnectionError("Unable to fetch browser authentication details.")
        except ConnectionError:
            self.id_token = False  # reset invalid
            return False

    def get_auth_header(self):
        """
        Get the authentication header for making API requests.

        Returns:
            (dict): The authentication header if id_token or API key is set, None otherwise.
        """
        if self.id_token:
            return {"authorization": f"Bearer {self.id_token}"}
        elif self.api_key:
            return {"x-api-key": self.api_key}

__init__(api_key='', verbose=False)

Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΡƒΠΉ класс Auth с Π½Π΅ΠΎΠ±ΡΠ·Π°Ρ‚Π΅Π»ΡŒΠ½Ρ‹ΠΌ ΠΊΠ»ΡŽΡ‡ΠΎΠΌ API.

ΠŸΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Ρ‹:

Имя Π’ΠΈΠΏ ОписаниС По ΡƒΠΌΠΎΠ»Ρ‡Π°Π½ΠΈΡŽ
api_key str

Π­Ρ‚ΠΎ ΠΌΠΎΠΆΠ΅Ρ‚ Π±Ρ‹Ρ‚ΡŒ API-ΠΊΠ»ΡŽΡ‡ ΠΈΠ»ΠΈ комбинация API-ΠΊΠ»ΡŽΡ‡Π° ΠΈ ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€Π° ΠΌΠΎΠ΄Π΅Π»ΠΈ, Ρ‚ΠΎ Π΅ΡΡ‚ΡŒ key_id

''
Π˜ΡΡ…ΠΎΠ΄Π½Ρ‹ΠΉ ΠΊΠΎΠ΄ Π² ultralytics/hub/auth.py
def __init__(self, api_key="", verbose=False):
    """
    Initialize the Auth class with an optional API key.

    Args:
        api_key (str, optional): May be an API key or a combination API key and model ID, i.e. key_id
    """
    # Split the input API key in case it contains a combined key_model and keep only the API key part
    api_key = api_key.split("_")[0]

    # Set API key attribute as value passed or SETTINGS API key if none passed
    self.api_key = api_key or SETTINGS.get("api_key", "")

    # If an API key is provided
    if self.api_key:
        # If the provided API key matches the API key in the SETTINGS
        if self.api_key == SETTINGS.get("api_key"):
            # Log that the user is already logged in
            if verbose:
                LOGGER.info(f"{PREFIX}Authenticated βœ…")
            return
        else:
            # Attempt to authenticate with the provided API key
            success = self.authenticate()
    # If the API key is not provided and the environment is a Google Colab notebook
    elif IS_COLAB:
        # Attempt to authenticate using browser cookies
        success = self.auth_with_cookies()
    else:
        # Request an API key
        success = self.request_api_key()

    # Update SETTINGS with the new API key after successful authentication
    if success:
        SETTINGS.update({"api_key": self.api_key})
        # Log that the new login was successful
        if verbose:
            LOGGER.info(f"{PREFIX}New authentication successful βœ…")
    elif verbose:
        LOGGER.info(f"{PREFIX}Get API key from {API_KEY_URL} and then run 'yolo hub login API_KEY'")

auth_with_cookies()

ΠŸΠΎΠΏΡ‹Ρ‚ΠΊΠ° ΠΏΠΎΠ»ΡƒΡ‡ΠΈΡ‚ΡŒ Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ†ΠΈΡŽ Ρ‡Π΅Ρ€Π΅Π· cookies ΠΈ ΡƒΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ id_token. ΠŸΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒ Π΄ΠΎΠ»ΠΆΠ΅Π½ Π±Ρ‹Ρ‚ΡŒ Π°Π²Ρ‚ΠΎΡ€ΠΈΠ·ΠΎΠ²Π°Π½ Π½Π° HUB ΠΈ Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ Π² ΠΏΠΎΠ΄Π΄Π΅Ρ€ΠΆΠΈΠ²Π°Π΅ΠΌΠΎΠΌ Π±Ρ€Π°ΡƒΠ·Π΅Ρ€Π΅.

ВозвращаСтся:

Вип ОписаниС
bool

True, Ссли аутСнтификация ΠΏΡ€ΠΎΡˆΠ»Π° ΡƒΡΠΏΠ΅ΡˆΠ½ΠΎ, False Π² ΠΏΡ€ΠΎΡ‚ΠΈΠ²Π½ΠΎΠΌ случаС.

Π˜ΡΡ…ΠΎΠ΄Π½Ρ‹ΠΉ ΠΊΠΎΠ΄ Π² ultralytics/hub/auth.py
def auth_with_cookies(self) -> bool:
    """
    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.
    """
    if not IS_COLAB:
        return False  # Currently only works with Colab
    try:
        authn = request_with_credentials(f"{HUB_API_ROOT}/v1/auth/auto")
        if authn.get("success", False):
            self.id_token = authn.get("data", {}).get("idToken", None)
            self.authenticate()
            return True
        raise ConnectionError("Unable to fetch browser authentication details.")
    except ConnectionError:
        self.id_token = False  # reset invalid
        return False

authenticate()

ΠŸΠΎΠΏΡ‹Ρ‚Π°ΠΉΡΡ Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΡ†ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒΡΡ Π½Π° сСрвСрС, ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΡ Π»ΠΈΠ±ΠΎ id_token, Π»ΠΈΠ±ΠΎ API-ΠΊΠ»ΡŽΡ‡.

ВозвращаСтся:

Вип ОписаниС
bool

True, Ссли аутСнтификация ΠΏΡ€ΠΎΡˆΠ»Π° ΡƒΡΠΏΠ΅ΡˆΠ½ΠΎ, False Π² ΠΏΡ€ΠΎΡ‚ΠΈΠ²Π½ΠΎΠΌ случаС.

Π˜ΡΡ…ΠΎΠ΄Π½Ρ‹ΠΉ ΠΊΠΎΠ΄ Π² ultralytics/hub/auth.py
def authenticate(self) -> bool:
    """
    Attempt to authenticate with the server using either id_token or API key.

    Returns:
        (bool): True if authentication is successful, False otherwise.
    """
    try:
        if header := self.get_auth_header():
            r = requests.post(f"{HUB_API_ROOT}/v1/auth", headers=header)
            if not r.json().get("success", False):
                raise ConnectionError("Unable to authenticate.")
            return True
        raise ConnectionError("User has not authenticated locally.")
    except ConnectionError:
        self.id_token = self.api_key = False  # reset invalid
        LOGGER.warning(f"{PREFIX}Invalid API key ⚠️")
        return False

get_auth_header()

ΠŸΠΎΠ»ΡƒΡ‡ΠΈ Π·Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ†ΠΈΠΈ для выполнСния API-запросов.

ВозвращаСтся:

Вип ОписаниС
dict

Π—Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ†ΠΈΠΈ, Ссли Π·Π°Π΄Π°Π½ id_token ΠΈΠ»ΠΈ API-ΠΊΠ»ΡŽΡ‡, Π² ΠΏΡ€ΠΎΡ‚ΠΈΠ²Π½ΠΎΠΌ случаС - None.

Π˜ΡΡ…ΠΎΠ΄Π½Ρ‹ΠΉ ΠΊΠΎΠ΄ Π² ultralytics/hub/auth.py
def get_auth_header(self):
    """
    Get the authentication header for making API requests.

    Returns:
        (dict): The authentication header if id_token or API key is set, None otherwise.
    """
    if self.id_token:
        return {"authorization": f"Bearer {self.id_token}"}
    elif self.api_key:
        return {"x-api-key": self.api_key}

request_api_key(max_attempts=3)

ΠŸΡ€Π΅Π΄Π»ΠΎΠΆΠΈ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŽ ввСсти свой API-ΠΊΠ»ΡŽΡ‡.

Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ ΠΌΠΎΠ΄Π΅Π»ΠΈ.

Π˜ΡΡ…ΠΎΠ΄Π½Ρ‹ΠΉ ΠΊΠΎΠ΄ Π² ultralytics/hub/auth.py
def request_api_key(self, max_attempts=3):
    """
    Prompt the user to input their API key.

    Returns the model ID.
    """
    import getpass

    for attempts in range(max_attempts):
        LOGGER.info(f"{PREFIX}Login. Attempt {attempts + 1} of {max_attempts}")
        input_key = getpass.getpass(f"Enter API key from {API_KEY_URL} ")
        self.api_key = input_key.split("_")[0]  # remove model id if present
        if self.authenticate():
            return True
    raise ConnectionError(emojis(f"{PREFIX}Failed to authenticate ❌"))





Боздано 2023-11-12, ОбновлСно 2023-11-25
Авторы: glenn-jocher (3)