attrs.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from __future__ import annotations
  2. from collections.abc import Mapping
  3. from typing import Any
  4. import wandb
  5. from ..sdk.lib import ipython
  6. class Attrs:
  7. def __init__(self, attrs: Mapping[str, Any]):
  8. self._attrs = dict(attrs)
  9. def snake_to_camel(self, string):
  10. camel = "".join([i.title() for i in string.split("_")])
  11. return camel[0].lower() + camel[1:]
  12. def display(self, height=420, hidden=False) -> bool:
  13. """Display this object in jupyter."""
  14. if wandb.run and wandb.run._settings.silent:
  15. return False
  16. if not ipython.in_jupyter():
  17. return False
  18. html = self.to_html(height, hidden)
  19. if html is None:
  20. wandb.termwarn("This object does not support `.display()`")
  21. return False
  22. try:
  23. from IPython import display
  24. except ImportError:
  25. wandb.termwarn(".display() only works in jupyter environments")
  26. return False
  27. display.display(display.HTML(html))
  28. return True
  29. def to_html(self, *args, **kwargs):
  30. return None
  31. def __getattr__(self, name):
  32. key = self.snake_to_camel(name)
  33. if key == "user":
  34. raise AttributeError
  35. if key in self._attrs:
  36. return self._attrs[key]
  37. elif name in self._attrs:
  38. return self._attrs[name]
  39. else:
  40. raise AttributeError(f"{repr(self)!r} object has no attribute {name!r}")