__init__.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import requests
  3. from ultralytics.data.utils import HUBDatasetStats
  4. from ultralytics.hub.auth import Auth
  5. from ultralytics.hub.session import HUBTrainingSession
  6. from ultralytics.hub.utils import HUB_API_ROOT, HUB_WEB_ROOT, PREFIX, events
  7. from ultralytics.utils import LOGGER, SETTINGS, checks
  8. __all__ = (
  9. "PREFIX",
  10. "HUB_WEB_ROOT",
  11. "HUBTrainingSession",
  12. "login",
  13. "logout",
  14. "reset_model",
  15. "export_fmts_hub",
  16. "export_model",
  17. "get_export",
  18. "check_dataset",
  19. "events",
  20. )
  21. def login(api_key: str = None, save=True) -> bool:
  22. """
  23. Log in to the Ultralytics HUB API using the provided API key.
  24. The session is not stored; a new session is created when needed using the saved SETTINGS or the HUB_API_KEY
  25. environment variable if successfully authenticated.
  26. Args:
  27. api_key (str, optional): API key to use for authentication.
  28. If not provided, it will be retrieved from SETTINGS or HUB_API_KEY environment variable.
  29. save (bool, optional): Whether to save the API key to SETTINGS if authentication is successful.
  30. Returns:
  31. (bool): True if authentication is successful, False otherwise.
  32. """
  33. checks.check_requirements("hub-sdk>=0.0.12")
  34. from hub_sdk import HUBClient
  35. api_key_url = f"{HUB_WEB_ROOT}/settings?tab=api+keys" # set the redirect URL
  36. saved_key = SETTINGS.get("api_key")
  37. active_key = api_key or saved_key
  38. credentials = {"api_key": active_key} if active_key and active_key != "" else None # set credentials
  39. client = HUBClient(credentials) # initialize HUBClient
  40. if client.authenticated:
  41. # Successfully authenticated with HUB
  42. if save and client.api_key != saved_key:
  43. SETTINGS.update({"api_key": client.api_key}) # update settings with valid API key
  44. # Set message based on whether key was provided or retrieved from settings
  45. log_message = (
  46. "New authentication successful ✅" if client.api_key == api_key or not credentials else "Authenticated ✅"
  47. )
  48. LOGGER.info(f"{PREFIX}{log_message}")
  49. return True
  50. else:
  51. # Failed to authenticate with HUB
  52. LOGGER.info(f"{PREFIX}Get API key from {api_key_url} and then run 'yolo login API_KEY'")
  53. return False
  54. def logout():
  55. """
  56. Log out of Ultralytics HUB by removing the API key from the settings file. To log in again, use 'yolo login'.
  57. Example:
  58. ```python
  59. from ultralytics import hub
  60. hub.logout()
  61. ```
  62. """
  63. SETTINGS["api_key"] = ""
  64. LOGGER.info(f"{PREFIX}logged out ✅. To log in again, use 'yolo login'.")
  65. def reset_model(model_id=""):
  66. """Reset a trained model to an untrained state."""
  67. r = requests.post(f"{HUB_API_ROOT}/model-reset", json={"modelId": model_id}, headers={"x-api-key": Auth().api_key})
  68. if r.status_code == 200:
  69. LOGGER.info(f"{PREFIX}Model reset successfully")
  70. return
  71. LOGGER.warning(f"{PREFIX}Model reset failure {r.status_code} {r.reason}")
  72. def export_fmts_hub():
  73. """Returns a list of HUB-supported export formats."""
  74. from ultralytics.engine.exporter import export_formats
  75. return list(export_formats()["Argument"][1:]) + ["ultralytics_tflite", "ultralytics_coreml"]
  76. def export_model(model_id="", format="torchscript"):
  77. """Export a model to all formats."""
  78. assert format in export_fmts_hub(), f"Unsupported export format '{format}', valid formats are {export_fmts_hub()}"
  79. r = requests.post(
  80. f"{HUB_API_ROOT}/v1/models/{model_id}/export", json={"format": format}, headers={"x-api-key": Auth().api_key}
  81. )
  82. assert r.status_code == 200, f"{PREFIX}{format} export failure {r.status_code} {r.reason}"
  83. LOGGER.info(f"{PREFIX}{format} export started ✅")
  84. def get_export(model_id="", format="torchscript"):
  85. """Get an exported model dictionary with download URL."""
  86. assert format in export_fmts_hub(), f"Unsupported export format '{format}', valid formats are {export_fmts_hub()}"
  87. r = requests.post(
  88. f"{HUB_API_ROOT}/get-export",
  89. json={"apiKey": Auth().api_key, "modelId": model_id, "format": format},
  90. headers={"x-api-key": Auth().api_key},
  91. )
  92. assert r.status_code == 200, f"{PREFIX}{format} get_export failure {r.status_code} {r.reason}"
  93. return r.json()
  94. def check_dataset(path: str, task: str) -> None:
  95. """
  96. Function for error-checking HUB dataset Zip file before upload. It checks a dataset for errors before it is uploaded
  97. to the HUB. Usage examples are given below.
  98. Args:
  99. path (str): Path to data.zip (with data.yaml inside data.zip).
  100. task (str): Dataset task. Options are 'detect', 'segment', 'pose', 'classify', 'obb'.
  101. Example:
  102. Download *.zip files from https://github.com/ultralytics/hub/tree/main/example_datasets
  103. i.e. https://github.com/ultralytics/hub/raw/main/example_datasets/coco8.zip for coco8.zip.
  104. ```python
  105. from ultralytics.hub import check_dataset
  106. check_dataset("path/to/coco8.zip", task="detect") # detect dataset
  107. check_dataset("path/to/coco8-seg.zip", task="segment") # segment dataset
  108. check_dataset("path/to/coco8-pose.zip", task="pose") # pose dataset
  109. check_dataset("path/to/dota8.zip", task="obb") # OBB dataset
  110. check_dataset("path/to/imagenet10.zip", task="classify") # classification dataset
  111. ```
  112. """
  113. HUBDatasetStats(path=path, task=task).get_json()
  114. LOGGER.info(f"Checks completed correctly ✅. Upload this dataset to {HUB_WEB_ROOT}/datasets/.")