term.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. """Global functions for interacting with the terminal for wandb.
  2. The functions termlog, termwarn and termerror print to stderr.
  3. The function terminput prints to stderr and reads from stdin.
  4. We print to stderr because wandb does not output any messages that are useful
  5. to pipe to another program. Using stderr allows using wandb in a program that
  6. *does* output pipe-able text.
  7. """
  8. from __future__ import annotations
  9. import contextlib
  10. import logging
  11. import os
  12. import re
  13. import shutil
  14. import sys
  15. import threading
  16. from typing import TYPE_CHECKING, Iterator, Protocol
  17. import click
  18. if TYPE_CHECKING:
  19. import wandb
  20. LOG_STRING = click.style("wandb", fg="blue", bold=True)
  21. LOG_STRING_NOCOLOR = "wandb"
  22. ERROR_STRING = click.style("ERROR", bg="red", fg="green")
  23. WARN_STRING = click.style("WARNING", fg="yellow")
  24. _silent: bool = False
  25. """If true, _logger is used instead of printing to stderr."""
  26. _logger: SupportsLeveledLogging | None = None
  27. """A fallback logger for _silent mode."""
  28. _show_info: bool = True
  29. """If false, then termlog() uses silent mode (see _silent)."""
  30. _show_warnings: bool = True
  31. """If false, then termwarn() uses silent mode (see _silent)."""
  32. _show_errors: bool = True
  33. """If false, then termerror() uses silent mode (see _silent)."""
  34. _printed_messages: set[str] = set()
  35. """Messages logged with repeat=False."""
  36. _dynamic_text_lock = threading.Lock()
  37. """Lock held for dynamic text operations.
  38. All uses of `_dynamic_blocks` and calls to functions that start with
  39. the `_l_` prefix must be guarded by this lock.
  40. """
  41. _dynamic_blocks: list[DynamicBlock] = []
  42. """Active dynamic text areas, created with dynamic_text()."""
  43. class NotATerminalError(Exception):
  44. """The output device is not sufficiently capable for the operation."""
  45. class SupportsLeveledLogging(Protocol):
  46. """Portion of the standard logging.Logger used in this module."""
  47. def info(self, msg: str) -> None: ...
  48. def warning(self, msg: str) -> None: ...
  49. def error(self, msg: str) -> None: ...
  50. def termsetup(
  51. settings: wandb.Settings,
  52. logger: SupportsLeveledLogging | None,
  53. ) -> None:
  54. """Configure the global logging functions.
  55. Args:
  56. settings: The settings object passed to wandb.setup() or wandb.init().
  57. logger: A fallback logger to use for "silent" mode. In this mode,
  58. the logger is used instead of printing to stderr.
  59. """
  60. global _silent, _show_info, _show_warnings, _show_errors, _logger
  61. _silent = settings.silent
  62. _show_info = settings.show_info
  63. _show_warnings = settings.show_warnings
  64. _show_errors = settings.show_errors
  65. _logger = logger
  66. @contextlib.contextmanager
  67. def dynamic_text() -> Iterator[DynamicBlock | None]:
  68. """A context manager that provides a handle to a new dynamic text area.
  69. The text goes to stderr. Returns None if dynamic text is not supported.
  70. Dynamic text must only be used while `wandb` has control of the terminal,
  71. or else text written by other programs will be overwritten. It's
  72. appropriate to use during a blocking operation.
  73. ```
  74. with term.dynamic_text() as text_area:
  75. if text_area:
  76. text_area.set_text("Writing to a terminal.")
  77. for i in range(2000):
  78. text_area.set_text(f"Still going... ({i}/2000)")
  79. time.sleep(0.001)
  80. else:
  81. wandb.termlog("Writing to a file or dumb terminal.")
  82. time.sleep(1)
  83. wandb.termlog("Finished 1000/2000 tasks, still working...")
  84. time.sleep(1)
  85. wandb.termlog("Done!", err=True)
  86. ```
  87. """
  88. # For now, dynamic text always corresponds to the "INFO" level.
  89. if _silent or not _show_info:
  90. yield None
  91. return
  92. # NOTE: In Jupyter notebooks, this will return False. Notebooks
  93. # support ANSI color sequences and the '\r' character, but not
  94. # cursor motions or line clear commands.
  95. if not _sys_stderr_isatty() or _is_term_dumb():
  96. yield None
  97. return
  98. # NOTE: On Windows < 10, ANSI escape sequences such as \x1b[Am and \x1b[2K,
  99. # used to move the cursor and clear text, aren't supported by the built-in
  100. # console. However, we rely on the click library's use of colorama which
  101. # emulates support for such sequences.
  102. #
  103. # For this reason, we don't have special checks for Windows.
  104. block = DynamicBlock()
  105. with _dynamic_text_lock:
  106. _dynamic_blocks.append(block)
  107. try:
  108. yield block
  109. finally:
  110. with _dynamic_text_lock:
  111. block._lines_to_print = []
  112. _l_rerender_dynamic_blocks()
  113. _dynamic_blocks.remove(block)
  114. def _sys_stderr_isatty() -> bool:
  115. """Returns sys.stderr.isatty().
  116. Defined here for patching in tests.
  117. """
  118. return _isatty(sys.stderr)
  119. def _sys_stdin_isatty() -> bool:
  120. """Returns sys.stdin.isatty().
  121. Defined here for patching in tests.
  122. """
  123. return _isatty(sys.stdin)
  124. def _isatty(stream: object) -> bool:
  125. """Returns true if the stream defines isatty and returns true for it.
  126. This is needed because some people patch `sys.stderr` / `sys.stdin`
  127. with incompatible objects, e.g. a Logger.
  128. Args:
  129. stream: An IO object like stdin or stderr.
  130. """
  131. isatty = getattr(stream, "isatty", None)
  132. if not isatty or not callable(isatty):
  133. return False
  134. try:
  135. return bool(isatty())
  136. except TypeError: # if isatty has required arguments
  137. return False
  138. def _is_term_dumb() -> bool:
  139. """Returns whether the TERM environment variable is set to 'dumb'.
  140. This is a convention to indicate that the terminal doesn't support
  141. ANSI sequences like colors, clearing the screen and positioning the cursor.
  142. """
  143. return os.getenv("TERM") == "dumb"
  144. def termlog(
  145. string: str = "",
  146. newline: bool = True,
  147. repeat: bool = True,
  148. prefix: bool = True,
  149. ) -> None:
  150. r"""Log an informational message to stderr.
  151. The message may contain ANSI color sequences and the \n character.
  152. Colors are stripped if stderr is not a TTY.
  153. Args:
  154. string: The message to display.
  155. newline: Whether to add a newline to the end of the string.
  156. repeat: If false, then the string is not printed if an exact match has
  157. already been printed through any of the other logging functions
  158. in this file.
  159. prefix: Whether to include the 'wandb:' prefix.
  160. """
  161. _log(
  162. string,
  163. newline=newline,
  164. repeat=repeat,
  165. prefix=prefix,
  166. silent=not _show_info,
  167. )
  168. def termwarn(
  169. string: str,
  170. newline: bool = True,
  171. repeat: bool = True,
  172. prefix: bool = True,
  173. ) -> None:
  174. """Log a warning to stderr.
  175. The arguments are the same as for `termlog()`.
  176. """
  177. string = "\n".join([f"{WARN_STRING} {s}" for s in string.split("\n")])
  178. _log(
  179. string,
  180. newline=newline,
  181. repeat=repeat,
  182. prefix=prefix,
  183. silent=not _show_warnings,
  184. level=logging.WARNING,
  185. )
  186. def termerror(
  187. string: str,
  188. newline: bool = True,
  189. repeat: bool = True,
  190. prefix: bool = True,
  191. ) -> None:
  192. """Log an error to stderr.
  193. The arguments are the same as for `termlog()`.
  194. """
  195. string = "\n".join([f"{ERROR_STRING} {s}" for s in string.split("\n")])
  196. _log(
  197. string,
  198. newline=newline,
  199. repeat=repeat,
  200. prefix=prefix,
  201. silent=not _show_errors,
  202. level=logging.ERROR,
  203. )
  204. def _in_jupyter() -> bool:
  205. """Returns True if we're in a Jupyter notebook."""
  206. # Lazy import to avoid circular imports.
  207. from wandb.sdk.lib import ipython
  208. return ipython.in_jupyter()
  209. def can_use_terminput() -> bool:
  210. """Returns True if terminput won't raise a NotATerminalError."""
  211. if _silent or not _show_info or _is_term_dumb():
  212. return False
  213. from wandb import util
  214. # TODO: Verify the databricks check is still necessary.
  215. # Originally added to fix WB-5264.
  216. if util._is_databricks():
  217. return False
  218. # isatty() returns false in Jupyter, but it's OK to output ANSI color
  219. # sequences and to read from stdin.
  220. return _in_jupyter() or (_sys_stderr_isatty() and _sys_stdin_isatty())
  221. def terminput(
  222. prompt: str,
  223. *,
  224. timeout: float | None = None,
  225. hide: bool = False,
  226. ) -> str:
  227. """Prompt the user for input.
  228. Args:
  229. prompt: The prompt to display. The prompt is printed without a newline
  230. and the cursor is positioned after the prompt's last character.
  231. The prompt should end with whitespace.
  232. timeout: A timeout after which to raise a TimeoutError.
  233. Cannot be set if hide is True.
  234. hide: If true, does not echo the characters typed by the user.
  235. This is useful for passwords.
  236. Returns:
  237. The text typed by the user before pressing the 'return' key.
  238. Raises:
  239. TimeoutError: If a timeout was specified and expired.
  240. NotATerminalError: If the output device is not capable, like if stderr
  241. is redirected to a file, stdin is a pipe or closed, TERM=dumb is
  242. set, or wandb is configured in 'silent' mode.
  243. KeyboardInterrupt: If the user pressed Ctrl+C during the prompt.
  244. """
  245. prefixed_prompt = f"{LOG_STRING}: {prompt}"
  246. return _terminput(prefixed_prompt, timeout=timeout, hide=hide)
  247. def confirm(prompt: str) -> bool:
  248. """Prompt the user with a yes/no question.
  249. Args:
  250. prompt: A prompt ending with a question mark (not whitespace),
  251. like "Are you sure?".
  252. Returns:
  253. The user's choice.
  254. """
  255. prompt = f"{prompt} [y/n] "
  256. while True:
  257. answer = terminput(prompt).strip().lower()
  258. if answer in ("n", "no"):
  259. return False
  260. if answer in ("y", "yes"):
  261. return True
  262. def _terminput(
  263. prefixed_prompt: str,
  264. *,
  265. timeout: float | None = None,
  266. hide: bool = False,
  267. ) -> str:
  268. """Implements terminput() and can be patched by tests."""
  269. if not can_use_terminput():
  270. raise NotATerminalError
  271. if hide and timeout is not None:
  272. # Only click.prompt() can hide, and only timed_input can time out.
  273. raise NotImplementedError
  274. if timeout is not None:
  275. # Lazy import to avoid circular imports.
  276. from wandb.sdk.lib.timed_input import timed_input
  277. try:
  278. return timed_input(
  279. prefixed_prompt,
  280. timeout=timeout,
  281. err=True,
  282. jupyter=_in_jupyter(),
  283. )
  284. except KeyboardInterrupt:
  285. sys.stderr.write("\n")
  286. raise
  287. try:
  288. return click.prompt(
  289. prefixed_prompt,
  290. prompt_suffix="",
  291. hide_input=hide,
  292. err=True,
  293. )
  294. except click.Abort:
  295. sys.stderr.write("\n")
  296. raise KeyboardInterrupt from None
  297. class DynamicBlock:
  298. """A handle to a changeable text area in the terminal."""
  299. def __init__(self) -> None:
  300. self._lines_to_print: list[str] = []
  301. self._num_lines_printed = 0
  302. def set_text(self, text: str, prefix: bool = True) -> None:
  303. r"""Replace the text in this block.
  304. Args:
  305. text: The text to put in the block, with lines separated
  306. by \n characters. The text should not end in \n unless
  307. a blank line at the end of the block is desired.
  308. prefix: Whether to include the "wandb:" prefix.
  309. """
  310. with _dynamic_text_lock:
  311. self._lines_to_print = text.splitlines()
  312. if prefix:
  313. self._lines_to_print = [
  314. f"{LOG_STRING}: {line}" for line in self._lines_to_print
  315. ]
  316. _l_rerender_dynamic_blocks()
  317. def _l_clear(self) -> None:
  318. """Send terminal commands to clear all previously printed lines.
  319. The lock must be held, and the cursor must be on the line after this
  320. block of text.
  321. """
  322. # NOTE: We rely on the fact that click.echo() uses colorama which
  323. # emulates these ANSI sequences on older Windows versions.
  324. #
  325. # \r move cursor to start of line
  326. # \x1b[Am move cursor up
  327. # \x1b[2K delete line (sometimes moves cursor)
  328. # \r move cursor to start of line
  329. move_up_and_delete_line = "\r\x1b[Am\x1b[2K\r"
  330. click.echo(
  331. move_up_and_delete_line * self._num_lines_printed,
  332. file=sys.stderr,
  333. nl=False,
  334. )
  335. self._num_lines_printed = 0
  336. def _l_print(self) -> None:
  337. """Print out this block of text.
  338. The lock must be held.
  339. """
  340. if self._lines_to_print:
  341. # Trim lines before printing. This is crucial because the \x1b[Am
  342. # (cursor up) sequence used when clearing the text moves up by one
  343. # visual line, and the terminal may be wrapping long lines onto
  344. # multiple visual lines.
  345. #
  346. # There is no ANSI escape sequence that moves the cursor up by one
  347. # "physical" line instead. Note that the user may resize their
  348. # terminal.
  349. term_width = _shutil_get_terminal_width()
  350. click.echo(
  351. "\n".join(
  352. _ansi_shorten(line, term_width) #
  353. for line in self._lines_to_print
  354. ),
  355. file=sys.stderr,
  356. )
  357. self._num_lines_printed += len(self._lines_to_print)
  358. def _shutil_get_terminal_width() -> int:
  359. """Returns the width of the terminal.
  360. Defined here for patching in tests.
  361. """
  362. columns, _ = shutil.get_terminal_size()
  363. return columns
  364. _ANSI_RE = re.compile("\x1b\\[(K|.*?m)")
  365. def _ansi_shorten(text: str, width: int) -> str:
  366. """Shorten text potentially containing ANSI sequences to fit a width."""
  367. first_ansi = _ANSI_RE.search(text)
  368. if not first_ansi:
  369. return _raw_shorten(text, width)
  370. if first_ansi.start() > width - 3:
  371. return _raw_shorten(text[: first_ansi.start()], width)
  372. return text[: first_ansi.end()] + _ansi_shorten(
  373. text[first_ansi.end() :],
  374. # Key part: the ANSI sequence doesn't reduce the remaining width.
  375. width - first_ansi.start(),
  376. )
  377. def _raw_shorten(text: str, width: int) -> str:
  378. """Shorten text to fit a width, replacing the end with "...".
  379. Unlike textwrap.shorten(), this does not drop whitespace or do anything
  380. smart.
  381. """
  382. if len(text) <= width:
  383. return text
  384. return text[: width - 3] + "..."
  385. def _log(
  386. string: str = "",
  387. newline: bool = True,
  388. repeat: bool = True,
  389. prefix: bool = True,
  390. silent: bool = False,
  391. level: int = logging.INFO,
  392. ) -> None:
  393. with _dynamic_text_lock, _l_above_dynamic_text():
  394. if not repeat:
  395. if string in _printed_messages:
  396. return
  397. if len(_printed_messages) < 1000:
  398. _printed_messages.add(string)
  399. if prefix:
  400. string = "\n".join([f"{LOG_STRING}: {s}" for s in string.split("\n")])
  401. silent = silent or _silent
  402. if not silent:
  403. click.echo(string, file=sys.stderr, nl=newline)
  404. elif not _logger:
  405. pass # No fallback logger, so nothing to do.
  406. elif level == logging.ERROR:
  407. _logger.error(click.unstyle(string))
  408. elif level == logging.WARNING:
  409. _logger.warning(click.unstyle(string))
  410. else:
  411. _logger.info(click.unstyle(string))
  412. def _l_rerender_dynamic_blocks() -> None:
  413. """Clear and re-print all dynamic text.
  414. The lock must be held. The cursor must be positioned at the start of
  415. the first line after the dynamic text area.
  416. """
  417. with _l_above_dynamic_text():
  418. # We just want the side-effect of rerendering the dynamic text.
  419. pass
  420. @contextlib.contextmanager
  421. def _l_above_dynamic_text():
  422. """A context manager for inserting static text above any dynamic text.
  423. The lock must be held. The cursor must be positioned at the start of the
  424. first line after the dynamic text area.
  425. The dynamic text is re-rendered.
  426. """
  427. _l_clear_dynamic_blocks()
  428. try:
  429. yield
  430. finally:
  431. _l_print_dynamic_blocks()
  432. def _l_clear_dynamic_blocks() -> None:
  433. """Delete all dynamic text.
  434. The lock must be held, and the cursor must be positioned at the start
  435. of the first line after the dynamic text area. After this, the cursor
  436. is positioned at the start of the first line after all static text.
  437. """
  438. for block in reversed(_dynamic_blocks):
  439. block._l_clear()
  440. def _l_print_dynamic_blocks() -> None:
  441. """Output all dynamic text.
  442. The lock must be held. After this, the cursor is positioned at the start
  443. of the first line after the dynamic text area.
  444. """
  445. for block in _dynamic_blocks:
  446. block._l_print()