Π£ΠΏΡΠ°Π²Π»ΡΠ΅Ρ ΠΏΡΠΎΡΠ΅ΡΡΠ°ΠΌΠΈ Π°ΡΡΠ΅Π½ΡΠΈΡΠΈΠΊΠ°ΡΠΈΠΈ, Π²ΠΊΠ»ΡΡΠ°Ρ ΡΠ°Π±ΠΎΡΡ Ρ 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
|
ΠΠΎΠ»ΡΡΠΈ Π·Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ Π°ΡΡΠ΅Π½ΡΠΈΡΠΈΠΊΠ°ΡΠΈΠΈ Π΄Π»Ρ Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ 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 β"))
|