utils.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import os
  3. import platform
  4. import random
  5. import threading
  6. import time
  7. from pathlib import Path
  8. import requests
  9. from ultralytics.utils import (
  10. ARGV,
  11. ENVIRONMENT,
  12. IS_COLAB,
  13. IS_GIT_DIR,
  14. IS_PIP_PACKAGE,
  15. LOGGER,
  16. ONLINE,
  17. RANK,
  18. SETTINGS,
  19. TESTS_RUNNING,
  20. TQDM,
  21. TryExcept,
  22. __version__,
  23. colorstr,
  24. get_git_origin_url,
  25. )
  26. from ultralytics.utils.downloads import GITHUB_ASSETS_NAMES
  27. HUB_API_ROOT = os.environ.get("ULTRALYTICS_HUB_API", "https://api.ultralytics.com")
  28. HUB_WEB_ROOT = os.environ.get("ULTRALYTICS_HUB_WEB", "https://hub.ultralytics.com")
  29. PREFIX = colorstr("Ultralytics HUB: ")
  30. HELP_MSG = "If this issue persists please visit https://github.com/ultralytics/hub/issues for assistance."
  31. def request_with_credentials(url: str) -> any:
  32. """
  33. Make an AJAX request with cookies attached in a Google Colab environment.
  34. Args:
  35. url (str): The URL to make the request to.
  36. Returns:
  37. (any): The response data from the AJAX request.
  38. Raises:
  39. OSError: If the function is not run in a Google Colab environment.
  40. """
  41. if not IS_COLAB:
  42. raise OSError("request_with_credentials() must run in a Colab environment")
  43. from google.colab import output # noqa
  44. from IPython import display # noqa
  45. display.display(
  46. display.Javascript(
  47. """
  48. window._hub_tmp = new Promise((resolve, reject) => {
  49. const timeout = setTimeout(() => reject("Failed authenticating existing browser session"), 5000)
  50. fetch("%s", {
  51. method: 'POST',
  52. credentials: 'include'
  53. })
  54. .then((response) => resolve(response.json()))
  55. .then((json) => {
  56. clearTimeout(timeout);
  57. }).catch((err) => {
  58. clearTimeout(timeout);
  59. reject(err);
  60. });
  61. });
  62. """
  63. % url
  64. )
  65. )
  66. return output.eval_js("_hub_tmp")
  67. def requests_with_progress(method, url, **kwargs):
  68. """
  69. Make an HTTP request using the specified method and URL, with an optional progress bar.
  70. Args:
  71. method (str): The HTTP method to use (e.g. 'GET', 'POST').
  72. url (str): The URL to send the request to.
  73. **kwargs (any): Additional keyword arguments to pass to the underlying `requests.request` function.
  74. Returns:
  75. (requests.Response): The response object from the HTTP request.
  76. Note:
  77. - If 'progress' is set to True, the progress bar will display the download progress for responses with a known
  78. content length.
  79. - If 'progress' is a number then progress bar will display assuming content length = progress.
  80. """
  81. progress = kwargs.pop("progress", False)
  82. if not progress:
  83. return requests.request(method, url, **kwargs)
  84. response = requests.request(method, url, stream=True, **kwargs)
  85. total = int(response.headers.get("content-length", 0) if isinstance(progress, bool) else progress) # total size
  86. try:
  87. pbar = TQDM(total=total, unit="B", unit_scale=True, unit_divisor=1024)
  88. for data in response.iter_content(chunk_size=1024):
  89. pbar.update(len(data))
  90. pbar.close()
  91. except requests.exceptions.ChunkedEncodingError: # avoid 'Connection broken: IncompleteRead' warnings
  92. response.close()
  93. return response
  94. def smart_request(method, url, retry=3, timeout=30, thread=True, code=-1, verbose=True, progress=False, **kwargs):
  95. """
  96. Makes an HTTP request using the 'requests' library, with exponential backoff retries up to a specified timeout.
  97. Args:
  98. method (str): The HTTP method to use for the request. Choices are 'post' and 'get'.
  99. url (str): The URL to make the request to.
  100. retry (int, optional): Number of retries to attempt before giving up. Default is 3.
  101. timeout (int, optional): Timeout in seconds after which the function will give up retrying. Default is 30.
  102. thread (bool, optional): Whether to execute the request in a separate daemon thread. Default is True.
  103. code (int, optional): An identifier for the request, used for logging purposes. Default is -1.
  104. verbose (bool, optional): A flag to determine whether to print out to console or not. Default is True.
  105. progress (bool, optional): Whether to show a progress bar during the request. Default is False.
  106. **kwargs (any): Keyword arguments to be passed to the requests function specified in method.
  107. Returns:
  108. (requests.Response): The HTTP response object. If the request is executed in a separate thread, returns None.
  109. """
  110. retry_codes = (408, 500) # retry only these codes
  111. @TryExcept(verbose=verbose)
  112. def func(func_method, func_url, **func_kwargs):
  113. """Make HTTP requests with retries and timeouts, with optional progress tracking."""
  114. r = None # response
  115. t0 = time.time() # initial time for timer
  116. for i in range(retry + 1):
  117. if (time.time() - t0) > timeout:
  118. break
  119. r = requests_with_progress(func_method, func_url, **func_kwargs) # i.e. get(url, data, json, files)
  120. if r.status_code < 300: # return codes in the 2xx range are generally considered "good" or "successful"
  121. break
  122. try:
  123. m = r.json().get("message", "No JSON message.")
  124. except AttributeError:
  125. m = "Unable to read JSON."
  126. if i == 0:
  127. if r.status_code in retry_codes:
  128. m += f" Retrying {retry}x for {timeout}s." if retry else ""
  129. elif r.status_code == 429: # rate limit
  130. h = r.headers # response headers
  131. m = (
  132. f"Rate limit reached ({h['X-RateLimit-Remaining']}/{h['X-RateLimit-Limit']}). "
  133. f"Please retry after {h['Retry-After']}s."
  134. )
  135. if verbose:
  136. LOGGER.warning(f"{PREFIX}{m} {HELP_MSG} ({r.status_code} #{code})")
  137. if r.status_code not in retry_codes:
  138. return r
  139. time.sleep(2**i) # exponential standoff
  140. return r
  141. args = method, url
  142. kwargs["progress"] = progress
  143. if thread:
  144. threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True).start()
  145. else:
  146. return func(*args, **kwargs)
  147. class Events:
  148. """
  149. A class for collecting anonymous event analytics. Event analytics are enabled when sync=True in settings and
  150. disabled when sync=False. Run 'yolo settings' to see and update settings YAML file.
  151. Attributes:
  152. url (str): The URL to send anonymous events.
  153. rate_limit (float): The rate limit in seconds for sending events.
  154. metadata (dict): A dictionary containing metadata about the environment.
  155. enabled (bool): A flag to enable or disable Events based on certain conditions.
  156. """
  157. url = "https://www.google-analytics.com/mp/collect?measurement_id=G-X8NCJYTQXM&api_secret=QLQrATrNSwGRFRLE-cbHJw"
  158. def __init__(self):
  159. """Initializes the Events object with default values for events, rate_limit, and metadata."""
  160. self.events = [] # events list
  161. self.rate_limit = 60.0 # rate limit (seconds)
  162. self.t = 0.0 # rate limit timer (seconds)
  163. self.metadata = {
  164. "cli": Path(ARGV[0]).name == "yolo",
  165. "install": "git" if IS_GIT_DIR else "pip" if IS_PIP_PACKAGE else "other",
  166. "python": ".".join(platform.python_version_tuple()[:2]), # i.e. 3.10
  167. "version": __version__,
  168. "env": ENVIRONMENT,
  169. "session_id": round(random.random() * 1e15),
  170. "engagement_time_msec": 1000,
  171. }
  172. self.enabled = (
  173. SETTINGS["sync"]
  174. and RANK in {-1, 0}
  175. and not TESTS_RUNNING
  176. and ONLINE
  177. and (IS_PIP_PACKAGE or get_git_origin_url() == "https://github.com/ultralytics/ultralytics.git")
  178. )
  179. def __call__(self, cfg):
  180. """
  181. Attempts to add a new event to the events list and send events if the rate limit is reached.
  182. Args:
  183. cfg (IterableSimpleNamespace): The configuration object containing mode and task information.
  184. """
  185. if not self.enabled:
  186. # Events disabled, do nothing
  187. return
  188. # Attempt to add to events
  189. if len(self.events) < 25: # Events list limited to 25 events (drop any events past this)
  190. params = {
  191. **self.metadata,
  192. "task": cfg.task,
  193. "model": cfg.model if cfg.model in GITHUB_ASSETS_NAMES else "custom",
  194. }
  195. if cfg.mode == "export":
  196. params["format"] = cfg.format
  197. self.events.append({"name": cfg.mode, "params": params})
  198. # Check rate limit
  199. t = time.time()
  200. if (t - self.t) < self.rate_limit:
  201. # Time is under rate limiter, wait to send
  202. return
  203. # Time is over rate limiter, send now
  204. data = {"client_id": SETTINGS["uuid"], "events": self.events} # SHA-256 anonymized UUID hash and events list
  205. # POST equivalent to requests.post(self.url, json=data)
  206. smart_request("post", self.url, json=data, retry=0, verbose=False)
  207. # Reset events and rate limit timer
  208. self.events = []
  209. self.t = t
  210. # Run below code on hub/utils init -------------------------------------------------------------------------------------
  211. events = Events()