diff --git a/.gitattributes b/.gitattributes index 9d4ae82a2ccd8507e112ae941f498d544ba53a87..513d3a08b59888605d11645fb26940d75443a97b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -148,3 +148,4 @@ parrot/lib/python3.10/site-packages/aiohttp/_http_writer.cpython-310-x86_64-linu parrot/lib/libquadmath.so filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/pyarrow/_dataset_parquet.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/ensurepip/_bundled/setuptools-65.5.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text +parrot/lib/python3.10/site-packages/cv2/qt/fonts/DejaVuSansCondensed.ttf filter=lfs diff=lfs merge=lfs -text diff --git a/parrot/lib/python3.10/site-packages/cv2/qt/fonts/DejaVuSansCondensed.ttf b/parrot/lib/python3.10/site-packages/cv2/qt/fonts/DejaVuSansCondensed.ttf new file mode 100644 index 0000000000000000000000000000000000000000..0a5db4d95da618635b71569c61ab434c447eeb46 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/cv2/qt/fonts/DejaVuSansCondensed.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69f1355c9eef0a3d11a6c06f3cbf1d46eabfdadcc993589a3be93a44ed8678b4 +size 643852 diff --git a/parrot/lib/python3.10/site-packages/tqdm/__main__.py b/parrot/lib/python3.10/site-packages/tqdm/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e28416e104515e90fca4b69cc60d0c61fd15d61 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +main() diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..082bbed1426c14592743722274079b98fb9076b3 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/__main__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4241cd496d3a66389a0b139a023707d90efa7aa3 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/__main__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_dist_ver.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_dist_ver.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6ca33aa473d3ef662a17882019e5dbedc447770 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_dist_ver.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_main.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_main.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f735cb04687b3cbd755fea9f0a50b210f0e70aa0 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_main.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_monitor.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_monitor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12c59746f92c1362cd61567c08e2a3d4a25c441d Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_monitor.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..972d7f5e48189c28c8c7cbffe876a2308b3d140b Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm_gui.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm_gui.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7e7158e29cf4a5e68e640dc84c6e97b7d2b28f4 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm_gui.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm_notebook.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm_notebook.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00d7837d4efe3e9c696929db6763ddbdaede3369 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm_notebook.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8c0c933ef9f9691b4ee8243d2506c18f699dc05 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/asyncio.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/asyncio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edee7dd6f1f0cf04b3600fb2cefc1b76bd15990e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/asyncio.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/auto.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/auto.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab7f22c9cdf1717c5193b86064927a05f9e30568 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/auto.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/autonotebook.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/autonotebook.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ae8626306f8fc4924ada87f66d3e090b3ed23c3 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/autonotebook.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/cli.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcd85dba4997fb268531bba120d282eb34ff422e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/cli.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/gui.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/gui.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f84d895db882a4f07b98e123fdcb855f0f3a44b Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/gui.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/keras.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/keras.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b562cad244c575e25569f3b63c592aa46c573347 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/keras.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/notebook.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/notebook.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21fa99a5119ebebd202de6511cdadefda40c6831 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/notebook.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/rich.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/rich.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8b0282e067abba4b85713231ee13cc1e07eb149 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/rich.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/std.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/std.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e4f8188bb4db4cece77edb792a632dfb467506e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/std.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/tk.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/tk.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52667791eda0acf3c140ffbb654cd8c683a7647f Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/tk.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/utils.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e347fdd812bfdbed81eb816a340c226eb094e9e1 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/utils.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/__pycache__/version.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..507b8d50e6f5f461888b72b350760d21989c1395 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/__pycache__/version.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/_dist_ver.py b/parrot/lib/python3.10/site-packages/tqdm/_dist_ver.py new file mode 100644 index 0000000000000000000000000000000000000000..1714d0db714d07094c3259281c1a63aec8bdf726 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/_dist_ver.py @@ -0,0 +1 @@ +__version__ = '4.66.5' diff --git a/parrot/lib/python3.10/site-packages/tqdm/_tqdm.py b/parrot/lib/python3.10/site-packages/tqdm/_tqdm.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc4962774a4651db7a739a3f143633b6215a9bd --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/_tqdm.py @@ -0,0 +1,9 @@ +from warnings import warn + +from .std import * # NOQA +from .std import __all__ # NOQA +from .std import TqdmDeprecationWarning + +warn("This function will be removed in tqdm==5.0.0\n" + "Please use `tqdm.std.*` instead of `tqdm._tqdm.*`", + TqdmDeprecationWarning, stacklevel=2) diff --git a/parrot/lib/python3.10/site-packages/tqdm/_tqdm_gui.py b/parrot/lib/python3.10/site-packages/tqdm/_tqdm_gui.py new file mode 100644 index 0000000000000000000000000000000000000000..f32aa894f54b3a5b47a0fbf4263c2fd20df56c9d --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/_tqdm_gui.py @@ -0,0 +1,9 @@ +from warnings import warn + +from .gui import * # NOQA +from .gui import __all__ # NOQA +from .std import TqdmDeprecationWarning + +warn("This function will be removed in tqdm==5.0.0\n" + "Please use `tqdm.gui.*` instead of `tqdm._tqdm_gui.*`", + TqdmDeprecationWarning, stacklevel=2) diff --git a/parrot/lib/python3.10/site-packages/tqdm/_tqdm_pandas.py b/parrot/lib/python3.10/site-packages/tqdm/_tqdm_pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..c4fe6efdc603579e7f8acfa27ac10dccdf3e94ce --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/_tqdm_pandas.py @@ -0,0 +1,24 @@ +import sys + +__author__ = "github.com/casperdcl" +__all__ = ['tqdm_pandas'] + + +def tqdm_pandas(tclass, **tqdm_kwargs): + """ + Registers the given `tqdm` instance with + `pandas.core.groupby.DataFrameGroupBy.progress_apply`. + """ + from tqdm import TqdmDeprecationWarning + + if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith( + 'tqdm_')): # delayed adapter case + TqdmDeprecationWarning( + "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.", + fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write)) + tclass.pandas(**tqdm_kwargs) + else: + TqdmDeprecationWarning( + "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.", + fp_write=getattr(tclass.fp, 'write', sys.stderr.write)) + type(tclass).pandas(deprecated_t=tclass) diff --git a/parrot/lib/python3.10/site-packages/tqdm/asyncio.py b/parrot/lib/python3.10/site-packages/tqdm/asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..2d00a0a2e755f36068d079ccc12ca84d86ff42be --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/asyncio.py @@ -0,0 +1,93 @@ +""" +Asynchronous progressbar decorator for iterators. +Includes a default `range` iterator printing to `stderr`. + +Usage: +>>> from tqdm.asyncio import trange, tqdm +>>> async for i in trange(10): +... ... +""" +import asyncio +from sys import version_info + +from .std import tqdm as std_tqdm + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['tqdm_asyncio', 'tarange', 'tqdm', 'trange'] + + +class tqdm_asyncio(std_tqdm): + """ + Asynchronous-friendly version of tqdm. + """ + def __init__(self, iterable=None, *args, **kwargs): + super().__init__(iterable, *args, **kwargs) + self.iterable_awaitable = False + if iterable is not None: + if hasattr(iterable, "__anext__"): + self.iterable_next = iterable.__anext__ + self.iterable_awaitable = True + elif hasattr(iterable, "__next__"): + self.iterable_next = iterable.__next__ + else: + self.iterable_iterator = iter(iterable) + self.iterable_next = self.iterable_iterator.__next__ + + def __aiter__(self): + return self + + async def __anext__(self): + try: + if self.iterable_awaitable: + res = await self.iterable_next() + else: + res = self.iterable_next() + self.update() + return res + except StopIteration: + self.close() + raise StopAsyncIteration + except BaseException: + self.close() + raise + + def send(self, *args, **kwargs): + return self.iterable.send(*args, **kwargs) + + @classmethod + def as_completed(cls, fs, *, loop=None, timeout=None, total=None, **tqdm_kwargs): + """ + Wrapper for `asyncio.as_completed`. + """ + if total is None: + total = len(fs) + kwargs = {} + if version_info[:2] < (3, 10): + kwargs['loop'] = loop + yield from cls(asyncio.as_completed(fs, timeout=timeout, **kwargs), + total=total, **tqdm_kwargs) + + @classmethod + async def gather(cls, *fs, loop=None, timeout=None, total=None, **tqdm_kwargs): + """ + Wrapper for `asyncio.gather`. + """ + async def wrap_awaitable(i, f): + return i, await f + + ifs = [wrap_awaitable(i, f) for i, f in enumerate(fs)] + res = [await f for f in cls.as_completed(ifs, loop=loop, timeout=timeout, + total=total, **tqdm_kwargs)] + return [i for _, i in sorted(res)] + + +def tarange(*args, **kwargs): + """ + A shortcut for `tqdm.asyncio.tqdm(range(*args), **kwargs)`. + """ + return tqdm_asyncio(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_asyncio +trange = tarange diff --git a/parrot/lib/python3.10/site-packages/tqdm/auto.py b/parrot/lib/python3.10/site-packages/tqdm/auto.py new file mode 100644 index 0000000000000000000000000000000000000000..206c4409d5269594bdbab3a092ef6e09e7c01947 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/auto.py @@ -0,0 +1,40 @@ +""" +Enables multiple commonly used features. + +Method resolution order: + +- `tqdm.autonotebook` without import warnings +- `tqdm.asyncio` +- `tqdm.std` base class + +Usage: +>>> from tqdm.auto import trange, tqdm +>>> for i in trange(10): +... ... +""" +import warnings + +from .std import TqdmExperimentalWarning + +with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=TqdmExperimentalWarning) + from .autonotebook import tqdm as notebook_tqdm + +from .asyncio import tqdm as asyncio_tqdm +from .std import tqdm as std_tqdm + +if notebook_tqdm != std_tqdm: + class tqdm(notebook_tqdm, asyncio_tqdm): # pylint: disable=inconsistent-mro + pass +else: + tqdm = asyncio_tqdm + + +def trange(*args, **kwargs): + """ + A shortcut for `tqdm.auto.tqdm(range(*args), **kwargs)`. + """ + return tqdm(range(*args), **kwargs) + + +__all__ = ["tqdm", "trange"] diff --git a/parrot/lib/python3.10/site-packages/tqdm/autonotebook.py b/parrot/lib/python3.10/site-packages/tqdm/autonotebook.py new file mode 100644 index 0000000000000000000000000000000000000000..a09f2ec4b8c95f12b8c7b7774f84d5ec55826334 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/autonotebook.py @@ -0,0 +1,29 @@ +""" +Automatically choose between `tqdm.notebook` and `tqdm.std`. + +Usage: +>>> from tqdm.autonotebook import trange, tqdm +>>> for i in trange(10): +... ... +""" +import sys +from warnings import warn + +try: + get_ipython = sys.modules['IPython'].get_ipython + if 'IPKernelApp' not in get_ipython().config: # pragma: no cover + raise ImportError("console") + from .notebook import WARN_NOIPYW, IProgress + if IProgress is None: + from .std import TqdmWarning + warn(WARN_NOIPYW, TqdmWarning, stacklevel=2) + raise ImportError('ipywidgets') +except Exception: + from .std import tqdm, trange +else: # pragma: no cover + from .notebook import tqdm, trange + from .std import TqdmExperimentalWarning + warn("Using `tqdm.autonotebook.tqdm` in notebook mode." + " Use `tqdm.tqdm` instead to force console mode" + " (e.g. in jupyter console)", TqdmExperimentalWarning, stacklevel=2) +__all__ = ["tqdm", "trange"] diff --git a/parrot/lib/python3.10/site-packages/tqdm/cli.py b/parrot/lib/python3.10/site-packages/tqdm/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..d681b1646a06074dcacf63246838634fec0ded82 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/cli.py @@ -0,0 +1,325 @@ +""" +Module version for monitoring CLI pipes (`... | python -m tqdm | ...`). +""" +import logging +import re +import sys +from ast import literal_eval as numeric +from textwrap import indent + +from .std import TqdmKeyError, TqdmTypeError, tqdm +from .version import __version__ + +__all__ = ["main"] +log = logging.getLogger(__name__) + + +def cast(val, typ): + log.debug((val, typ)) + if " or " in typ: + for t in typ.split(" or "): + try: + return cast(val, t) + except TqdmTypeError: + pass + raise TqdmTypeError(f"{val} : {typ}") + + # sys.stderr.write('\ndebug | `val:type`: `' + val + ':' + typ + '`.\n') + if typ == 'bool': + if (val == 'True') or (val == ''): + return True + if val == 'False': + return False + raise TqdmTypeError(val + ' : ' + typ) + if typ == 'chr': + if len(val) == 1: + return val.encode() + if re.match(r"^\\\w+$", val): + return eval(f'"{val}"').encode() + raise TqdmTypeError(f"{val} : {typ}") + if typ == 'str': + return val + if typ == 'int': + try: + return int(val) + except ValueError as exc: + raise TqdmTypeError(f"{val} : {typ}") from exc + if typ == 'float': + try: + return float(val) + except ValueError as exc: + raise TqdmTypeError(f"{val} : {typ}") from exc + raise TqdmTypeError(f"{val} : {typ}") + + +def posix_pipe(fin, fout, delim=b'\\n', buf_size=256, + callback=lambda float: None, callback_len=True): + """ + Params + ------ + fin : binary file with `read(buf_size : int)` method + fout : binary file with `write` (and optionally `flush`) methods. + callback : function(float), e.g.: `tqdm.update` + callback_len : If (default: True) do `callback(len(buffer))`. + Otherwise, do `callback(data) for data in buffer.split(delim)`. + """ + fp_write = fout.write + + if not delim: + while True: + tmp = fin.read(buf_size) + + # flush at EOF + if not tmp: + getattr(fout, 'flush', lambda: None)() + return + + fp_write(tmp) + callback(len(tmp)) + # return + + buf = b'' + len_delim = len(delim) + # n = 0 + while True: + tmp = fin.read(buf_size) + + # flush at EOF + if not tmp: + if buf: + fp_write(buf) + if callback_len: + # n += 1 + buf.count(delim) + callback(1 + buf.count(delim)) + else: + for i in buf.split(delim): + callback(i) + getattr(fout, 'flush', lambda: None)() + return # n + + while True: + i = tmp.find(delim) + if i < 0: + buf += tmp + break + fp_write(buf + tmp[:i + len(delim)]) + # n += 1 + callback(1 if callback_len else (buf + tmp[:i])) + buf = b'' + tmp = tmp[i + len_delim:] + + +# ((opt, type), ... ) +RE_OPTS = re.compile(r'\n {4}(\S+)\s{2,}:\s*([^,]+)') +# better split method assuming no positional args +RE_SHLEX = re.compile(r'\s*(? : \2', d) + split = RE_OPTS.split(d) + opt_types_desc = zip(split[1::3], split[2::3], split[3::3]) + d = ''.join(('\n --{0} : {2}{3}' if otd[1] == 'bool' else + '\n --{0}=<{1}> : {2}{3}').format( + otd[0].replace('_', '-'), otd[0], *otd[1:]) + for otd in opt_types_desc if otd[0] not in UNSUPPORTED_OPTS) + + help_short = "Usage:\n tqdm [--help | options]\n" + d = help_short + """ +Options: + -h, --help Print this help and exit. + -v, --version Print version and exit. +""" + d.strip('\n') + '\n' + + # opts = docopt(d, version=__version__) + if any(v in argv for v in ('-v', '--version')): + sys.stdout.write(__version__ + '\n') + sys.exit(0) + elif any(v in argv for v in ('-h', '--help')): + sys.stdout.write(d + '\n') + sys.exit(0) + elif argv and argv[0][:2] != '--': + sys.stderr.write(f"Error:Unknown argument:{argv[0]}\n{help_short}") + + argv = RE_SHLEX.split(' '.join(["tqdm"] + argv)) + opts = dict(zip(argv[1::3], argv[3::3])) + + log.debug(opts) + opts.pop('log', True) + + tqdm_args = {'file': fp} + try: + for (o, v) in opts.items(): + o = o.replace('-', '_') + try: + tqdm_args[o] = cast(v, opt_types[o]) + except KeyError as e: + raise TqdmKeyError(str(e)) + log.debug('args:' + str(tqdm_args)) + + delim_per_char = tqdm_args.pop('bytes', False) + update = tqdm_args.pop('update', False) + update_to = tqdm_args.pop('update_to', False) + if sum((delim_per_char, update, update_to)) > 1: + raise TqdmKeyError("Can only have one of --bytes --update --update_to") + except Exception: + fp.write("\nError:\n" + help_short) + stdin, stdout_write = sys.stdin, sys.stdout.write + for i in stdin: + stdout_write(i) + raise + else: + buf_size = tqdm_args.pop('buf_size', 256) + delim = tqdm_args.pop('delim', b'\\n') + tee = tqdm_args.pop('tee', False) + manpath = tqdm_args.pop('manpath', None) + comppath = tqdm_args.pop('comppath', None) + if tqdm_args.pop('null', False): + class stdout(object): + @staticmethod + def write(_): + pass + else: + stdout = sys.stdout + stdout = getattr(stdout, 'buffer', stdout) + stdin = getattr(sys.stdin, 'buffer', sys.stdin) + if manpath or comppath: + from importlib import resources + from os import path + from shutil import copyfile + + def cp(name, dst): + """copy resource `name` to `dst`""" + if hasattr(resources, 'files'): + copyfile(str(resources.files('tqdm') / name), dst) + else: # py<3.9 + with resources.path('tqdm', name) as src: + copyfile(str(src), dst) + log.info("written:%s", dst) + if manpath is not None: + cp('tqdm.1', path.join(manpath, 'tqdm.1')) + if comppath is not None: + cp('completion.sh', path.join(comppath, 'tqdm_completion.sh')) + sys.exit(0) + if tee: + stdout_write = stdout.write + fp_write = getattr(fp, 'buffer', fp).write + + class stdout(object): # pylint: disable=function-redefined + @staticmethod + def write(x): + with tqdm.external_write_mode(file=fp): + fp_write(x) + stdout_write(x) + if delim_per_char: + tqdm_args.setdefault('unit', 'B') + tqdm_args.setdefault('unit_scale', True) + tqdm_args.setdefault('unit_divisor', 1024) + log.debug(tqdm_args) + with tqdm(**tqdm_args) as t: + posix_pipe(stdin, stdout, '', buf_size, t.update) + elif delim == b'\\n': + log.debug(tqdm_args) + write = stdout.write + if update or update_to: + with tqdm(**tqdm_args) as t: + if update: + def callback(i): + t.update(numeric(i.decode())) + else: # update_to + def callback(i): + t.update(numeric(i.decode()) - t.n) + for i in stdin: + write(i) + callback(i) + else: + for i in tqdm(stdin, **tqdm_args): + write(i) + else: + log.debug(tqdm_args) + with tqdm(**tqdm_args) as t: + callback_len = False + if update: + def callback(i): + t.update(numeric(i.decode())) + elif update_to: + def callback(i): + t.update(numeric(i.decode()) - t.n) + else: + callback = t.update + callback_len = True + posix_pipe(stdin, stdout, delim, buf_size, callback, callback_len) diff --git a/parrot/lib/python3.10/site-packages/tqdm/completion.sh b/parrot/lib/python3.10/site-packages/tqdm/completion.sh new file mode 100644 index 0000000000000000000000000000000000000000..9f61c7f14bb8c1f6099b9eb75dce28ece6a7ae96 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/completion.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +_tqdm(){ + local cur prv + cur="${COMP_WORDS[COMP_CWORD]}" + prv="${COMP_WORDS[COMP_CWORD - 1]}" + + case ${prv} in + --bar_format|--buf_size|--colour|--comppath|--delay|--delim|--desc|--initial|--lock_args|--manpath|--maxinterval|--mininterval|--miniters|--ncols|--nrows|--position|--postfix|--smoothing|--total|--unit|--unit_divisor) + # await user input + ;; + "--log") + COMPREPLY=($(compgen -W 'CRITICAL FATAL ERROR WARN WARNING INFO DEBUG NOTSET' -- ${cur})) + ;; + *) + COMPREPLY=($(compgen -W '--ascii --bar_format --buf_size --bytes --colour --comppath --delay --delim --desc --disable --dynamic_ncols --help --initial --leave --lock_args --log --manpath --maxinterval --mininterval --miniters --ncols --nrows --null --position --postfix --smoothing --tee --total --unit --unit_divisor --unit_scale --update --update_to --version --write_bytes -h -v' -- ${cur})) + ;; + esac +} +complete -F _tqdm tqdm diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8c079c262a86406beb2d6e0503e5bedb8b1ca91 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/bells.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/bells.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88710271a8b14edc4ac9358a85a6d27393dd18e4 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/bells.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/concurrent.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/concurrent.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91381849fde41e12edbe5cec8cfb933935b6219f Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/concurrent.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/discord.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/discord.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c112c2a4b988105f3636a8eb87a7bd916bd889f Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/discord.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/logging.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/logging.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..109c390daceb922a9a31fee51d8ad9d3010c1165 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/logging.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/slack.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/slack.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50682b241a4fd613056a3f2eb979ea70cd5e52f1 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/slack.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/telegram.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/telegram.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d949be7a7898e4ef2377df434041c32b645ac8e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/telegram.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/utils_worker.cpython-310.pyc b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/utils_worker.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7a972ca8f140c6fa1b492fe1d76ac5ce10d67c2 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/tqdm/contrib/__pycache__/utils_worker.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/itertools.py b/parrot/lib/python3.10/site-packages/tqdm/contrib/itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..e67651a41a6b8760d9b928ea48239e4611d70315 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/contrib/itertools.py @@ -0,0 +1,35 @@ +""" +Thin wrappers around `itertools`. +""" +import itertools + +from ..auto import tqdm as tqdm_auto + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['product'] + + +def product(*iterables, **tqdm_kwargs): + """ + Equivalent of `itertools.product`. + + Parameters + ---------- + tqdm_class : [default: tqdm.auto.tqdm]. + """ + kwargs = tqdm_kwargs.copy() + tqdm_class = kwargs.pop("tqdm_class", tqdm_auto) + try: + lens = list(map(len, iterables)) + except TypeError: + total = None + else: + total = 1 + for i in lens: + total *= i + kwargs.setdefault("total", total) + with tqdm_class(**kwargs) as t: + it = itertools.product(*iterables) + for i in it: + yield i + t.update() diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/logging.py b/parrot/lib/python3.10/site-packages/tqdm/contrib/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..e06febe37b5d70b5296804c55dca48a397c250e3 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/contrib/logging.py @@ -0,0 +1,126 @@ +""" +Helper functionality for interoperability with stdlib `logging`. +""" +import logging +import sys +from contextlib import contextmanager + +try: + from typing import Iterator, List, Optional, Type # noqa: F401 +except ImportError: + pass + +from ..std import tqdm as std_tqdm + + +class _TqdmLoggingHandler(logging.StreamHandler): + def __init__( + self, + tqdm_class=std_tqdm # type: Type[std_tqdm] + ): + super().__init__() + self.tqdm_class = tqdm_class + + def emit(self, record): + try: + msg = self.format(record) + self.tqdm_class.write(msg, file=self.stream) + self.flush() + except (KeyboardInterrupt, SystemExit): + raise + except: # noqa pylint: disable=bare-except + self.handleError(record) + + +def _is_console_logging_handler(handler): + return (isinstance(handler, logging.StreamHandler) + and handler.stream in {sys.stdout, sys.stderr}) + + +def _get_first_found_console_logging_handler(handlers): + for handler in handlers: + if _is_console_logging_handler(handler): + return handler + + +@contextmanager +def logging_redirect_tqdm( + loggers=None, # type: Optional[List[logging.Logger]], + tqdm_class=std_tqdm # type: Type[std_tqdm] +): + # type: (...) -> Iterator[None] + """ + Context manager redirecting console logging to `tqdm.write()`, leaving + other logging handlers (e.g. log files) unaffected. + + Parameters + ---------- + loggers : list, optional + Which handlers to redirect (default: [logging.root]). + tqdm_class : optional + + Example + ------- + ```python + import logging + from tqdm import trange + from tqdm.contrib.logging import logging_redirect_tqdm + + LOG = logging.getLogger(__name__) + + if __name__ == '__main__': + logging.basicConfig(level=logging.INFO) + with logging_redirect_tqdm(): + for i in trange(9): + if i == 4: + LOG.info("console logging redirected to `tqdm.write()`") + # logging restored + ``` + """ + if loggers is None: + loggers = [logging.root] + original_handlers_list = [logger.handlers for logger in loggers] + try: + for logger in loggers: + tqdm_handler = _TqdmLoggingHandler(tqdm_class) + orig_handler = _get_first_found_console_logging_handler(logger.handlers) + if orig_handler is not None: + tqdm_handler.setFormatter(orig_handler.formatter) + tqdm_handler.stream = orig_handler.stream + logger.handlers = [ + handler for handler in logger.handlers + if not _is_console_logging_handler(handler)] + [tqdm_handler] + yield + finally: + for logger, original_handlers in zip(loggers, original_handlers_list): + logger.handlers = original_handlers + + +@contextmanager +def tqdm_logging_redirect( + *args, + # loggers=None, # type: Optional[List[logging.Logger]] + # tqdm=None, # type: Optional[Type[tqdm.tqdm]] + **kwargs +): + # type: (...) -> Iterator[None] + """ + Convenience shortcut for: + ```python + with tqdm_class(*args, **tqdm_kwargs) as pbar: + with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class): + yield pbar + ``` + + Parameters + ---------- + tqdm_class : optional, (default: tqdm.std.tqdm). + loggers : optional, list. + **tqdm_kwargs : passed to `tqdm_class`. + """ + tqdm_kwargs = kwargs.copy() + loggers = tqdm_kwargs.pop('loggers', None) + tqdm_class = tqdm_kwargs.pop('tqdm_class', std_tqdm) + with tqdm_class(*args, **tqdm_kwargs) as pbar: + with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class): + yield pbar diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/telegram.py b/parrot/lib/python3.10/site-packages/tqdm/contrib/telegram.py new file mode 100644 index 0000000000000000000000000000000000000000..019151800bc0c4c4fc543314b6398aa602b0692a --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/contrib/telegram.py @@ -0,0 +1,153 @@ +""" +Sends updates to a Telegram bot. + +Usage: +>>> from tqdm.contrib.telegram import tqdm, trange +>>> for i in trange(10, token='{token}', chat_id='{chat_id}'): +... ... + +![screenshot](https://tqdm.github.io/img/screenshot-telegram.gif) +""" +from os import getenv +from warnings import warn + +from requests import Session + +from ..auto import tqdm as tqdm_auto +from ..std import TqdmWarning +from .utils_worker import MonoWorker + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange'] + + +class TelegramIO(MonoWorker): + """Non-blocking file-like IO using a Telegram Bot.""" + API = 'https://api.telegram.org/bot' + + def __init__(self, token, chat_id): + """Creates a new message in the given `chat_id`.""" + super().__init__() + self.token = token + self.chat_id = chat_id + self.session = Session() + self.text = self.__class__.__name__ + self.message_id + + @property + def message_id(self): + if hasattr(self, '_message_id'): + return self._message_id + try: + res = self.session.post( + self.API + '%s/sendMessage' % self.token, + data={'text': '`' + self.text + '`', 'chat_id': self.chat_id, + 'parse_mode': 'MarkdownV2'}).json() + except Exception as e: + tqdm_auto.write(str(e)) + else: + if res.get('error_code') == 429: + warn("Creation rate limit: try increasing `mininterval`.", + TqdmWarning, stacklevel=2) + else: + self._message_id = res['result']['message_id'] + return self._message_id + + def write(self, s): + """Replaces internal `message_id`'s text with `s`.""" + if not s: + s = "..." + s = s.replace('\r', '').strip() + if s == self.text: + return # avoid duplicate message Bot error + message_id = self.message_id + if message_id is None: + return + self.text = s + try: + future = self.submit( + self.session.post, self.API + '%s/editMessageText' % self.token, + data={'text': '`' + s + '`', 'chat_id': self.chat_id, + 'message_id': message_id, 'parse_mode': 'MarkdownV2'}) + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + def delete(self): + """Deletes internal `message_id`.""" + try: + future = self.submit( + self.session.post, self.API + '%s/deleteMessage' % self.token, + data={'chat_id': self.chat_id, 'message_id': self.message_id}) + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + +class tqdm_telegram(tqdm_auto): + """ + Standard `tqdm.auto.tqdm` but also sends updates to a Telegram Bot. + May take a few seconds to create (`__init__`). + + - create a bot + - copy its `{token}` + - add the bot to a chat and send it a message such as `/start` + - go to to find out + the `{chat_id}` + - paste the `{token}` & `{chat_id}` below + + >>> from tqdm.contrib.telegram import tqdm, trange + >>> for i in tqdm(iterable, token='{token}', chat_id='{chat_id}'): + ... ... + """ + def __init__(self, *args, **kwargs): + """ + Parameters + ---------- + token : str, required. Telegram token + [default: ${TQDM_TELEGRAM_TOKEN}]. + chat_id : str, required. Telegram chat ID + [default: ${TQDM_TELEGRAM_CHAT_ID}]. + + See `tqdm.auto.tqdm.__init__` for other parameters. + """ + if not kwargs.get('disable'): + kwargs = kwargs.copy() + self.tgio = TelegramIO( + kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')), + kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID'))) + super().__init__(*args, **kwargs) + + def display(self, **kwargs): + super().display(**kwargs) + fmt = self.format_dict + if fmt.get('bar_format', None): + fmt['bar_format'] = fmt['bar_format'].replace( + '', '{bar:10u}').replace('{bar}', '{bar:10u}') + else: + fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}' + self.tgio.write(self.format_meter(**fmt)) + + def clear(self, *args, **kwargs): + super().clear(*args, **kwargs) + if not self.disable: + self.tgio.write("") + + def close(self): + if self.disable: + return + super().close() + if not (self.leave or (self.leave is None and self.pos == 0)): + self.tgio.delete() + + +def ttgrange(*args, **kwargs): + """Shortcut for `tqdm.contrib.telegram.tqdm(range(*args), **kwargs)`.""" + return tqdm_telegram(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_telegram +trange = ttgrange diff --git a/parrot/lib/python3.10/site-packages/tqdm/contrib/utils_worker.py b/parrot/lib/python3.10/site-packages/tqdm/contrib/utils_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..2a03a2a8930001e37938836196e0d15b649b07a8 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/contrib/utils_worker.py @@ -0,0 +1,38 @@ +""" +IO/concurrency helpers for `tqdm.contrib`. +""" +from collections import deque +from concurrent.futures import ThreadPoolExecutor + +from ..auto import tqdm as tqdm_auto + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['MonoWorker'] + + +class MonoWorker(object): + """ + Supports one running task and one waiting task. + The waiting task is the most recent submitted (others are discarded). + """ + def __init__(self): + self.pool = ThreadPoolExecutor(max_workers=1) + self.futures = deque([], 2) + + def submit(self, func, *args, **kwargs): + """`func(*args, **kwargs)` may replace currently waiting task.""" + futures = self.futures + if len(futures) == futures.maxlen: + running = futures.popleft() + if not running.done(): + if len(futures): # clear waiting + waiting = futures.pop() + waiting.cancel() + futures.appendleft(running) # re-insert running + try: + waiting = self.pool.submit(func, *args, **kwargs) + except Exception as e: + tqdm_auto.write(str(e)) + else: + futures.append(waiting) + return waiting diff --git a/parrot/lib/python3.10/site-packages/tqdm/keras.py b/parrot/lib/python3.10/site-packages/tqdm/keras.py new file mode 100644 index 0000000000000000000000000000000000000000..cce9467c51a95388aaa502d1da9a42f3ebf0af24 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/keras.py @@ -0,0 +1,122 @@ +from copy import copy +from functools import partial + +from .auto import tqdm as tqdm_auto + +try: + import keras +except (ImportError, AttributeError) as e: + try: + from tensorflow import keras + except ImportError: + raise e +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['TqdmCallback'] + + +class TqdmCallback(keras.callbacks.Callback): + """Keras callback for epoch and batch progress.""" + @staticmethod + def bar2callback(bar, pop=None, delta=(lambda logs: 1)): + def callback(_, logs=None): + n = delta(logs) + if logs: + if pop: + logs = copy(logs) + [logs.pop(i, 0) for i in pop] + bar.set_postfix(logs, refresh=False) + bar.update(n) + + return callback + + def __init__(self, epochs=None, data_size=None, batch_size=None, verbose=1, + tqdm_class=tqdm_auto, **tqdm_kwargs): + """ + Parameters + ---------- + epochs : int, optional + data_size : int, optional + Number of training pairs. + batch_size : int, optional + Number of training pairs per batch. + verbose : int + 0: epoch, 1: batch (transient), 2: batch. [default: 1]. + Will be set to `0` unless both `data_size` and `batch_size` + are given. + tqdm_class : optional + `tqdm` class to use for bars [default: `tqdm.auto.tqdm`]. + tqdm_kwargs : optional + Any other arguments used for all bars. + """ + if tqdm_kwargs: + tqdm_class = partial(tqdm_class, **tqdm_kwargs) + self.tqdm_class = tqdm_class + self.epoch_bar = tqdm_class(total=epochs, unit='epoch') + self.on_epoch_end = self.bar2callback(self.epoch_bar) + if data_size and batch_size: + self.batches = batches = (data_size + batch_size - 1) // batch_size + else: + self.batches = batches = None + self.verbose = verbose + if verbose == 1: + self.batch_bar = tqdm_class(total=batches, unit='batch', leave=False) + self.on_batch_end = self.bar2callback( + self.batch_bar, pop=['batch', 'size'], + delta=lambda logs: logs.get('size', 1)) + + def on_train_begin(self, *_, **__): + params = self.params.get + auto_total = params('epochs', params('nb_epoch', None)) + if auto_total is not None and auto_total != self.epoch_bar.total: + self.epoch_bar.reset(total=auto_total) + + def on_epoch_begin(self, epoch, *_, **__): + if self.epoch_bar.n < epoch: + ebar = self.epoch_bar + ebar.n = ebar.last_print_n = ebar.initial = epoch + if self.verbose: + params = self.params.get + total = params('samples', params( + 'nb_sample', params('steps', None))) or self.batches + if self.verbose == 2: + if hasattr(self, 'batch_bar'): + self.batch_bar.close() + self.batch_bar = self.tqdm_class( + total=total, unit='batch', leave=True, + unit_scale=1 / (params('batch_size', 1) or 1)) + self.on_batch_end = self.bar2callback( + self.batch_bar, pop=['batch', 'size'], + delta=lambda logs: logs.get('size', 1)) + elif self.verbose == 1: + self.batch_bar.unit_scale = 1 / (params('batch_size', 1) or 1) + self.batch_bar.reset(total=total) + else: + raise KeyError('Unknown verbosity') + + def on_train_end(self, *_, **__): + if hasattr(self, 'batch_bar'): + self.batch_bar.close() + self.epoch_bar.close() + + def display(self): + """Displays in the current cell in Notebooks.""" + container = getattr(self.epoch_bar, 'container', None) + if container is None: + return + from .notebook import display + display(container) + batch_bar = getattr(self, 'batch_bar', None) + if batch_bar is not None: + display(batch_bar.container) + + @staticmethod + def _implements_train_batch_hooks(): + return True + + @staticmethod + def _implements_test_batch_hooks(): + return True + + @staticmethod + def _implements_predict_batch_hooks(): + return True diff --git a/parrot/lib/python3.10/site-packages/tqdm/notebook.py b/parrot/lib/python3.10/site-packages/tqdm/notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..77b91bdd43183998fcb99e92dd4597ff7fc6c3fb --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/notebook.py @@ -0,0 +1,317 @@ +""" +IPython/Jupyter Notebook progressbar decorator for iterators. +Includes a default `range` iterator printing to `stderr`. + +Usage: +>>> from tqdm.notebook import trange, tqdm +>>> for i in trange(10): +... ... +""" +# import compatibility functions and utilities +import re +import sys +from html import escape +from weakref import proxy + +# to inherit from the tqdm class +from .std import tqdm as std_tqdm + +if True: # pragma: no cover + # import IPython/Jupyter base widget and display utilities + IPY = 0 + try: # IPython 4.x + import ipywidgets + IPY = 4 + except ImportError: # IPython 3.x / 2.x + IPY = 32 + import warnings + with warnings.catch_warnings(): + warnings.filterwarnings( + 'ignore', message=".*The `IPython.html` package has been deprecated.*") + try: + import IPython.html.widgets as ipywidgets # NOQA: F401 + except ImportError: + pass + + try: # IPython 4.x / 3.x + if IPY == 32: + from IPython.html.widgets import HTML + from IPython.html.widgets import FloatProgress as IProgress + from IPython.html.widgets import HBox + IPY = 3 + else: + from ipywidgets import HTML + from ipywidgets import FloatProgress as IProgress + from ipywidgets import HBox + except ImportError: + try: # IPython 2.x + from IPython.html.widgets import HTML + from IPython.html.widgets import ContainerWidget as HBox + from IPython.html.widgets import FloatProgressWidget as IProgress + IPY = 2 + except ImportError: + IPY = 0 + IProgress = None + HBox = object + + try: + from IPython.display import display # , clear_output + except ImportError: + pass + +__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} +__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] +WARN_NOIPYW = ("IProgress not found. Please update jupyter and ipywidgets." + " See https://ipywidgets.readthedocs.io/en/stable" + "/user_install.html") + + +class TqdmHBox(HBox): + """`ipywidgets.HBox` with a pretty representation""" + def _json_(self, pretty=None): + pbar = getattr(self, 'pbar', None) + if pbar is None: + return {} + d = pbar.format_dict + if pretty is not None: + d["ascii"] = not pretty + return d + + def __repr__(self, pretty=False): + pbar = getattr(self, 'pbar', None) + if pbar is None: + return super().__repr__() + return pbar.format_meter(**self._json_(pretty)) + + def _repr_pretty_(self, pp, *_, **__): + pp.text(self.__repr__(True)) + + +class tqdm_notebook(std_tqdm): + """ + Experimental IPython/Jupyter Notebook widget using tqdm! + """ + @staticmethod + def status_printer(_, total=None, desc=None, ncols=None): + """ + Manage the printing of an IPython/Jupyter Notebook progress bar widget. + """ + # Fallback to text bar if there's no total + # DEPRECATED: replaced with an 'info' style bar + # if not total: + # return super(tqdm_notebook, tqdm_notebook).status_printer(file) + + # fp = file + + # Prepare IPython progress bar + if IProgress is None: # #187 #451 #558 #872 + raise ImportError(WARN_NOIPYW) + if total: + pbar = IProgress(min=0, max=total) + else: # No total? Show info style bar with no progress tqdm status + pbar = IProgress(min=0, max=1) + pbar.value = 1 + pbar.bar_style = 'info' + if ncols is None: + pbar.layout.width = "20px" + + ltext = HTML() + rtext = HTML() + if desc: + ltext.value = desc + container = TqdmHBox(children=[ltext, pbar, rtext]) + # Prepare layout + if ncols is not None: # use default style of ipywidgets + # ncols could be 100, "100px", "100%" + ncols = str(ncols) # ipywidgets only accepts string + try: + if int(ncols) > 0: # isnumeric and positive + ncols += 'px' + except ValueError: + pass + pbar.layout.flex = '2' + container.layout.width = ncols + container.layout.display = 'inline-flex' + container.layout.flex_flow = 'row wrap' + + return container + + def display(self, msg=None, pos=None, + # additional signals + close=False, bar_style=None, check_delay=True): + # Note: contrary to native tqdm, msg='' does NOT clear bar + # goal is to keep all infos if error happens so user knows + # at which iteration the loop failed. + + # Clear previous output (really necessary?) + # clear_output(wait=1) + + if not msg and not close: + d = self.format_dict + # remove {bar} + d['bar_format'] = (d['bar_format'] or "{l_bar}{r_bar}").replace( + "{bar}", "") + msg = self.format_meter(**d) + + ltext, pbar, rtext = self.container.children + pbar.value = self.n + + if msg: + msg = msg.replace(' ', u'\u2007') # fix html space padding + # html escape special characters (like '&') + if '' in msg: + left, right = map(escape, re.split(r'\|?\|?', msg, maxsplit=1)) + else: + left, right = '', escape(msg) + + # Update description + ltext.value = left + # never clear the bar (signal: msg='') + if right: + rtext.value = right + + # Change bar style + if bar_style: + # Hack-ish way to avoid the danger bar_style being overridden by + # success because the bar gets closed after the error... + if pbar.bar_style != 'danger' or bar_style != 'success': + pbar.bar_style = bar_style + + # Special signal to close the bar + if close and pbar.bar_style != 'danger': # hide only if no error + try: + self.container.close() + except AttributeError: + self.container.visible = False + self.container.layout.visibility = 'hidden' # IPYW>=8 + + if check_delay and self.delay > 0 and not self.displayed: + display(self.container) + self.displayed = True + + @property + def colour(self): + if hasattr(self, 'container'): + return self.container.children[-2].style.bar_color + + @colour.setter + def colour(self, bar_color): + if hasattr(self, 'container'): + self.container.children[-2].style.bar_color = bar_color + + def __init__(self, *args, **kwargs): + """ + Supports the usual `tqdm.tqdm` parameters as well as those listed below. + + Parameters + ---------- + display : Whether to call `display(self.container)` immediately + [default: True]. + """ + kwargs = kwargs.copy() + # Setup default output + file_kwarg = kwargs.get('file', sys.stderr) + if file_kwarg is sys.stderr or file_kwarg is None: + kwargs['file'] = sys.stdout # avoid the red block in IPython + + # Initialize parent class + avoid printing by using gui=True + kwargs['gui'] = True + # convert disable = None to False + kwargs['disable'] = bool(kwargs.get('disable', False)) + colour = kwargs.pop('colour', None) + display_here = kwargs.pop('display', True) + super().__init__(*args, **kwargs) + if self.disable or not kwargs['gui']: + self.disp = lambda *_, **__: None + return + + # Get bar width + self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None) + + # Replace with IPython progress bar display (with correct total) + unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1 + total = self.total * unit_scale if self.total else self.total + self.container = self.status_printer(self.fp, total, self.desc, self.ncols) + self.container.pbar = proxy(self) + self.displayed = False + if display_here and self.delay <= 0: + display(self.container) + self.displayed = True + self.disp = self.display + self.colour = colour + + # Print initial bar state + if not self.disable: + self.display(check_delay=False) + + def __iter__(self): + try: + it = super().__iter__() + for obj in it: + # return super(tqdm...) will not catch exception + yield obj + # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt + except: # NOQA + self.disp(bar_style='danger') + raise + # NB: don't `finally: close()` + # since this could be a shared bar which the user will `reset()` + + def update(self, n=1): + try: + return super().update(n=n) + # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt + except: # NOQA + # cannot catch KeyboardInterrupt when using manual tqdm + # as the interrupt will most likely happen on another statement + self.disp(bar_style='danger') + raise + # NB: don't `finally: close()` + # since this could be a shared bar which the user will `reset()` + + def close(self): + if self.disable: + return + super().close() + # Try to detect if there was an error or KeyboardInterrupt + # in manual mode: if n < total, things probably got wrong + if self.total and self.n < self.total: + self.disp(bar_style='danger', check_delay=False) + else: + if self.leave: + self.disp(bar_style='success', check_delay=False) + else: + self.disp(close=True, check_delay=False) + + def clear(self, *_, **__): + pass + + def reset(self, total=None): + """ + Resets to 0 iterations for repeated use. + + Consider combining with `leave=True`. + + Parameters + ---------- + total : int or float, optional. Total to use for the new bar. + """ + if self.disable: + return super().reset(total=total) + _, pbar, _ = self.container.children + pbar.bar_style = '' + if total is not None: + pbar.max = total + if not self.total and self.ncols is None: # no longer unknown total + pbar.layout.width = None # reset width + return super().reset(total=total) + + +def tnrange(*args, **kwargs): + """Shortcut for `tqdm.notebook.tqdm(range(*args), **kwargs)`.""" + return tqdm_notebook(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_notebook +trange = tnrange diff --git a/parrot/lib/python3.10/site-packages/tqdm/rich.py b/parrot/lib/python3.10/site-packages/tqdm/rich.py new file mode 100644 index 0000000000000000000000000000000000000000..3d392edaf115a93f7c145de52cbe8978dcf1ede8 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/rich.py @@ -0,0 +1,151 @@ +""" +`rich.progress` decorator for iterators. + +Usage: +>>> from tqdm.rich import trange, tqdm +>>> for i in trange(10): +... ... +""" +from warnings import warn + +from rich.progress import ( + BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) + +from .std import TqdmExperimentalWarning +from .std import tqdm as std_tqdm + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange'] + + +class FractionColumn(ProgressColumn): + """Renders completed/total, e.g. '0.5/2.3 G'.""" + def __init__(self, unit_scale=False, unit_divisor=1000): + self.unit_scale = unit_scale + self.unit_divisor = unit_divisor + super().__init__() + + def render(self, task): + """Calculate common unit for completed and total.""" + completed = int(task.completed) + total = int(task.total) + if self.unit_scale: + unit, suffix = filesize.pick_unit_and_suffix( + total, + ["", "K", "M", "G", "T", "P", "E", "Z", "Y"], + self.unit_divisor, + ) + else: + unit, suffix = filesize.pick_unit_and_suffix(total, [""], 1) + precision = 0 if unit == 1 else 1 + return Text( + f"{completed/unit:,.{precision}f}/{total/unit:,.{precision}f} {suffix}", + style="progress.download") + + +class RateColumn(ProgressColumn): + """Renders human readable transfer speed.""" + def __init__(self, unit="", unit_scale=False, unit_divisor=1000): + self.unit = unit + self.unit_scale = unit_scale + self.unit_divisor = unit_divisor + super().__init__() + + def render(self, task): + """Show data transfer speed.""" + speed = task.speed + if speed is None: + return Text(f"? {self.unit}/s", style="progress.data.speed") + if self.unit_scale: + unit, suffix = filesize.pick_unit_and_suffix( + speed, + ["", "K", "M", "G", "T", "P", "E", "Z", "Y"], + self.unit_divisor, + ) + else: + unit, suffix = filesize.pick_unit_and_suffix(speed, [""], 1) + precision = 0 if unit == 1 else 1 + return Text(f"{speed/unit:,.{precision}f} {suffix}{self.unit}/s", + style="progress.data.speed") + + +class tqdm_rich(std_tqdm): # pragma: no cover + """Experimental rich.progress GUI version of tqdm!""" + # TODO: @classmethod: write()? + def __init__(self, *args, **kwargs): + """ + This class accepts the following parameters *in addition* to + the parameters accepted by `tqdm`. + + Parameters + ---------- + progress : tuple, optional + arguments for `rich.progress.Progress()`. + options : dict, optional + keyword arguments for `rich.progress.Progress()`. + """ + kwargs = kwargs.copy() + kwargs['gui'] = True + # convert disable = None to False + kwargs['disable'] = bool(kwargs.get('disable', False)) + progress = kwargs.pop('progress', None) + options = kwargs.pop('options', {}).copy() + super().__init__(*args, **kwargs) + + if self.disable: + return + + warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2) + d = self.format_dict + if progress is None: + progress = ( + "[progress.description]{task.description}" + "[progress.percentage]{task.percentage:>4.0f}%", + BarColumn(bar_width=None), + FractionColumn( + unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']), + "[", TimeElapsedColumn(), "<", TimeRemainingColumn(), + ",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'], + unit_divisor=d['unit_divisor']), "]" + ) + options.setdefault('transient', not self.leave) + self._prog = Progress(*progress, **options) + self._prog.__enter__() + self._task_id = self._prog.add_task(self.desc or "", **d) + + def close(self): + if self.disable: + return + self.display() # print 100%, vis #1306 + super().close() + self._prog.__exit__(None, None, None) + + def clear(self, *_, **__): + pass + + def display(self, *_, **__): + if not hasattr(self, '_prog'): + return + self._prog.update(self._task_id, completed=self.n, description=self.desc) + + def reset(self, total=None): + """ + Resets to 0 iterations for repeated use. + + Parameters + ---------- + total : int or float, optional. Total to use for the new bar. + """ + if hasattr(self, '_prog'): + self._prog.reset(total=total) + super().reset(total=total) + + +def trrange(*args, **kwargs): + """Shortcut for `tqdm.rich.tqdm(range(*args), **kwargs)`.""" + return tqdm_rich(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_rich +trange = trrange diff --git a/parrot/lib/python3.10/site-packages/tqdm/tk.py b/parrot/lib/python3.10/site-packages/tqdm/tk.py new file mode 100644 index 0000000000000000000000000000000000000000..788303c8687e007338ce816bf9afeec8581f0188 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/tk.py @@ -0,0 +1,196 @@ +""" +Tkinter GUI progressbar decorator for iterators. + +Usage: +>>> from tqdm.tk import trange, tqdm +>>> for i in trange(10): +... ... +""" +import re +import sys +import tkinter +import tkinter.ttk as ttk +from warnings import warn + +from .std import TqdmExperimentalWarning, TqdmWarning +from .std import tqdm as std_tqdm + +__author__ = {"github.com/": ["richardsheridan", "casperdcl"]} +__all__ = ['tqdm_tk', 'ttkrange', 'tqdm', 'trange'] + + +class tqdm_tk(std_tqdm): # pragma: no cover + """ + Experimental Tkinter GUI version of tqdm! + + Note: Window interactivity suffers if `tqdm_tk` is not running within + a Tkinter mainloop and values are generated infrequently. In this case, + consider calling `tqdm_tk.refresh()` frequently in the Tk thread. + """ + + # TODO: @classmethod: write()? + + def __init__(self, *args, **kwargs): + """ + This class accepts the following parameters *in addition* to + the parameters accepted by `tqdm`. + + Parameters + ---------- + grab : bool, optional + Grab the input across all windows of the process. + tk_parent : `tkinter.Wm`, optional + Parent Tk window. + cancel_callback : Callable, optional + Create a cancel button and set `cancel_callback` to be called + when the cancel or window close button is clicked. + """ + kwargs = kwargs.copy() + kwargs['gui'] = True + # convert disable = None to False + kwargs['disable'] = bool(kwargs.get('disable', False)) + self._warn_leave = 'leave' in kwargs + grab = kwargs.pop('grab', False) + tk_parent = kwargs.pop('tk_parent', None) + self._cancel_callback = kwargs.pop('cancel_callback', None) + super().__init__(*args, **kwargs) + + if self.disable: + return + + if tk_parent is None: # Discover parent widget + try: + tk_parent = tkinter._default_root + except AttributeError: + raise AttributeError( + "`tk_parent` required when using `tkinter.NoDefaultRoot()`") + if tk_parent is None: # use new default root window as display + self._tk_window = tkinter.Tk() + else: # some other windows already exist + self._tk_window = tkinter.Toplevel() + else: + self._tk_window = tkinter.Toplevel(tk_parent) + + warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2) + self._tk_dispatching = self._tk_dispatching_helper() + + self._tk_window.protocol("WM_DELETE_WINDOW", self.cancel) + self._tk_window.wm_title(self.desc) + self._tk_window.wm_attributes("-topmost", 1) + self._tk_window.after(0, lambda: self._tk_window.wm_attributes("-topmost", 0)) + self._tk_n_var = tkinter.DoubleVar(self._tk_window, value=0) + self._tk_text_var = tkinter.StringVar(self._tk_window) + pbar_frame = ttk.Frame(self._tk_window, padding=5) + pbar_frame.pack() + _tk_label = ttk.Label(pbar_frame, textvariable=self._tk_text_var, + wraplength=600, anchor="center", justify="center") + _tk_label.pack() + self._tk_pbar = ttk.Progressbar( + pbar_frame, variable=self._tk_n_var, length=450) + if self.total is not None: + self._tk_pbar.configure(maximum=self.total) + else: + self._tk_pbar.configure(mode="indeterminate") + self._tk_pbar.pack() + if self._cancel_callback is not None: + _tk_button = ttk.Button(pbar_frame, text="Cancel", command=self.cancel) + _tk_button.pack() + if grab: + self._tk_window.grab_set() + + def close(self): + if self.disable: + return + + self.disable = True + + with self.get_lock(): + self._instances.remove(self) + + def _close(): + self._tk_window.after('idle', self._tk_window.destroy) + if not self._tk_dispatching: + self._tk_window.update() + + self._tk_window.protocol("WM_DELETE_WINDOW", _close) + + # if leave is set but we are self-dispatching, the left window is + # totally unresponsive unless the user manually dispatches + if not self.leave: + _close() + elif not self._tk_dispatching: + if self._warn_leave: + warn("leave flag ignored if not in tkinter mainloop", + TqdmWarning, stacklevel=2) + _close() + + def clear(self, *_, **__): + pass + + def display(self, *_, **__): + self._tk_n_var.set(self.n) + d = self.format_dict + # remove {bar} + d['bar_format'] = (d['bar_format'] or "{l_bar}{r_bar}").replace( + "{bar}", "") + msg = self.format_meter(**d) + if '' in msg: + msg = "".join(re.split(r'\|?\|?', msg, maxsplit=1)) + self._tk_text_var.set(msg) + if not self._tk_dispatching: + self._tk_window.update() + + def set_description(self, desc=None, refresh=True): + self.set_description_str(desc, refresh) + + def set_description_str(self, desc=None, refresh=True): + self.desc = desc + if not self.disable: + self._tk_window.wm_title(desc) + if refresh and not self._tk_dispatching: + self._tk_window.update() + + def cancel(self): + """ + `cancel_callback()` followed by `close()` + when close/cancel buttons clicked. + """ + if self._cancel_callback is not None: + self._cancel_callback() + self.close() + + def reset(self, total=None): + """ + Resets to 0 iterations for repeated use. + + Parameters + ---------- + total : int or float, optional. Total to use for the new bar. + """ + if hasattr(self, '_tk_pbar'): + if total is None: + self._tk_pbar.configure(maximum=100, mode="indeterminate") + else: + self._tk_pbar.configure(maximum=total, mode="determinate") + super().reset(total=total) + + @staticmethod + def _tk_dispatching_helper(): + """determine if Tkinter mainloop is dispatching events""" + codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__} + for frame in sys._current_frames().values(): + while frame: + if frame.f_code in codes: + return True + frame = frame.f_back + return False + + +def ttkrange(*args, **kwargs): + """Shortcut for `tqdm.tk.tqdm(range(*args), **kwargs)`.""" + return tqdm_tk(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_tk +trange = ttkrange diff --git a/parrot/lib/python3.10/site-packages/tqdm/tqdm.1 b/parrot/lib/python3.10/site-packages/tqdm/tqdm.1 new file mode 100644 index 0000000000000000000000000000000000000000..b90ab4b9ebdd183c98ee8ae0c7f0a65ac676e3b7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/tqdm.1 @@ -0,0 +1,314 @@ +.\" Automatically generated by Pandoc 1.19.2 +.\" +.TH "TQDM" "1" "2015\-2021" "tqdm User Manuals" "" +.hy +.SH NAME +.PP +tqdm \- fast, extensible progress bar for Python and CLI +.SH SYNOPSIS +.PP +tqdm [\f[I]options\f[]] +.SH DESCRIPTION +.PP +See . +Can be used as a pipe: +.IP +.nf +\f[C] +$\ #\ count\ lines\ of\ code +$\ cat\ *.py\ |\ tqdm\ |\ wc\ \-l +327it\ [00:00,\ 981773.38it/s] +327 + +$\ #\ find\ all\ files +$\ find\ .\ \-name\ "*.py"\ |\ tqdm\ |\ wc\ \-l +432it\ [00:00,\ 833842.30it/s] +432 + +#\ ...\ and\ more\ info +$\ find\ .\ \-name\ \[aq]*.py\[aq]\ \-exec\ wc\ \-l\ \\{}\ \\;\ \\ +\ \ |\ tqdm\ \-\-total\ 432\ \-\-unit\ files\ \-\-desc\ counting\ \\ +\ \ |\ awk\ \[aq]{\ sum\ +=\ $1\ };\ END\ {\ print\ sum\ }\[aq] +counting:\ 100%|█████████|\ 432/432\ [00:00<00:00,\ 794361.83files/s] +131998 +\f[] +.fi +.SH OPTIONS +.TP +.B \-h, \-\-help +Print this help and exit. +.RS +.RE +.TP +.B \-v, \-\-version +Print version and exit. +.RS +.RE +.TP +.B \-\-desc=\f[I]desc\f[] +str, optional. +Prefix for the progressbar. +.RS +.RE +.TP +.B \-\-total=\f[I]total\f[] +int or float, optional. +The number of expected iterations. +If unspecified, len(iterable) is used if possible. +If float("inf") or as a last resort, only basic progress statistics are +displayed (no ETA, no progressbar). +If \f[C]gui\f[] is True and this parameter needs subsequent updating, +specify an initial arbitrary large positive number, e.g. +9e9. +.RS +.RE +.TP +.B \-\-leave +bool, optional. +If [default: True], keeps all traces of the progressbar upon termination +of iteration. +If \f[C]None\f[], will leave only if \f[C]position\f[] is \f[C]0\f[]. +.RS +.RE +.TP +.B \-\-ncols=\f[I]ncols\f[] +int, optional. +The width of the entire output message. +If specified, dynamically resizes the progressbar to stay within this +bound. +If unspecified, attempts to use environment width. +The fallback is a meter width of 10 and no limit for the counter and +statistics. +If 0, will not print any meter (only stats). +.RS +.RE +.TP +.B \-\-mininterval=\f[I]mininterval\f[] +float, optional. +Minimum progress display update interval [default: 0.1] seconds. +.RS +.RE +.TP +.B \-\-maxinterval=\f[I]maxinterval\f[] +float, optional. +Maximum progress display update interval [default: 10] seconds. +Automatically adjusts \f[C]miniters\f[] to correspond to +\f[C]mininterval\f[] after long display update lag. +Only works if \f[C]dynamic_miniters\f[] or monitor thread is enabled. +.RS +.RE +.TP +.B \-\-miniters=\f[I]miniters\f[] +int or float, optional. +Minimum progress display update interval, in iterations. +If 0 and \f[C]dynamic_miniters\f[], will automatically adjust to equal +\f[C]mininterval\f[] (more CPU efficient, good for tight loops). +If > 0, will skip display of specified number of iterations. +Tweak this and \f[C]mininterval\f[] to get very efficient loops. +If your progress is erratic with both fast and slow iterations (network, +skipping items, etc) you should set miniters=1. +.RS +.RE +.TP +.B \-\-ascii=\f[I]ascii\f[] +bool or str, optional. +If unspecified or False, use unicode (smooth blocks) to fill the meter. +The fallback is to use ASCII characters " 123456789#". +.RS +.RE +.TP +.B \-\-disable +bool, optional. +Whether to disable the entire progressbar wrapper [default: False]. +If set to None, disable on non\-TTY. +.RS +.RE +.TP +.B \-\-unit=\f[I]unit\f[] +str, optional. +String that will be used to define the unit of each iteration [default: +it]. +.RS +.RE +.TP +.B \-\-unit\-scale=\f[I]unit_scale\f[] +bool or int or float, optional. +If 1 or True, the number of iterations will be reduced/scaled +automatically and a metric prefix following the International System of +Units standard will be added (kilo, mega, etc.) [default: False]. +If any other non\-zero number, will scale \f[C]total\f[] and \f[C]n\f[]. +.RS +.RE +.TP +.B \-\-dynamic\-ncols +bool, optional. +If set, constantly alters \f[C]ncols\f[] and \f[C]nrows\f[] to the +environment (allowing for window resizes) [default: False]. +.RS +.RE +.TP +.B \-\-smoothing=\f[I]smoothing\f[] +float, optional. +Exponential moving average smoothing factor for speed estimates (ignored +in GUI mode). +Ranges from 0 (average speed) to 1 (current/instantaneous speed) +[default: 0.3]. +.RS +.RE +.TP +.B \-\-bar\-format=\f[I]bar_format\f[] +str, optional. +Specify a custom bar string formatting. +May impact performance. +[default: \[aq]{l_bar}{bar}{r_bar}\[aq]], where l_bar=\[aq]{desc}: +{percentage:3.0f}%|\[aq] and r_bar=\[aq]| {n_fmt}/{total_fmt} +[{elapsed}<{remaining}, \[aq] \[aq]{rate_fmt}{postfix}]\[aq] Possible +vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, +elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, +rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, +unit_divisor, remaining, remaining_s, eta. +Note that a trailing ": " is automatically removed after {desc} if the +latter is empty. +.RS +.RE +.TP +.B \-\-initial=\f[I]initial\f[] +int or float, optional. +The initial counter value. +Useful when restarting a progress bar [default: 0]. +If using float, consider specifying \f[C]{n:.3f}\f[] or similar in +\f[C]bar_format\f[], or specifying \f[C]unit_scale\f[]. +.RS +.RE +.TP +.B \-\-position=\f[I]position\f[] +int, optional. +Specify the line offset to print this bar (starting from 0) Automatic if +unspecified. +Useful to manage multiple bars at once (eg, from threads). +.RS +.RE +.TP +.B \-\-postfix=\f[I]postfix\f[] +dict or *, optional. +Specify additional stats to display at the end of the bar. +Calls \f[C]set_postfix(**postfix)\f[] if possible (dict). +.RS +.RE +.TP +.B \-\-unit\-divisor=\f[I]unit_divisor\f[] +float, optional. +[default: 1000], ignored unless \f[C]unit_scale\f[] is True. +.RS +.RE +.TP +.B \-\-write\-bytes +bool, optional. +Whether to write bytes. +If (default: False) will write unicode. +.RS +.RE +.TP +.B \-\-lock\-args=\f[I]lock_args\f[] +tuple, optional. +Passed to \f[C]refresh\f[] for intermediate output (initialisation, +iterating, and updating). +.RS +.RE +.TP +.B \-\-nrows=\f[I]nrows\f[] +int, optional. +The screen height. +If specified, hides nested bars outside this bound. +If unspecified, attempts to use environment height. +The fallback is 20. +.RS +.RE +.TP +.B \-\-colour=\f[I]colour\f[] +str, optional. +Bar colour (e.g. +\[aq]green\[aq], \[aq]#00ff00\[aq]). +.RS +.RE +.TP +.B \-\-delay=\f[I]delay\f[] +float, optional. +Don\[aq]t display until [default: 0] seconds have elapsed. +.RS +.RE +.TP +.B \-\-delim=\f[I]delim\f[] +chr, optional. +Delimiting character [default: \[aq]\\n\[aq]]. +Use \[aq]\\0\[aq] for null. +N.B.: on Windows systems, Python converts \[aq]\\n\[aq] to +\[aq]\\r\\n\[aq]. +.RS +.RE +.TP +.B \-\-buf\-size=\f[I]buf_size\f[] +int, optional. +String buffer size in bytes [default: 256] used when \f[C]delim\f[] is +specified. +.RS +.RE +.TP +.B \-\-bytes +bool, optional. +If true, will count bytes, ignore \f[C]delim\f[], and default +\f[C]unit_scale\f[] to True, \f[C]unit_divisor\f[] to 1024, and +\f[C]unit\f[] to \[aq]B\[aq]. +.RS +.RE +.TP +.B \-\-tee +bool, optional. +If true, passes \f[C]stdin\f[] to both \f[C]stderr\f[] and +\f[C]stdout\f[]. +.RS +.RE +.TP +.B \-\-update +bool, optional. +If true, will treat input as newly elapsed iterations, i.e. +numbers to pass to \f[C]update()\f[]. +Note that this is slow (~2e5 it/s) since every input must be decoded as +a number. +.RS +.RE +.TP +.B \-\-update\-to +bool, optional. +If true, will treat input as total elapsed iterations, i.e. +numbers to assign to \f[C]self.n\f[]. +Note that this is slow (~2e5 it/s) since every input must be decoded as +a number. +.RS +.RE +.TP +.B \-\-null +bool, optional. +If true, will discard input (no stdout). +.RS +.RE +.TP +.B \-\-manpath=\f[I]manpath\f[] +str, optional. +Directory in which to install tqdm man pages. +.RS +.RE +.TP +.B \-\-comppath=\f[I]comppath\f[] +str, optional. +Directory in which to place tqdm completion. +.RS +.RE +.TP +.B \-\-log=\f[I]log\f[] +str, optional. +CRITICAL|FATAL|ERROR|WARN(ING)|[default: \[aq]INFO\[aq]]|DEBUG|NOTSET. +.RS +.RE +.SH AUTHORS +tqdm developers . diff --git a/parrot/lib/python3.10/site-packages/tqdm/version.py b/parrot/lib/python3.10/site-packages/tqdm/version.py new file mode 100644 index 0000000000000000000000000000000000000000..11cbaea79d1f4f46f9ae4bea542d7c66ded96e34 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/tqdm/version.py @@ -0,0 +1,9 @@ +"""`tqdm` version detector. Precedence: installed dist, git, 'UNKNOWN'.""" +try: + from ._dist_ver import __version__ +except ImportError: + try: + from setuptools_scm import get_version + __version__ = get_version(root='..', relative_to=__file__) + except (ImportError, LookupError): + __version__ = "UNKNOWN" diff --git a/parrot/lib/python3.10/site-packages/validators-0.34.0.dist-info/INSTALLER b/parrot/lib/python3.10/site-packages/validators-0.34.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/validators-0.34.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/parrot/lib/python3.10/site-packages/validators-0.34.0.dist-info/METADATA b/parrot/lib/python3.10/site-packages/validators-0.34.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..4a571e06a4155dce13ecc4f97702f8fb8b492226 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/validators-0.34.0.dist-info/METADATA @@ -0,0 +1,79 @@ +Metadata-Version: 2.1 +Name: validators +Version: 0.34.0 +Summary: Python Data Validation for Humans™ +Author-email: Konsta Vesterinen +License: MIT +Project-URL: Homepage, https://python-validators.github.io/validators +Project-URL: Documentation, https://yozachar.github.io/pyvalidators +Project-URL: Repository, https://github.com/python-validators/validators +Project-URL: Changelog, https://github.com/python-validators/validators/blob/master/CHANGES.md +Keywords: validation,validator,python-validator +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: LICENSE.txt +Provides-Extra: crypto-eth-addresses +Requires-Dist: eth-hash[pycryptodome] >=0.7.0 ; extra == 'crypto-eth-addresses' + +# validators - Python Data Validation for Humans™ + +[![PyCQA][pycqa-badge]][pycqa-link] [![SAST][sast-badge]][sast-link] [![Docs][docs-badge]][docs-link] [![Version][vs-badge]][vs-link] [![Downloads][dw-badge]][dw-link] + + + +Python has all kinds of data validation tools, but every one of them seems to +require defining a schema or form. I wanted to create a simple validation +library where validating a simple value does not require defining a form or a +schema. + +```python +>>> import validators +>>> +>>> validators.email('someone@example.com') +True +``` + +## Resources + + + + +- [Documentation](https://yozachar.github.io/pyvalidators) +- [Bugtracker](https://github.com/python-validators/validators/issues) +- [Security](https://github.com/python-validators/validators/blob/master/SECURITY.md) +- [Code](https://github.com/python-validators/validators/) + + + +--- + +> **_Python 3.8 [reaches EOL in](https://endoflife.date/python) October 2024._** + + +[sast-badge]: https://github.com/python-validators/validators/actions/workflows/sast.yaml/badge.svg +[sast-link]: https://github.com/python-validators/validators/actions/workflows/sast.yaml +[pycqa-badge]: https://github.com/python-validators/validators/actions/workflows/pycqa.yaml/badge.svg +[pycqa-link]: https://github.com/python-validators/validators/actions/workflows/pycqa.yaml +[docs-badge]: https://github.com/yozachar/pyvalidators/actions/workflows/pages/pages-build-deployment/badge.svg +[docs-link]: https://github.com/yozachar/pyvalidators/actions/workflows/pages/pages-build-deployment +[vs-badge]: https://img.shields.io/pypi/v/validators?logo=pypi&logoColor=white&label=version&color=blue +[vs-link]: https://pypi.python.org/pypi/validators/ +[dw-badge]: https://img.shields.io/pypi/dm/validators?logo=pypi&logoColor=white&color=blue +[dw-link]: https://pypi.python.org/pypi/validators/ + + diff --git a/parrot/lib/python3.10/site-packages/validators-0.34.0.dist-info/WHEEL b/parrot/lib/python3.10/site-packages/validators-0.34.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..3ad1642709d9bc766a327667f66ac7cd20c9fc49 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/validators-0.34.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (74.1.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/parrot/lib/python3.10/site-packages/wandb/cli/__pycache__/cli.cpython-310.pyc b/parrot/lib/python3.10/site-packages/wandb/cli/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..915e1e2bf6bd33668db1502e603672ea875310e8 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/wandb/cli/__pycache__/cli.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/wandb/cli/cli.py b/parrot/lib/python3.10/site-packages/wandb/cli/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..c9e7ca9607affb59c52dc72a9c81bed6de39629c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/cli/cli.py @@ -0,0 +1,3007 @@ +#!/usr/bin/env python + +import asyncio +import configparser +import datetime +import getpass +import json +import logging +import os +import pathlib +import shlex +import shutil +import subprocess +import sys +import tempfile +import textwrap +import time +import traceback +from functools import wraps +from typing import Any, Dict, Optional + +import click +import yaml +from click.exceptions import ClickException + +# pycreds has a find_executable that works in windows +from dockerpycreds.utils import find_executable + +import wandb +import wandb.env + +# from wandb.old.core import wandb_dir +import wandb.errors +import wandb.sdk.verify.verify as wandb_verify +from wandb import Config, Error, env, util, wandb_agent, wandb_sdk +from wandb.apis import InternalApi, PublicApi +from wandb.apis.public import RunQueue +from wandb.errors import UsageError, WandbCoreNotAvailableError +from wandb.integration.magic import magic_install +from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache +from wandb.sdk.launch import utils as launch_utils +from wandb.sdk.launch._launch_add import _launch_add +from wandb.sdk.launch.errors import ExecutionError, LaunchError +from wandb.sdk.launch.sweeps import utils as sweep_utils +from wandb.sdk.launch.sweeps.scheduler import Scheduler +from wandb.sdk.lib import filesystem +from wandb.sdk.lib.wburls import wburls +from wandb.sync import SyncManager, get_run_from_path, get_runs +from wandb.util import get_core_path + +# Send cli logs to wandb/debug-cli..log by default and fallback to a temp dir. +_wandb_dir = wandb.old.core.wandb_dir(env.get_dir()) +if not os.path.exists(_wandb_dir): + _wandb_dir = tempfile.gettempdir() + +try: + _username = getpass.getuser() +except KeyError: + # getuser() could raise KeyError in restricted environments like + # chroot jails or docker containers. Return user id in these cases. + _username = str(os.getuid()) + +_wandb_log_path = os.path.join(_wandb_dir, f"debug-cli.{_username}.log") + +logging.basicConfig( + filename=_wandb_log_path, + level=logging.INFO, + format="%(asctime)s %(levelname)s %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", +) +logging.basicConfig(stream=sys.stdout, level=logging.INFO) +logger = logging.getLogger("wandb") + +# Click Contexts +CONTEXT = {"default_map": {}} +RUN_CONTEXT = { + "default_map": {}, + "allow_extra_args": True, + "ignore_unknown_options": True, +} + + +def cli_unsupported(argument): + wandb.termerror(f"Unsupported argument `{argument}`") + sys.exit(1) + + +class ClickWandbException(ClickException): + def format_message(self): + # log_file = util.get_log_file_path() + log_file = "" + orig_type = f"{self.orig_type.__module__}.{self.orig_type.__name__}" + if issubclass(self.orig_type, Error): + return click.style(str(self.message), fg="red") + else: + return ( + f"An Exception was raised, see {log_file} for full traceback.\n" + f"{orig_type}: {self.message}" + ) + + +def display_error(func): + """Function decorator for catching common errors and re-raising as wandb.Error.""" + + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except wandb.Error as e: + exc_type, exc_value, exc_traceback = sys.exc_info() + lines = traceback.format_exception(exc_type, exc_value, exc_traceback) + logger.error("".join(lines)) + wandb.termerror(f"Find detailed error logs at: {_wandb_log_path}") + click_exc = ClickWandbException(e) + click_exc.orig_type = exc_type + raise click_exc.with_traceback(sys.exc_info()[2]) + + return wrapper + + +_api = None # caching api instance allows patching from unit tests + + +def _get_cling_api(reset=None): + """Get a reference to the internal api with cling settings.""" + # TODO: move CLI to wandb-core backend + wandb.require("legacy-service") + + global _api + if reset: + _api = None + wandb_sdk.wandb_setup._setup(_reset=True) + if _api is None: + # TODO(jhr): make a settings object that is better for non runs. + # only override the necessary setting + wandb.setup(settings=dict(_cli_only_mode=True)) + _api = InternalApi() + return _api + + +def prompt_for_project(ctx, entity): + """Ask the user for a project, creating one if necessary.""" + result = ctx.invoke(projects, entity=entity, display=False) + api = _get_cling_api() + try: + if len(result) == 0: + project = click.prompt("Enter a name for your first project") + # description = editor() + project = api.upsert_project(project, entity=entity)["name"] + else: + project_names = [project["name"] for project in result] + ["Create New"] + wandb.termlog("Which project should we use?") + result = util.prompt_choices(project_names) + if result: + project = result + else: + project = "Create New" + # TODO: check with the server if the project exists + if project == "Create New": + project = click.prompt( + "Enter a name for your new project", value_proc=api.format_project + ) + # description = editor() + project = api.upsert_project(project, entity=entity)["name"] + + except wandb.errors.CommError as e: + raise ClickException(str(e)) + + return project + + +class RunGroup(click.Group): + @display_error + def get_command(self, ctx, cmd_name): + # TODO: check if cmd_name is a file in the current dir and not require `run`? + rv = click.Group.get_command(self, ctx, cmd_name) + if rv is not None: + return rv + return None + + +@click.command(cls=RunGroup, invoke_without_command=True) +@click.version_option(version=wandb.__version__) +@click.pass_context +def cli(ctx): + if ctx.invoked_subcommand is None: + click.echo(ctx.get_help()) + + +@cli.command(context_settings=CONTEXT, help="List projects", hidden=True) +@click.option( + "--entity", + "-e", + default=None, + envvar=env.ENTITY, + help="The entity to scope the listing to.", +) +@display_error +def projects(entity, display=True): + api = _get_cling_api() + projects = api.list_projects(entity=entity) + if len(projects) == 0: + message = "No projects found for {}".format(entity) + else: + message = 'Latest projects for "{}"'.format(entity) + if display: + click.echo(click.style(message, bold=True)) + for project in projects: + click.echo( + "".join( + ( + click.style(project["name"], fg="blue", bold=True), + " - ", + str(project["description"] or "").split("\n")[0], + ) + ) + ) + return projects + + +@cli.command(context_settings=CONTEXT, help="Login to Weights & Biases") +@click.argument("key", nargs=-1) +@click.option("--cloud", is_flag=True, help="Login to the cloud instead of local") +@click.option("--host", default=None, help="Login to a specific instance of W&B") +@click.option( + "--relogin", default=None, is_flag=True, help="Force relogin if already logged in." +) +@click.option("--anonymously", default=False, is_flag=True, help="Log in anonymously") +@click.option("--verify", default=False, is_flag=True, help="Verify login credentials") +@display_error +def login(key, host, cloud, relogin, anonymously, verify, no_offline=False): + # TODO: move CLI to wandb-core backend + wandb.require("legacy-service") + + # TODO: handle no_offline + anon_mode = "must" if anonymously else "never" + + wandb_sdk.wandb_login._handle_host_wandb_setting(host, cloud) + # A change in click or the test harness means key can be none... + key = key[0] if key is not None and len(key) > 0 else None + if key: + relogin = True + + login_settings = dict( + _cli_only_mode=True, + _disable_viewer=relogin and not verify, + anonymous=anon_mode, + ) + if host is not None: + login_settings["base_url"] = host + + try: + wandb.setup(settings=login_settings) + except TypeError as e: + wandb.termerror(str(e)) + sys.exit(1) + + wandb.login( + relogin=relogin, + key=key, + anonymous=anon_mode, + host=host, + force=True, + verify=verify, + ) + + +@cli.command( + context_settings=CONTEXT, help="Run a wandb service", name="service", hidden=True +) +@click.option( + "--sock-port", default=None, type=int, help="The host port to bind socket service." +) +@click.option("--port-filename", default=None, help="Save allocated port to file.") +@click.option("--address", default=None, help="The address to bind service.") +@click.option("--pid", default=None, type=int, help="The parent process id to monitor.") +@click.option("--debug", is_flag=True, help="log debug info") +@click.option("--serve-sock", is_flag=True, help="use socket mode") +@display_error +def service( + sock_port=None, + port_filename=None, + address=None, + pid=None, + debug=False, + serve_sock=False, +): + from wandb.sdk.service.server import WandbServer + + server = WandbServer( + sock_port=sock_port, + port_fname=port_filename, + address=address, + pid=pid, + debug=debug, + serve_sock=serve_sock, + ) + server.serve() + + +@cli.command( + context_settings=CONTEXT, help="Configure a directory with Weights & Biases" +) +@click.option("--project", "-p", help="The project to use.") +@click.option("--entity", "-e", help="The entity to scope the project to.") +# TODO(jhr): Enable these with settings rework +# @click.option("--setting", "-s", help="enable an arbitrary setting.", multiple=True) +# @click.option('--show', is_flag=True, help="Show settings") +@click.option("--reset", is_flag=True, help="Reset settings") +@click.option( + "--mode", + "-m", + help=' Can be "online", "offline" or "disabled". Defaults to online.', +) +@click.pass_context +@display_error +def init(ctx, project, entity, reset, mode): + from wandb.old.core import __stage_dir__, _set_stage_dir, wandb_dir + + if __stage_dir__ is None: + _set_stage_dir("wandb") + + # non-interactive init + if reset or project or entity or mode: + api = InternalApi() + if reset: + api.clear_setting("entity", persist=True) + api.clear_setting("project", persist=True) + api.clear_setting("mode", persist=True) + # TODO(jhr): clear more settings? + if entity: + api.set_setting("entity", entity, persist=True) + if project: + api.set_setting("project", project, persist=True) + if mode: + api.set_setting("mode", mode, persist=True) + return + + if os.path.isdir(wandb_dir()) and os.path.exists( + os.path.join(wandb_dir(), "settings") + ): + click.confirm( + click.style( + "This directory has been configured previously, should we re-configure it?", + bold=True, + ), + abort=True, + ) + else: + click.echo( + click.style("Let's setup this directory for W&B!", fg="green", bold=True) + ) + api = _get_cling_api() + if api.api_key is None: + ctx.invoke(login) + api = _get_cling_api(reset=True) + + viewer = api.viewer() + + # Viewer can be `None` in case your API information became invalid, or + # in testing if you switch hosts. + if not viewer: + click.echo( + click.style( + "Your login information seems to be invalid: can you log in again please?", + fg="red", + bold=True, + ) + ) + ctx.invoke(login) + api = _get_cling_api(reset=True) + + # This shouldn't happen. + viewer = api.viewer() + if not viewer: + click.echo( + click.style( + "We're sorry, there was a problem logging you in. " + "Please send us a note at support@wandb.com and tell us how this happened.", + fg="red", + bold=True, + ) + ) + sys.exit(1) + + # At this point we should be logged in successfully. + if len(viewer["teams"]["edges"]) > 1: + team_names = [e["node"]["name"] for e in viewer["teams"]["edges"]] + [ + "Manual entry" + ] + wandb.termlog( + "Which team should we use?", + ) + result = util.prompt_choices(team_names) + # result can be empty on click + if result: + entity = result + else: + entity = "Manual Entry" + if entity == "Manual Entry": + entity = click.prompt("Enter the name of the team you want to use") + else: + entity = viewer.get("entity") or click.prompt( + "What username or team should we use?" + ) + + # TODO: this error handling sucks and the output isn't pretty + try: + project = prompt_for_project(ctx, entity) + except ClickWandbException: + raise ClickException(f"Could not find team: {entity}") + + api.set_setting("entity", entity, persist=True) + api.set_setting("project", project, persist=True) + api.set_setting("base_url", api.settings().get("base_url"), persist=True) + + filesystem.mkdir_exists_ok(wandb_dir()) + with open(os.path.join(wandb_dir(), ".gitignore"), "w") as file: + file.write("*\n!settings") + + click.echo( + click.style("This directory is configured! Next, track a run:\n", fg="green") + + textwrap.dedent( + """\ + * In your training script: + {code1} + {code2} + * then `{run}`. + """ + ).format( + code1=click.style("import wandb", bold=True), + code2=click.style('wandb.init(project="{}")'.format(project), bold=True), + run=click.style("python ", bold=True), + ) + ) + + +@cli.group() +def beta(): + """Beta versions of wandb CLI commands. Requires wandb-core.""" + # this is the future that requires wandb-core! + import wandb.env + + wandb._sentry.configure_scope(process_context="wandb_beta") + + if wandb.env.is_require_legacy_service(): + raise UsageError( + "wandb beta commands can only be used with wandb-core. " + f"Please make sure that `{wandb.env._REQUIRE_LEGACY_SERVICE}` is not set." + ) + + try: + get_core_path() + except WandbCoreNotAvailableError as e: + wandb._sentry.exception(f"using `wandb beta`. failed with {e}") + click.secho( + (e), + fg="red", + err=True, + ) + + +@beta.command( + name="sync", + context_settings=CONTEXT, + help="Upload a training run to W&B", +) +@click.pass_context +@click.argument("wandb_dir", nargs=1, type=click.Path(exists=True)) +@click.option("--id", "run_id", help="The run you want to upload to.") +@click.option("--project", "-p", help="The project you want to upload to.") +@click.option("--entity", "-e", help="The entity to scope to.") +@click.option("--skip-console", is_flag=True, default=False, help="Skip console logs") +@click.option("--append", is_flag=True, default=False, help="Append run") +@click.option( + "--include", + "-i", + help="Glob to include. Can be used multiple times.", + multiple=True, +) +@click.option( + "--exclude", + "-e", + help="Glob to exclude. Can be used multiple times.", + multiple=True, +) +@click.option( + "--mark-synced/--no-mark-synced", + is_flag=True, + default=True, + help="Mark runs as synced", +) +@click.option( + "--skip-synced/--no-skip-synced", + is_flag=True, + default=True, + help="Skip synced runs", +) +@click.option( + "--dry-run", is_flag=True, help="Perform a dry run without uploading anything." +) +@display_error +def sync_beta( + ctx, + wandb_dir=None, + run_id: Optional[str] = None, + project: Optional[str] = None, + entity: Optional[str] = None, + skip_console: bool = False, + append: bool = False, + include: Optional[str] = None, + exclude: Optional[str] = None, + skip_synced: bool = True, + mark_synced: bool = True, + dry_run: bool = False, +): + import concurrent.futures + from multiprocessing import cpu_count + + paths = set() + + # TODO: test file discovery logic + # include and exclude globs are evaluated relative to the provided base_path + if include: + for pattern in include: + matching_dirs = list(pathlib.Path(wandb_dir).glob(pattern)) + for d in matching_dirs: + if not d.is_dir(): + continue + wandb_files = [p for p in d.glob("*.wandb") if p.is_file()] + if len(wandb_files) > 1: + print(f"Multiple wandb files found in directory {d}, skipping") + elif len(wandb_files) == 1: + paths.add(d) + else: + paths.update({p.parent for p in pathlib.Path(wandb_dir).glob("**/*.wandb")}) + + for pattern in exclude: + matching_dirs = list(pathlib.Path(wandb_dir).glob(pattern)) + for d in matching_dirs: + if not d.is_dir(): + continue + if d in paths: + paths.remove(d) + + # remove paths that are already synced, if requested + if skip_synced: + synced_paths = set() + for path in paths: + wandb_synced_files = [p for p in path.glob("*.wandb.synced") if p.is_file()] + if len(wandb_synced_files) > 1: + print( + f"Multiple wandb.synced files found in directory {path}, skipping" + ) + elif len(wandb_synced_files) == 1: + synced_paths.add(path) + paths -= synced_paths + + if run_id and len(paths) > 1: + # TODO: handle this more gracefully + click.echo("id can only be set for a single run.", err=True) + sys.exit(1) + + if not paths: + click.echo("No runs to sync.") + return + + click.echo("Found runs:") + for path in paths: + click.echo(f" {path}") + + if dry_run: + return + + wandb.sdk.wandb_setup.setup() + + # TODO: make it thread-safe in the Rust code + with concurrent.futures.ProcessPoolExecutor( + max_workers=min(len(paths), cpu_count()) + ) as executor: + futures = [] + for path in paths: + # we already know there is only one wandb file in the directory + wandb_file = [p for p in path.glob("*.wandb") if p.is_file()][0] + future = executor.submit( + wandb._sync, + wandb_file, + run_id=run_id, + project=project, + entity=entity, + skip_console=skip_console, + append=append, + mark_synced=mark_synced, + ) + futures.append(future) + + # Wait for tasks to complete + for _ in concurrent.futures.as_completed(futures): + pass + + +@cli.command( + context_settings=CONTEXT, help="Upload an offline training directory to W&B" +) +@click.pass_context +@click.argument("path", nargs=-1, type=click.Path(exists=True)) +@click.option("--view", is_flag=True, default=False, help="View runs", hidden=True) +@click.option("--verbose", is_flag=True, default=False, help="Verbose", hidden=True) +@click.option("--id", "run_id", help="The run you want to upload to.") +@click.option("--project", "-p", help="The project you want to upload to.") +@click.option("--entity", "-e", help="The entity to scope to.") +@click.option( + "--job_type", + "job_type", + help="Specifies the type of run for grouping related runs together.", +) +@click.option( + "--sync-tensorboard/--no-sync-tensorboard", + is_flag=True, + default=None, + help="Stream tfevent files to wandb.", +) +@click.option("--include-globs", help="Comma separated list of globs to include.") +@click.option("--exclude-globs", help="Comma separated list of globs to exclude.") +@click.option( + "--include-online/--no-include-online", + is_flag=True, + default=None, + help="Include online runs", +) +@click.option( + "--include-offline/--no-include-offline", + is_flag=True, + default=None, + help="Include offline runs", +) +@click.option( + "--include-synced/--no-include-synced", + is_flag=True, + default=None, + help="Include synced runs", +) +@click.option( + "--mark-synced/--no-mark-synced", + is_flag=True, + default=True, + help="Mark runs as synced", +) +@click.option("--sync-all", is_flag=True, default=False, help="Sync all runs") +@click.option("--clean", is_flag=True, default=False, help="Delete synced runs") +@click.option( + "--clean-old-hours", + default=24, + help="Delete runs created before this many hours. To be used alongside --clean flag.", + type=int, +) +@click.option( + "--clean-force", + is_flag=True, + default=False, + help="Clean without confirmation prompt.", +) +@click.option("--ignore", hidden=True) +@click.option("--show", default=5, help="Number of runs to show") +@click.option("--append", is_flag=True, default=False, help="Append run") +@click.option("--skip-console", is_flag=True, default=False, help="Skip console logs") +@display_error +def sync( + ctx, + path=None, + view=None, + verbose=None, + run_id=None, + project=None, + entity=None, + job_type=None, # trace this back to SyncManager + sync_tensorboard=None, + include_globs=None, + exclude_globs=None, + include_online=None, + include_offline=None, + include_synced=None, + mark_synced=None, + sync_all=None, + ignore=None, + show=None, + clean=None, + clean_old_hours=24, + clean_force=None, + append=None, + skip_console=None, +): + api = _get_cling_api() + if not api.is_authenticated: + wandb.termlog("Login to W&B to sync offline runs") + ctx.invoke(login, no_offline=True) + api = _get_cling_api(reset=True) + + if ignore: + exclude_globs = ignore + if include_globs: + include_globs = include_globs.split(",") + if exclude_globs: + exclude_globs = exclude_globs.split(",") + + def _summary(): + all_items = get_runs( + include_online=True, + include_offline=True, + include_synced=True, + include_unsynced=True, + ) + sync_items = get_runs( + include_online=include_online if include_online is not None else True, + include_offline=include_offline if include_offline is not None else True, + include_synced=include_synced if include_synced is not None else False, + include_unsynced=True, + exclude_globs=exclude_globs, + include_globs=include_globs, + ) + synced = [] + unsynced = [] + for item in all_items: + (synced if item.synced else unsynced).append(item) + if sync_items: + wandb.termlog(f"Number of runs to be synced: {len(sync_items)}") + if show and show < len(sync_items): + wandb.termlog(f"Showing {show} runs to be synced:") + for item in sync_items[: (show or len(sync_items))]: + wandb.termlog(f" {item}") + else: + wandb.termlog("No runs to be synced.") + if synced: + clean_cmd = click.style("wandb sync --clean", fg="yellow") + wandb.termlog( + f"NOTE: use {clean_cmd} to delete {len(synced)} synced runs from local directory." + ) + if unsynced: + sync_cmd = click.style("wandb sync --sync-all", fg="yellow") + wandb.termlog( + f"NOTE: use {sync_cmd} to sync {len(unsynced)} unsynced runs from local directory." + ) + + def _sync_path(_path, _sync_tensorboard): + if run_id and len(_path) > 1: + wandb.termerror("id can only be set for a single run.") + sys.exit(1) + sm = SyncManager( + project=project, + entity=entity, + run_id=run_id, + job_type=job_type, + mark_synced=mark_synced, + app_url=api.app_url, + view=view, + verbose=verbose, + sync_tensorboard=_sync_tensorboard, + log_path=_wandb_log_path, + append=append, + skip_console=skip_console, + ) + for p in _path: + sm.add(p) + sm.start() + while not sm.is_done(): + _ = sm.poll() + + def _sync_all(): + sync_items = get_runs( + include_online=include_online if include_online is not None else True, + include_offline=include_offline if include_offline is not None else True, + include_synced=include_synced if include_synced is not None else False, + include_unsynced=True, + exclude_globs=exclude_globs, + include_globs=include_globs, + ) + if not sync_items: + wandb.termerror("Nothing to sync.") + else: + # When syncing run directories, default to not syncing tensorboard + sync_tb = sync_tensorboard if sync_tensorboard is not None else False + _sync_path(sync_items, sync_tb) + + def _clean(): + if path: + runs = list(map(get_run_from_path, path)) + if not clean_force: + click.confirm( + click.style( + f"Are you sure you want to remove {len(runs)} runs?", + bold=True, + ), + abort=True, + ) + for run in runs: + shutil.rmtree(run.path) + click.echo(click.style("Success!", fg="green")) + return + runs = get_runs( + include_online=include_online if include_online is not None else True, + include_offline=include_offline if include_offline is not None else True, + include_synced=include_synced if include_synced is not None else True, + include_unsynced=False, + exclude_globs=exclude_globs, + include_globs=include_globs, + ) + since = datetime.datetime.now() - datetime.timedelta(hours=clean_old_hours) + old_runs = [run for run in runs if run.datetime < since] + old_runs.sort(key=lambda _run: _run.datetime) + if old_runs: + click.echo( + f"Found {len(runs)} runs, {len(old_runs)} are older than {clean_old_hours} hours" + ) + for run in old_runs: + click.echo(run.path) + if not clean_force: + click.confirm( + click.style( + f"Are you sure you want to remove {len(old_runs)} runs?", + bold=True, + ), + abort=True, + ) + for run in old_runs: + shutil.rmtree(run.path) + click.echo(click.style("Success!", fg="green")) + else: + click.echo( + click.style( + f"No runs older than {clean_old_hours} hours found", fg="red" + ) + ) + + if sync_all: + _sync_all() + elif clean: + _clean() + elif path: + # When syncing a specific path, default to syncing tensorboard + sync_tb = sync_tensorboard if sync_tensorboard is not None else True + _sync_path(path, sync_tb) + else: + _summary() + + +@cli.command( + context_settings=CONTEXT, + help="Initialize a hyperparameter sweep. Search for hyperparameters that optimizes a cost function of a machine learning model by testing various combinations.", +) +@click.option( + "--project", + "-p", + default=None, + help="""The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled Uncategorized.""", +) +@click.option( + "--entity", + "-e", + default=None, + help="""The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.""", +) +@click.option("--controller", is_flag=True, default=False, help="Run local controller") +@click.option("--verbose", is_flag=True, default=False, help="Display verbose output") +@click.option( + "--name", + default=None, + help="The name of the sweep. The sweep ID is used if no name is specified.", +) +@click.option("--program", default=None, help="Set sweep program") +@click.option("--settings", default=None, help="Set sweep settings", hidden=True) +@click.option("--update", default=None, help="Update pending sweep") +@click.option( + "--stop", + is_flag=True, + default=False, + help="Finish a sweep to stop running new runs and let currently running runs finish.", +) +@click.option( + "--cancel", + is_flag=True, + default=False, + help="Cancel a sweep to kill all running runs and stop running new runs.", +) +@click.option( + "--pause", + is_flag=True, + default=False, + help="Pause a sweep to temporarily stop running new runs.", +) +@click.option( + "--resume", + is_flag=True, + default=False, + help="Resume a sweep to continue running new runs.", +) +@click.option( + "--prior_run", + "-R", + "prior_runs", + multiple=True, + default=None, + help="ID of an existing run to add to this sweep", +) +@click.argument("config_yaml_or_sweep_id") +@click.pass_context +@display_error +def sweep( + ctx, + project, + entity, + controller, + verbose, + name, + program, + settings, + update, + stop, + cancel, + pause, + resume, + prior_runs, + config_yaml_or_sweep_id, +): + state_args = "stop", "cancel", "pause", "resume" + lcls = locals() + is_state_change_command = sum(lcls[k] for k in state_args) + if is_state_change_command > 1: + raise Exception("Only one state flag (stop/cancel/pause/resume) is allowed.") + elif is_state_change_command == 1: + sweep_id = config_yaml_or_sweep_id + api = _get_cling_api() + if not api.is_authenticated: + wandb.termlog("Login to W&B to use the sweep feature") + ctx.invoke(login, no_offline=True) + api = _get_cling_api(reset=True) + parts = dict(entity=entity, project=project, name=sweep_id) + err = sweep_utils.parse_sweep_id(parts) + if err: + wandb.termerror(err) + return + entity = parts.get("entity") or entity + project = parts.get("project") or project + sweep_id = parts.get("name") or sweep_id + state = [s for s in state_args if lcls[s]][0] + ings = { + "stop": "Stopping", + "cancel": "Cancelling", + "pause": "Pausing", + "resume": "Resuming", + } + wandb.termlog(f"{ings[state]} sweep {entity}/{project}/{sweep_id}") + getattr(api, "{}_sweep".format(state))(sweep_id, entity=entity, project=project) + wandb.termlog("Done.") + return + else: + config_yaml = config_yaml_or_sweep_id + + def _parse_settings(settings): + """Parse settings from json or comma separated assignments.""" + ret = {} + # TODO(jhr): merge with magic:_parse_magic + if settings.find("=") > 0: + for item in settings.split(","): + kv = item.split("=") + if len(kv) != 2: + wandb.termwarn( + "Unable to parse sweep settings key value pair", repeat=False + ) + ret.update(dict([kv])) + return ret + wandb.termwarn("Unable to parse settings parameter", repeat=False) + return ret + + api = _get_cling_api() + if not api.is_authenticated: + wandb.termlog("Login to W&B to use the sweep feature") + ctx.invoke(login, no_offline=True) + api = _get_cling_api(reset=True) + + sweep_obj_id = None + if update: + parts = dict(entity=entity, project=project, name=update) + err = sweep_utils.parse_sweep_id(parts) + if err: + wandb.termerror(err) + return + entity = parts.get("entity") or entity + project = parts.get("project") or project + sweep_id = parts.get("name") or update + + has_project = (project or api.settings("project")) is not None + has_entity = (entity or api.settings("entity")) is not None + + termerror_msg = ( + "Sweep lookup requires a valid %s, and none was specified. \n" + "Either set a default %s in wandb/settings, or, if invoking \n`wandb sweep` " + "from the command line, specify the full sweep path via: \n\n" + " wandb sweep {username}/{projectname}/{sweepid}\n\n" + ) + + if not has_entity: + wandb.termerror(termerror_msg % (("entity",) * 2)) + return + + if not has_project: + wandb.termerror(termerror_msg % (("project",) * 2)) + return + + found = api.sweep(sweep_id, "{}", entity=entity, project=project) + if not found: + wandb.termerror(f"Could not find sweep {entity}/{project}/{sweep_id}") + return + sweep_obj_id = found["id"] + + action = "Updating" if sweep_obj_id else "Creating" + wandb.termlog(f"{action} sweep from: {config_yaml}") + config = sweep_utils.load_sweep_config(config_yaml) + + # Set or override parameters + if name: + config["name"] = name + if program: + config["program"] = program + if settings: + settings = _parse_settings(settings) + if settings: + config.setdefault("settings", {}) + config["settings"].update(settings) + if controller: + config.setdefault("controller", {}) + config["controller"]["type"] = "local" + + is_local = config.get("controller", {}).get("type") == "local" + if is_local: + from wandb import controller as wandb_controller + + tuner = wandb_controller() + err = tuner._validate(config) + if err: + wandb.termerror(f"Error in sweep file: {err}") + return + + env = os.environ + entity = ( + entity + or env.get("WANDB_ENTITY") + or config.get("entity") + or api.settings("entity") + ) + project = ( + project + or env.get("WANDB_PROJECT") + or config.get("project") + or api.settings("project") + or util.auto_project_name(config.get("program")) + ) + + sweep_id, warnings = api.upsert_sweep( + config, + project=project, + entity=entity, + obj_id=sweep_obj_id, + prior_runs=prior_runs, + ) + sweep_utils.handle_sweep_config_violations(warnings) + + # Log nicely formatted sweep information + styled_id = click.style(sweep_id, fg="yellow") + wandb.termlog(f"{action} sweep with ID: {styled_id}") + + sweep_url = wandb_sdk.wandb_sweep._get_sweep_url(api, sweep_id) + if sweep_url: + styled_url = click.style(sweep_url, underline=True, fg="blue") + wandb.termlog(f"View sweep at: {styled_url}") + + # re-probe entity and project if it was auto-detected by upsert_sweep + entity = entity or env.get("WANDB_ENTITY") + project = project or env.get("WANDB_PROJECT") + + if entity and project: + sweep_path = f"{entity}/{project}/{sweep_id}" + elif project: + sweep_path = f"{project}/{sweep_id}" + else: + sweep_path = sweep_id + + if sweep_path.find(" ") >= 0: + sweep_path = f"{sweep_path!r}" + + styled_path = click.style(f"wandb agent {sweep_path}", fg="yellow") + wandb.termlog(f"Run sweep agent with: {styled_path}") + if controller: + wandb.termlog("Starting wandb controller...") + from wandb import controller as wandb_controller + + tuner = wandb_controller(sweep_id) + tuner.run(verbose=verbose) + + +@cli.command( + context_settings=CONTEXT, + no_args_is_help=True, + help="Run a W&B launch sweep (Experimental).", +) +@click.option( + "--queue", + "-q", + default=None, + help="The name of a queue to push the sweep to", +) +@click.option( + "--project", + "-p", + default=None, + help="Name of the project which the agent will watch. " + "If passed in, will override the project value passed in using a config file", +) +@click.option( + "--entity", + "-e", + default=None, + help="The entity to use. Defaults to current logged-in user", +) +@click.option( + "--resume_id", + "-r", + default=None, + help="Resume a launch sweep by passing an 8-char sweep id. Queue required", +) +@click.option( + "--prior_run", + "-R", + "prior_runs", + multiple=True, + default=None, + help="ID of an existing run to add to this sweep", +) +@click.argument("config", required=False, type=click.Path(exists=True)) +@click.pass_context +@display_error +def launch_sweep( + ctx, + project, + entity, + queue, + config, + resume_id, + prior_runs, +): + api = _get_cling_api() + env = os.environ + if not api.is_authenticated: + wandb.termlog("Login to W&B to use the sweep feature") + ctx.invoke(login, no_offline=True) + api = _get_cling_api(reset=True) + + entity = entity or env.get("WANDB_ENTITY") or api.settings("entity") + if entity is None: + wandb.termerror("Must specify entity when using launch") + return + + project = project or env.get("WANDB_PROJECT") or api.settings("project") + if project is None: + wandb.termerror("A project must be configured when using launch") + return + + # get personal username, not team name or service account, default to entity + author = api.viewer().get("username") or entity + + # if not sweep_config XOR resume_id + if not (config or resume_id): + wandb.termerror("'config' and/or 'resume_id' required") + return + + parsed_user_config = sweep_utils.load_launch_sweep_config(config) + # Rip special keys out of config, store in scheduler run_config + launch_args: Dict[str, Any] = parsed_user_config.pop("launch", {}) + scheduler_args: Dict[str, Any] = parsed_user_config.pop("scheduler", {}) + settings: Dict[str, Any] = scheduler_args.pop("settings", {}) + + scheduler_job: Optional[str] = scheduler_args.get("job") + if scheduler_job: + wandb.termwarn( + "Using a scheduler job for launch sweeps is *experimental* and may change without warning" + ) + queue: Optional[str] = queue or launch_args.get("queue") + + sweep_config, sweep_obj_id = None, None + if not resume_id: + sweep_config = parsed_user_config + + # check method + method = sweep_config.get("method") + if scheduler_job and not method: + sweep_config["method"] = "custom" + elif scheduler_job and method != "custom": + # TODO(gst): Check if using Anaconda2 + wandb.termwarn( + "Use 'method': 'custom' in the sweep config when using scheduler jobs, " + "or omit it entirely. For jobs using the wandb optimization engine (WandbScheduler), " + "set the method in the sweep config under scheduler.settings.method " + ) + settings["method"] = method + + if settings.get("method"): + # assume WandbScheduler, and user is using this right + sweep_config["method"] = settings["method"] + + else: # Resuming an existing sweep + found = api.sweep(resume_id, "{}", entity=entity, project=project) + if not found: + wandb.termerror(f"Could not find sweep {entity}/{project}/{resume_id}") + return + + if found.get("state") == "RUNNING": + wandb.termerror( + f"Cannot resume sweep {entity}/{project}/{resume_id}, it is already running" + ) + return + + sweep_obj_id = found["id"] + sweep_config = yaml.safe_load(found["config"]) + wandb.termlog(f"Resuming from existing sweep {entity}/{project}/{resume_id}") + if len(parsed_user_config.keys()) > 0: + wandb.termwarn( + "Sweep parameters loaded from resumed sweep, ignoring provided config" + ) + + prev_scheduler = json.loads(found.get("scheduler") or "{}") + run_spec = json.loads(prev_scheduler.get("run_spec", "{}")) + if ( + scheduler_job + and run_spec.get("job") + and run_spec.get("job") != scheduler_job + ): + wandb.termerror( + f"Resuming a launch sweep with a different scheduler job is not supported. Job loaded from sweep: {run_spec.get('job')}, job in config: {scheduler_job}" + ) + return + + prev_scheduler_args, prev_settings = sweep_utils.get_previous_args(run_spec) + # Passed in scheduler_args and settings override previous + scheduler_args.update(prev_scheduler_args) + settings.update(prev_settings) + if not queue: + wandb.termerror( + "Launch-sweeps require setting a 'queue', use --queue option or a 'queue' key in the 'launch' section in the config" + ) + return + + entrypoint = Scheduler.ENTRYPOINT if not scheduler_job else None + args = sweep_utils.construct_scheduler_args( + return_job=scheduler_job is not None, + sweep_config=sweep_config, + queue=queue, + project=project, + author=author, + ) + if not args: + return + + # validate training job existence + if not sweep_utils.check_job_exists(PublicApi(), sweep_config.get("job")): + return False + + # validate scheduler job existence, if present + if not sweep_utils.check_job_exists(PublicApi(), scheduler_job): + return False + + # Set run overrides for the Scheduler + overrides = {"run_config": {}} + if launch_args: + overrides["run_config"]["launch"] = launch_args + if scheduler_args: + overrides["run_config"]["scheduler"] = scheduler_args + if settings: + overrides["run_config"]["settings"] = settings + + if scheduler_job: + overrides["run_config"]["sweep_args"] = args + else: + overrides["args"] = args + + # configure scheduler job resource + resource = scheduler_args.get("resource") + if resource: + if resource == "local-process" and scheduler_job: + wandb.termerror( + "Scheduler jobs cannot be run with the 'local-process' resource" + ) + return + if resource == "local-process" and scheduler_args.get("docker_image"): + wandb.termerror( + "Scheduler jobs cannot be run with the 'local-process' resource and a docker image" + ) + return + else: # no resource set, default local-process if not scheduler job, else container + resource = "local-process" if not scheduler_job else "local-container" + + # Launch job spec for the Scheduler + launch_scheduler_spec = launch_utils.construct_launch_spec( + uri=Scheduler.PLACEHOLDER_URI, + api=api, + name="Scheduler.WANDB_SWEEP_ID", + project=project, + entity=entity, + docker_image=scheduler_args.get("docker_image"), + resource=resource, + entry_point=entrypoint, + resource_args=scheduler_args.get("resource_args", {}), + repository=launch_args.get("registry", {}).get("url", None), + job=scheduler_job, + version=None, + launch_config={"overrides": overrides}, + run_id="WANDB_SWEEP_ID", # scheduler inits run with sweep_id=run_id + author=None, # author gets passed into scheduler override args + ) + launch_scheduler_with_queue = json.dumps( + { + "queue": queue, + "run_queue_project": launch_utils.LAUNCH_DEFAULT_PROJECT, + "run_spec": json.dumps(launch_scheduler_spec), + } + ) + + sweep_id, warnings = api.upsert_sweep( + sweep_config, + project=project, + entity=entity, + obj_id=sweep_obj_id, # if resuming + launch_scheduler=launch_scheduler_with_queue, + state="PENDING", + prior_runs=prior_runs, + template_variable_values=scheduler_args.get("template_variables", None), + ) + sweep_utils.handle_sweep_config_violations(warnings) + # Log nicely formatted sweep information + styled_id = click.style(sweep_id, fg="yellow") + wandb.termlog(f"{'Resumed' if resume_id else 'Created'} sweep with ID: {styled_id}") + sweep_url = wandb_sdk.wandb_sweep._get_sweep_url(api, sweep_id) + if sweep_url: + styled_url = click.style(sweep_url, underline=True, fg="blue") + wandb.termlog(f"View sweep at: {styled_url}") + wandb.termlog(f"Scheduler added to launch queue ({queue})") + + +@cli.command(help=f"Launch or queue a W&B Job. See {wburls.get('cli_launch')}") +@click.option( + "--uri", + "-u", + metavar="(str)", + default=None, + help="Local path or git repo uri to launch. If provided this command will " + "create a job from the specified uri.", +) +@click.option( + "--job", + "-j", + metavar="(str)", + default=None, + help="Name of the job to launch. If passed in, launch does not require a uri.", +) +@click.option( + "--entry-point", + "-E", + metavar="NAME", + default=None, + help="""Entry point within project. [default: main]. If the entry point is not found, + attempts to run the project file with the specified name as a script, + using 'python' to run .py files and the default shell (specified by + environment variable $SHELL) to run .sh files. If passed in, will override the entrypoint value passed in using a config file.""", +) +@click.option( + "--git-version", + "-g", + metavar="GIT-VERSION", + hidden=True, + help="Version of the project to run, as a Git commit reference for Git projects.", +) +@click.option( + "--build-context", + metavar="(str)", + help="Path to the build context within the source code. Defaults to the " + "root of the source code. Compatible only with -u.", +) +@click.option( + "--job-name", + "-J", + metavar="(str)", + default=None, + hidden=True, + help="Name for the job created if the -u,--uri flag is passed in.", +) +@click.option( + "--name", + envvar="WANDB_NAME", + help="""Name of the run under which to launch the run. If not + specified, a random run name will be used to launch run. If passed in, will override the name passed in using a config file.""", +) +@click.option( + "--entity", + "-e", + metavar="(str)", + default=None, + help="""Name of the target entity which the new run will be sent to. Defaults to using the entity set by local wandb/settings folder. + If passed in, will override the entity value passed in using a config file.""", +) +@click.option( + "--project", + "-p", + metavar="(str)", + default=None, + help="""Name of the target project which the new run will be sent to. Defaults to using the project name given by the source uri + or for github runs, the git repo name. If passed in, will override the project value passed in using a config file.""", +) +@click.option( + "--resource", + "-r", + metavar="BACKEND", + default=None, + help="""Execution resource to use for run. Supported values: 'local-process', 'local-container', 'kubernetes', 'sagemaker', 'gcp-vertex'. + This is now a required parameter if pushing to a queue with no resource configuration. + If passed in, will override the resource value passed in using a config file.""", +) +@click.option( + "--docker-image", + "-d", + default=None, + metavar="DOCKER IMAGE", + help="""Specific docker image you'd like to use. In the form name:tag. + If passed in, will override the docker image value passed in using a config file.""", +) +@click.option( + "--base-image", + "-B", + default=None, + metavar="BASE IMAGE", + help="""Docker image to run job code in. Incompatible with --docker-image.""", +) +@click.option( + "--config", + "-c", + metavar="FILE", + help="""Path to JSON file (must end in '.json') or JSON string which will be passed + as a launch config. Dictation how the launched run will be configured.""", +) +@click.option( + "--set-var", + "-v", + "cli_template_vars", + default=None, + multiple=True, + help="""Set template variable values for queues with allow listing enabled, + as key-value pairs e.g. `--set-var key1=value1 --set-var key2=value2`""", +) +@click.option( + "--queue", + "-q", + is_flag=False, + flag_value="default", + default=None, + help="""Name of run queue to push to. If none, launches single run directly. If supplied without + an argument (`--queue`), defaults to queue 'default'. Else, if name supplied, specified run queue must exist under the + project and entity supplied.""", +) +@click.option( + "--async", + "run_async", + is_flag=True, + help="""Flag to run the job asynchronously. Defaults to false, i.e. unless --async is set, wandb launch will wait for + the job to finish. This option is incompatible with --queue; asynchronous options when running with an agent should be + set on wandb launch-agent.""", +) +@click.option( + "--resource-args", + "-R", + metavar="FILE", + help="""Path to JSON file (must end in '.json') or JSON string which will be passed + as resource args to the compute resource. The exact content which should be + provided is different for each execution backend. See documentation for layout of this file.""", +) +@click.option( + "--build", + "-b", + is_flag=True, + hidden=True, + help="Flag to build an associated job and push to queue as an image job.", +) +@click.option( + "--repository", + "-rg", + is_flag=False, + default=None, + hidden=True, + help="Name of a remote repository. Will be used to push a built image to.", +) +# TODO: this is only included for back compat. But we should remove this in the future +@click.option( + "--project-queue", + "-pq", + default=None, + hidden=True, + help="Name of the project containing the queue to push to. If none, defaults to entity level queues.", +) +@click.option( + "--dockerfile", + "-D", + default=None, + help="Path to the Dockerfile used to build the job, relative to the job's root", +) +@click.option( + "--priority", + "-P", + default=None, + type=click.Choice(["critical", "high", "medium", "low"]), + help="""When --queue is passed, set the priority of the job. Launch jobs with higher priority + are served first. The order, from highest to lowest priority, is: critical, high, medium, low""", +) +@display_error +def launch( + uri, + job, + entry_point, + git_version, + build_context, + name, + resource, + entity, + project, + docker_image, + base_image, + config, + cli_template_vars, + queue, + run_async, + resource_args, + build, + repository, + project_queue, + dockerfile, + priority, + job_name, +): + """Start a W&B run from the given URI. + + The URI can bea wandb URI, a GitHub repo uri, or a local path). In the case of a + wandb URI the arguments used in the original run will be used by default. These + arguments can be overridden using the args option, or specifying those arguments in + the config's 'overrides' key, 'args' field as a list of strings. + + Running `wandb launch [URI]` will launch the run directly. To add the run to a + queue, run `wandb launch [URI] --queue [optional queuename]`. + """ + logger.info( + f"=== Launch called with kwargs {locals()} CLI Version: {wandb.__version__}===" + ) + from wandb.sdk.launch._launch import _launch + from wandb.sdk.launch.create_job import _create_job + from wandb.sdk.launch.utils import _is_git_uri + + api = _get_cling_api() + wandb._sentry.configure_scope(process_context="launch_cli") + + if run_async and queue is not None: + raise LaunchError( + "Cannot use both --async and --queue with wandb launch, see help for details." + ) + + if queue and docker_image and not project: + raise LaunchError( + "Cannot use --queue and --docker together without a project. Please specify a project with --project or -p." + ) + + if priority is not None and queue is None: + raise LaunchError("--priority flag requires --queue to be set") + + if resource_args is not None: + resource_args = util.load_json_yaml_dict(resource_args) + if resource_args is None: + raise LaunchError("Invalid format for resource-args") + else: + resource_args = {} + + if entry_point is not None: + entry_point = shlex.split(entry_point) + + if config is not None: + config = util.load_json_yaml_dict(config) + if config is None: + raise LaunchError("Invalid format for config") + else: + config = {} + + resource = resource or config.get("resource") + + if build and queue is None: + raise LaunchError("Build flag requires a queue to be set") + + try: + launch_utils.check_logged_in(api) + except Exception: + wandb.termerror(f"Error running job: {traceback.format_exc()}") + + run_id = config.get("run_id") + + # If URI was provided, we need to create a job from it. + if uri: + if entry_point is None: + raise LaunchError( + "Cannot provide a uri without an entry point. Please provide an " + "entry point with --entry-point or -E." + ) + if job is not None: + raise LaunchError("Cannot provide both a uri and a job name.") + job_type = ( + "git" if _is_git_uri(uri) else "code" + ) # TODO: Add support for local URIs with git. + if entity is None: + entity = launch_utils.get_default_entity(api, config) + artifact, _, _ = _create_job( + api, + job_type, + uri, + entrypoint=" ".join(entry_point), + git_hash=git_version, + name=job_name, + project=project, + base_image=base_image, + build_context=build_context, + dockerfile=dockerfile, + entity=entity, + ) + if artifact is None: + raise LaunchError(f"Failed to create job from uri: {uri}") + job = f"{entity}/{project}/{artifact.name}" + + if dockerfile: + if "overrides" in config: + config["overrides"]["dockerfile"] = dockerfile + else: + config["overrides"] = {"dockerfile": dockerfile} + + if priority is not None: + priority_map = { + "critical": 0, + "high": 1, + "medium": 2, + "low": 3, + } + priority = priority_map[priority.lower()] + + template_variables = None + if cli_template_vars: + if queue is None: + raise LaunchError("'--set-var' flag requires queue to be set") + if entity is None: + entity = launch_utils.get_default_entity(api, config) + public_api = PublicApi() + runqueue = RunQueue(client=public_api.client, name=queue, entity=entity) + template_variables = launch_utils.fetch_and_validate_template_variables( + runqueue, cli_template_vars + ) + + if queue is None: + # direct launch + try: + run = asyncio.run( + _launch( + api, + job, + project=project, + entity=entity, + docker_image=docker_image, + name=name, + entry_point=entry_point, + version=git_version, + resource=resource, + resource_args=resource_args, + launch_config=config, + synchronous=(not run_async), + run_id=run_id, + repository=repository, + ) + ) + if asyncio.run(run.get_status()).state in [ + "failed", + "stopped", + "preempted", + ]: + wandb.termerror("Launched run exited with non-zero status") + sys.exit(1) + except LaunchError as e: + logger.error("=== %s ===", e) + wandb._sentry.exception(e) + sys.exit(e) + except ExecutionError as e: + logger.error("=== %s ===", e) + wandb._sentry.exception(e) + sys.exit(e) + except asyncio.CancelledError: + sys.exit(0) + else: + try: + _launch_add( + api, + job, + config, + template_variables, + project, + entity, + queue, + resource, + entry_point, + name, + git_version, + docker_image, + project_queue, + resource_args, + build=build, + run_id=run_id, + repository=repository, + priority=priority, + ) + + except Exception as e: + wandb._sentry.exception(e) + raise e + + +@cli.command( + context_settings=CONTEXT, + help="Run a W&B launch agent.", +) +@click.pass_context +@click.option( + "--queue", + "-q", + "queues", + default=None, + multiple=True, + metavar="", + help="The name of a queue for the agent to watch. Multiple -q flags supported.", +) +@click.option( + "--entity", + "-e", + default=None, + help="The entity to use. Defaults to current logged-in user", +) +@click.option( + "--log-file", + "-l", + default=None, + help=( + "Destination for internal agent logs. Use - for stdout. " + "By default all agents logs will go to debug.log in your wandb/ " + "subdirectory or WANDB_DIR if set." + ), +) +@click.option( + "--max-jobs", + "-j", + default=None, + help="The maximum number of launch jobs this agent can run in parallel. Defaults to 1. Set to -1 for no upper limit", +) +@click.option( + "--config", "-c", default=None, help="path to the agent config yaml to use" +) +@click.option( + "--url", + "-u", + default=None, + hidden=True, + help="a wandb client registration URL, this is generated in the UI", +) +@click.option("--verbose", "-v", count=True, help="Display verbose output") +@display_error +def launch_agent( + ctx, + entity=None, + queues=None, + max_jobs=None, + config=None, + url=None, + log_file=None, + verbose=0, +): + logger.info( + f"=== Launch-agent called with kwargs {locals()} CLI Version: {wandb.__version__} ===" + ) + if url is not None: + raise LaunchError( + "--url is not supported in this version, upgrade with: pip install -u wandb" + ) + + import wandb.sdk.launch._launch as _launch + + if log_file is not None: + _launch.set_launch_logfile(log_file) + + api = _get_cling_api() + wandb._sentry.configure_scope(process_context="launch_agent") + agent_config, api = _launch.resolve_agent_config( + entity, max_jobs, queues, config, verbose + ) + + if len(agent_config.get("queues")) == 0: + raise LaunchError( + "To launch an agent please specify a queue or a list of queues in the configuration file or cli." + ) + + launch_utils.check_logged_in(api) + + wandb.termlog("Starting launch agent ✨") + try: + _launch.create_and_run_agent(api, agent_config) + except Exception as e: + wandb._sentry.exception(e) + raise e + + +@cli.command(context_settings=CONTEXT, help="Run the W&B agent") +@click.pass_context +@click.option( + "--project", + "-p", + default=None, + help="""The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled 'Uncategorized'.""", +) +@click.option( + "--entity", + "-e", + default=None, + help="""The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.""", +) +@click.option( + "--count", default=None, type=int, help="The max number of runs for this agent." +) +@click.argument("sweep_id") +@display_error +def agent(ctx, project, entity, count, sweep_id): + api = _get_cling_api() + if not api.is_authenticated: + wandb.termlog("Login to W&B to use the sweep agent feature") + ctx.invoke(login, no_offline=True) + api = _get_cling_api(reset=True) + + wandb.termlog("Starting wandb agent 🕵️") + wandb_agent.agent(sweep_id, entity=entity, project=project, count=count) + + # you can send local commands like so: + # agent_api.command({'type': 'run', 'program': 'train.py', + # 'args': ['--max_epochs=10']}) + + +@cli.command( + context_settings=RUN_CONTEXT, help="Run a W&B launch sweep scheduler (Experimental)" +) +@click.pass_context +@click.argument("sweep_id") +@display_error +def scheduler( + ctx, + sweep_id, +): + api = InternalApi() + if not api.is_authenticated: + wandb.termlog("Login to W&B to use the sweep scheduler feature") + ctx.invoke(login, no_offline=True) + api = InternalApi(reset=True) + + wandb._sentry.configure_scope(process_context="sweep_scheduler") + wandb.termlog("Starting a Launch Scheduler 🚀") + from wandb.sdk.launch.sweeps import load_scheduler + + # TODO(gst): remove this monstrosity + # Future-proofing hack to pull any kwargs that get passed in through the CLI + kwargs = {} + for i, _arg in enumerate(ctx.args): + if isinstance(_arg, str) and _arg.startswith("--"): + # convert input kwargs from hyphens to underscores + _key = _arg[2:].replace("-", "_") + _args = ctx.args[i + 1] + if str.isdigit(_args): + _args = int(_args) + kwargs[_key] = _args + try: + sweep_type = kwargs.get("sweep_type", "wandb") + _scheduler = load_scheduler(scheduler_type=sweep_type)( + api, + sweep_id=sweep_id, + **kwargs, + ) + _scheduler.start() + except Exception as e: + wandb._sentry.exception(e) + raise e + + +@cli.group(help="Commands for managing and viewing W&B jobs") +def job() -> None: + pass + + +@job.command("list", help="List jobs in a project") +@click.option( + "--project", + "-p", + envvar=env.PROJECT, + help="The project you want to list jobs from.", +) +@click.option( + "--entity", + "-e", + default="models", + envvar=env.ENTITY, + help="The entity the jobs belong to", +) +def _list(project, entity): + wandb.termlog(f"Listing jobs in {entity}/{project}") + public_api = PublicApi() + try: + jobs = public_api.list_jobs(entity=entity, project=project) + except wandb.errors.CommError as e: + wandb.termerror(f"{e}") + return + + if len(jobs) == 0: + wandb.termlog("No jobs found") + return + + for job in jobs: + aliases = [] + if len(job["edges"]) == 0: + # deleted? + continue + + name = job["edges"][0]["node"]["artifactSequence"]["name"] + for version in job["edges"]: + aliases += [x["alias"] for x in version["node"]["aliases"]] + + # only list the most recent 10 job versions + aliases_str = ",".join(aliases[::-1]) + wandb.termlog(f"{name} -- versions ({len(aliases)}): {aliases_str}") + + +@job.command( + help="Describe a launch job. Provide the launch job in the form of: entity/project/job-name:alias-or-version" +) +@click.argument("job") +def describe(job): + public_api = PublicApi() + try: + job = public_api.job(name=job) + except wandb.errors.CommError as e: + wandb.termerror(f"{e}") + return + + for key in job._job_info: + if key.startswith("_"): + continue + wandb.termlog(f"{key}: {job._job_info[key]}") + + +@job.command( + no_args_is_help=True, +) +@click.option( + "--project", + "-p", + envvar=env.PROJECT, + help="The project you want to list jobs from.", +) +@click.option( + "--entity", + "-e", + envvar=env.ENTITY, + help="The entity the jobs belong to", +) +@click.option( + "--name", + "-n", + help="Name for the job", +) +@click.option( + "--description", + "-d", + help="Description for the job", +) +@click.option( + "--alias", + "-a", + "aliases", + help="Alias for the job", + multiple=True, + default=tuple(), +) +@click.option( + "--entry-point", + "-E", + "entrypoint", + help="Entrypoint to the script, including an executable and an entrypoint " + "file. Required for code or repo jobs. If --build-context is provided, " + "paths in the entrypoint command will be relative to the build context.", +) +@click.option( + "--git-hash", + "-g", + "git_hash", + type=str, + help="Commit reference to use as the source for git jobs", +) +@click.option( + "--runtime", + "-r", + type=str, + help="Python runtime to execute the job", +) +@click.option( + "--build-context", + "-b", + type=str, + help="Path to the build context from the root of the job source code. If " + "provided, this is used as the base path for the Dockerfile and entrypoint.", +) +@click.option( + "--base-image", + "-B", + type=str, + help="Base image to use for the job. Incompatible with image jobs.", +) +@click.option( + "--dockerfile", + "-D", + type=str, + help="Path to the Dockerfile for the job. If --build-context is provided, " + "the Dockerfile path will be relative to the build context.", +) +@click.argument( + "job_type", + type=click.Choice(("git", "code", "image")), +) +@click.argument("path") +def create( + path, + project, + entity, + name, + job_type, + description, + aliases, + entrypoint, + git_hash, + runtime, + build_context, + base_image, + dockerfile, +): + """Create a job from a source, without a wandb run. + + Jobs can be of three types, git, code, or image. + + git: A git source, with an entrypoint either in the path or provided explicitly pointing to the main python executable. + code: A code path, containing a requirements.txt file. + image: A docker image. + """ + from wandb.sdk.launch.create_job import _create_job + + api = _get_cling_api() + wandb._sentry.configure_scope(process_context="job_create") + + entity = entity or os.getenv("WANDB_ENTITY") or api.default_entity + if not entity: + wandb.termerror("No entity provided, use --entity or set WANDB_ENTITY") + return + + project = project or os.getenv("WANDB_PROJECT") + if not project: + wandb.termerror("No project provided, use --project or set WANDB_PROJECT") + return + + if entrypoint is None and job_type in ["git", "code"]: + wandb.termwarn( + f"No entrypoint provided for {job_type} job, defaulting to main.py" + ) + entrypoint = "main.py" + + if job_type == "image" and base_image: + wandb.termerror("Cannot provide --base-image/-B for an `image` job") + return + + artifact, action, aliases = _create_job( + api=api, + path=path, + entity=entity, + project=project, + name=name, + job_type=job_type, + description=description, + aliases=list(aliases), + entrypoint=entrypoint, + git_hash=git_hash, + runtime=runtime, + build_context=build_context, + base_image=base_image, + dockerfile=dockerfile, + ) + if not artifact: + wandb.termerror("Job creation failed") + return + + artifact_path = f"{entity}/{project}/{artifact.name}" + msg = f"{action} job: {click.style(artifact_path, fg='yellow')}" + if len(aliases) == 1: + alias_str = click.style(aliases[0], fg="yellow") + msg += f", with alias: {alias_str}" + elif len(aliases) > 1: + alias_str = click.style(", ".join(aliases), fg="yellow") + msg += f", with aliases: {alias_str}" + + wandb.termlog(msg) + web_url = util.app_url(api.settings().get("base_url")) + url = click.style(f"{web_url}/{entity}/{project}/jobs", underline=True) + wandb.termlog(f"View all jobs in project '{project}' here: {url}\n") + + +@cli.command(context_settings=CONTEXT, help="Run the W&B local sweep controller") +@click.option("--verbose", is_flag=True, default=False, help="Display verbose output") +@click.argument("sweep_id") +@display_error +def controller(verbose, sweep_id): + click.echo("Starting wandb controller...") + from wandb import controller as wandb_controller + + tuner = wandb_controller(sweep_id) + tuner.run(verbose=verbose) + + +@cli.command(context_settings=RUN_CONTEXT, name="docker-run") +@click.pass_context +@click.argument("docker_run_args", nargs=-1) +def docker_run(ctx, docker_run_args): + """Wrap `docker run` and adds WANDB_API_KEY and WANDB_DOCKER environment variables. + + This will also set the runtime to nvidia if the nvidia-docker executable is present + on the system and --runtime wasn't set. + + See `docker run --help` for more details. + """ + api = InternalApi() + args = list(docker_run_args) + if len(args) > 0 and args[0] == "run": + args.pop(0) + if len([a for a in args if a.startswith("--runtime")]) == 0 and find_executable( + "nvidia-docker" + ): + args = ["--runtime", "nvidia"] + args + # TODO: image_from_docker_args uses heuristics to find the docker image arg, there are likely cases + # where this won't work + image = util.image_from_docker_args(args) + resolved_image = None + if image: + resolved_image = wandb.docker.image_id(image) + if resolved_image: + args = ["-e", "WANDB_DOCKER={}".format(resolved_image)] + args + else: + wandb.termlog( + "Couldn't detect image argument, running command without the WANDB_DOCKER env variable" + ) + if api.api_key: + args = ["-e", "WANDB_API_KEY={}".format(api.api_key)] + args + else: + wandb.termlog( + "Not logged in, run `wandb login` from the host machine to enable result logging" + ) + subprocess.call(["docker", "run"] + args) + + +@cli.command(context_settings=RUN_CONTEXT) +@click.pass_context +@click.argument("docker_run_args", nargs=-1) +@click.argument("docker_image", required=False) +@click.option( + "--nvidia/--no-nvidia", + default=find_executable("nvidia-docker") is not None, + help="Use the nvidia runtime, defaults to nvidia if nvidia-docker is present", +) +@click.option( + "--digest", is_flag=True, default=False, help="Output the image digest and exit" +) +@click.option( + "--jupyter/--no-jupyter", default=False, help="Run jupyter lab in the container" +) +@click.option( + "--dir", default="/app", help="Which directory to mount the code in the container" +) +@click.option("--no-dir", is_flag=True, help="Don't mount the current directory") +@click.option( + "--shell", default="/bin/bash", help="The shell to start the container with" +) +@click.option("--port", default="8888", help="The host port to bind jupyter on") +@click.option("--cmd", help="The command to run in the container") +@click.option( + "--no-tty", is_flag=True, default=False, help="Run the command without a tty" +) +@display_error +def docker( + ctx, + docker_run_args, + docker_image, + nvidia, + digest, + jupyter, + dir, + no_dir, + shell, + port, + cmd, + no_tty, +): + """Run your code in a docker container. + + W&B docker lets you run your code in a docker image ensuring wandb is configured. It + adds the WANDB_DOCKER and WANDB_API_KEY environment variables to your container and + mounts the current directory in /app by default. You can pass additional args which + will be added to `docker run` before the image name is declared, we'll choose a + default image for you if one isn't passed: + + ```sh + wandb docker -v /mnt/dataset:/app/data + wandb docker gcr.io/kubeflow-images-public/tensorflow-1.12.0-notebook-cpu:v0.4.0 --jupyter + wandb docker wandb/deepo:keras-gpu --no-tty --cmd "python train.py --epochs=5" + ``` + + By default, we override the entrypoint to check for the existence of wandb and + install it if not present. If you pass the --jupyter flag we will ensure jupyter is + installed and start jupyter lab on port 8888. If we detect nvidia-docker on your + system we will use the nvidia runtime. If you just want wandb to set environment + variable to an existing docker run command, see the wandb docker-run command. + """ + api = InternalApi() + if not find_executable("docker"): + raise ClickException("Docker not installed, install it from https://docker.com") + args = list(docker_run_args) + image = docker_image or "" + # remove run for users used to nvidia-docker + if len(args) > 0 and args[0] == "run": + args.pop(0) + if image == "" and len(args) > 0: + image = args.pop(0) + # If the user adds docker args without specifying an image (should be rare) + if not util.docker_image_regex(image.split("@")[0]): + if image: + args = args + [image] + image = wandb.docker.default_image(gpu=nvidia) + subprocess.call(["docker", "pull", image]) + _, repo_name, tag = wandb.docker.parse(image) + + resolved_image = wandb.docker.image_id(image) + if resolved_image is None: + raise ClickException( + "Couldn't find image locally or in a registry, try running `docker pull {}`".format( + image + ) + ) + if digest: + sys.stdout.write(resolved_image) + exit(0) + + existing = wandb.docker.shell( + ["ps", "-f", "ancestor={}".format(resolved_image), "-q"] + ) + if existing: + if click.confirm( + "Found running container with the same image, do you want to attach?" + ): + subprocess.call(["docker", "attach", existing.split("\n")[0]]) + exit(0) + cwd = os.getcwd() + command = [ + "docker", + "run", + "-e", + "LANG=C.UTF-8", + "-e", + "WANDB_DOCKER={}".format(resolved_image), + "--ipc=host", + "-v", + wandb.docker.entrypoint + ":/wandb-entrypoint.sh", + "--entrypoint", + "/wandb-entrypoint.sh", + ] + if nvidia: + command.extend(["--runtime", "nvidia"]) + if not no_dir: + # TODO: We should default to the working directory if defined + command.extend(["-v", cwd + ":" + dir, "-w", dir]) + if api.api_key: + command.extend(["-e", "WANDB_API_KEY={}".format(api.api_key)]) + else: + wandb.termlog( + "Couldn't find WANDB_API_KEY, run `wandb login` to enable streaming metrics" + ) + if jupyter: + command.extend(["-e", "WANDB_ENSURE_JUPYTER=1", "-p", port + ":8888"]) + no_tty = True + cmd = "jupyter lab --no-browser --ip=0.0.0.0 --allow-root --NotebookApp.token= --notebook-dir {}".format( + dir + ) + command.extend(args) + if no_tty: + command.extend([image, shell, "-c", cmd]) + else: + if cmd: + command.extend(["-e", "WANDB_COMMAND={}".format(cmd)]) + command.extend(["-it", image, shell]) + wandb.termlog("Launching docker container \U0001f6a2") + subprocess.call(command) + + +@cli.command( + context_settings=RUN_CONTEXT, + help="Start a local W&B container (deprecated, see wandb server --help)", + hidden=True, +) +@click.pass_context +@click.option("--port", "-p", default="8080", help="The host port to bind W&B local on") +@click.option( + "--env", "-e", default=[], multiple=True, help="Env vars to pass to wandb/local" +) +@click.option( + "--daemon/--no-daemon", default=True, help="Run or don't run in daemon mode" +) +@click.option( + "--upgrade", is_flag=True, default=False, help="Upgrade to the most recent version" +) +@click.option( + "--edge", is_flag=True, default=False, help="Run the bleeding edge", hidden=True +) +@display_error +def local(ctx, *args, **kwargs): + wandb.termwarn("`wandb local` has been replaced with `wandb server start`.") + ctx.invoke(start, *args, **kwargs) + + +@cli.group(help="Commands for operating a local W&B server") +def server(): + pass + + +@server.command(context_settings=RUN_CONTEXT, help="Start a local W&B server") +@click.pass_context +@click.option( + "--port", "-p", default="8080", help="The host port to bind W&B server on" +) +@click.option( + "--env", "-e", default=[], multiple=True, help="Env vars to pass to wandb/local" +) +@click.option( + "--daemon/--no-daemon", default=True, help="Run or don't run in daemon mode" +) +@click.option( + "--upgrade", + is_flag=True, + default=False, + help="Upgrade to the most recent version", + hidden=True, +) +@click.option( + "--edge", is_flag=True, default=False, help="Run the bleeding edge", hidden=True +) +@display_error +def start(ctx, port, env, daemon, upgrade, edge): + api = InternalApi() + if not find_executable("docker"): + raise ClickException("Docker not installed, install it from https://docker.com") + local_image_sha = wandb.docker.image_id("wandb/local").split("wandb/local")[-1] + registry_image_sha = wandb.docker.image_id_from_registry("wandb/local").split( + "wandb/local" + )[-1] + if local_image_sha != registry_image_sha: + if upgrade: + subprocess.call(["docker", "pull", "wandb/local"]) + else: + wandb.termlog( + "A new version of the W&B server is available, upgrade by calling `wandb server start --upgrade`" + ) + running = subprocess.check_output( + ["docker", "ps", "--filter", "name=wandb-local", "--format", "{{.ID}}"] + ) + if running != b"": + if upgrade: + subprocess.call(["docker", "stop", "wandb-local"]) + else: + wandb.termerror( + "A container named wandb-local is already running, run `docker stop wandb-local` if you want to start a new instance" + ) + exit(1) + image = "docker.pkg.github.com/wandb/core/local" if edge else "wandb/local" + username = getpass.getuser() + env_vars = ["-e", "LOCAL_USERNAME={}".format(username)] + for e in env: + env_vars.append("-e") + env_vars.append(e) + command = [ + "docker", + "run", + "--rm", + "-v", + "wandb:/vol", + "-p", + port + ":8080", + "--name", + "wandb-local", + ] + env_vars + host = f"http://localhost:{port}" + api.set_setting("base_url", host, globally=True, persist=True) + if daemon: + command += ["-d"] + command += [image] + + # DEVNULL is only in py3 + try: + from subprocess import DEVNULL + except ImportError: + DEVNULL = open(os.devnull, "wb") # noqa: N806 + code = subprocess.call(command, stdout=DEVNULL) + if daemon: + if code != 0: + wandb.termerror( + "Failed to launch the W&B server container, see the above error." + ) + exit(1) + else: + wandb.termlog( + "W&B server started at http://localhost:{} \U0001f680".format(port) + ) + wandb.termlog("You can stop the server by running `wandb server stop`") + if not api.api_key: + # Let the server start before potentially launching a browser + time.sleep(2) + ctx.invoke(login, host=host) + + +@server.command(context_settings=RUN_CONTEXT, help="Stop a local W&B server") +def stop(): + if not find_executable("docker"): + raise ClickException("Docker not installed, install it from https://docker.com") + subprocess.call(["docker", "stop", "wandb-local"]) + + +@cli.group(help="Commands for interacting with artifacts") +def artifact(): + pass + + +@artifact.command(context_settings=CONTEXT, help="Upload an artifact to wandb") +@click.argument("path") +@click.option( + "--name", "-n", help="The name of the artifact to push: project/artifact_name" +) +@click.option("--description", "-d", help="A description of this artifact") +@click.option("--type", "-t", default="dataset", help="The type of the artifact") +@click.option( + "--alias", + "-a", + default=["latest"], + multiple=True, + help="An alias to apply to this artifact", +) +@click.option("--id", "run_id", help="The run you want to upload to.") +@click.option( + "--resume", + is_flag=True, + default=None, + help="Resume the last run from your current directory.", +) +@click.option( + "--skip_cache", + is_flag=True, + default=False, + help="Skip caching while uploading artifact files.", +) +@click.option( + "--policy", + default="mutable", + type=click.Choice(["mutable", "immutable"]), + help="Set the storage policy while uploading artifact files.", +) +@display_error +def put( + path, + name, + description, + type, + alias, + run_id, + resume, + skip_cache, + policy, +): + if name is None: + name = os.path.basename(path) + public_api = PublicApi() + entity, project, artifact_name = public_api._parse_artifact_path(name) + if project is None: + project = click.prompt("Enter the name of the project you want to use") + # TODO: settings nightmare... + api = InternalApi() + api.set_setting("entity", entity) + api.set_setting("project", project) + artifact = wandb.Artifact(name=artifact_name, type=type, description=description) + artifact_path = f"{entity}/{project}/{artifact_name}:{alias[0]}" + if os.path.isdir(path): + wandb.termlog(f'Uploading directory {path} to: "{artifact_path}" ({type})') + artifact.add_dir(path, skip_cache=skip_cache, policy=policy) + elif os.path.isfile(path): + wandb.termlog(f'Uploading file {path} to: "{artifact_path}" ({type})') + artifact.add_file(path, skip_cache=skip_cache, policy=policy) + elif "://" in path: + wandb.termlog( + f'Logging reference artifact from {path} to: "{artifact_path}" ({type})' + ) + artifact.add_reference(path) + else: + raise ClickException("Path argument must be a file or directory") + + with wandb.init( + entity=entity, + project=project, + config={"path": path}, + job_type="cli_put", + id=run_id, + resume=resume, + ) as run: + run.log_artifact(artifact, aliases=alias) + artifact.wait() + + wandb.termlog( + "Artifact uploaded, use this artifact in a run by adding:\n", prefix=False + ) + wandb.termlog( + f' artifact = run.use_artifact("{artifact.source_qualified_name}")\n', + prefix=False, + ) + + +@artifact.command(context_settings=CONTEXT, help="Download an artifact from wandb") +@click.argument("path") +@click.option("--root", help="The directory you want to download the artifact to") +@click.option("--type", help="The type of artifact you are downloading") +@display_error +def get(path, root, type): + public_api = PublicApi() + entity, project, artifact_name = public_api._parse_artifact_path(path) + if project is None: + project = click.prompt("Enter the name of the project you want to use") + + try: + artifact_parts = artifact_name.split(":") + if len(artifact_parts) > 1: + version = artifact_parts[1] + artifact_name = artifact_parts[0] + else: + version = "latest" + full_path = f"{entity}/{project}/{artifact_name}:{version}" + wandb.termlog( + "Downloading {type} artifact {full_path}".format( + type=type or "dataset", full_path=full_path + ) + ) + artifact = public_api.artifact(full_path, type=type) + path = artifact.download(root=root) + wandb.termlog("Artifact downloaded to {}".format(path)) + except ValueError: + raise ClickException("Unable to download artifact") + + +@artifact.command( + context_settings=CONTEXT, help="List all artifacts in a wandb project" +) +@click.argument("path") +@click.option("--type", "-t", help="The type of artifacts to list") +@display_error +def ls(path, type): + public_api = PublicApi() + if type is not None: + types = [public_api.artifact_type(type, path)] + else: + types = public_api.artifact_types(path) + + for kind in types: + for collection in kind.collections(): + versions = public_api.artifact_versions( + kind.type, + "/".join([kind.entity, kind.project, collection.name]), + per_page=1, + ) + latest = next(versions) + print( + "{:<15s}{:<15s}{:>15s} {:<20s}".format( + kind.type, + latest.updated_at, + util.to_human_size(latest.size), + latest.name, + ) + ) + + +@artifact.group(help="Commands for interacting with the artifact cache") +def cache(): + pass + + +@cache.command( + context_settings=CONTEXT, + help="Clean up less frequently used files from the artifacts cache", +) +@click.argument("target_size") +@click.option("--remove-temp/--no-remove-temp", default=False, help="Remove temp files") +@display_error +def cleanup(target_size, remove_temp): + target_size = util.from_human_size(target_size) + cache = get_artifact_file_cache() + reclaimed_bytes = cache.cleanup(target_size, remove_temp) + print(f"Reclaimed {util.to_human_size(reclaimed_bytes)} of space") + + +@cli.command(context_settings=CONTEXT, help="Pull files from Weights & Biases") +@click.argument("run", envvar=env.RUN_ID) +@click.option( + "--project", "-p", envvar=env.PROJECT, help="The project you want to download." +) +@click.option( + "--entity", + "-e", + default="models", + envvar=env.ENTITY, + help="The entity to scope the listing to.", +) +@display_error +def pull(run, project, entity): + api = InternalApi() + project, run = api.parse_slug(run, project=project) + urls = api.download_urls(project, run=run, entity=entity) + if len(urls) == 0: + raise ClickException("Run has no files") + click.echo(f"Downloading: {click.style(project, bold=True)}/{run}") + + for name in urls: + if api.file_current(name, urls[name]["md5"]): + click.echo("File {} is up to date".format(name)) + else: + length, response = api.download_file(urls[name]["url"]) + # TODO: I had to add this because some versions in CI broke click.progressbar + sys.stdout.write("File {}\r".format(name)) + dirname = os.path.dirname(name) + if dirname != "": + filesystem.mkdir_exists_ok(dirname) + with click.progressbar( + length=length, + label="File {}".format(name), + fill_char=click.style("&", fg="green"), + ) as bar: + with open(name, "wb") as f: + for data in response.iter_content(chunk_size=4096): + f.write(data) + bar.update(len(data)) + + +@cli.command( + context_settings=CONTEXT, help="Restore code, config and docker state for a run" +) +@click.pass_context +@click.argument("run", envvar=env.RUN_ID) +@click.option("--no-git", is_flag=True, default=False, help="Don't restore git state") +@click.option( + "--branch/--no-branch", + default=True, + help="Whether to create a branch or checkout detached", +) +@click.option( + "--project", "-p", envvar=env.PROJECT, help="The project you wish to upload to." +) +@click.option( + "--entity", "-e", envvar=env.ENTITY, help="The entity to scope the listing to." +) +@display_error +def restore(ctx, run, no_git, branch, project, entity): + from wandb.old.core import wandb_dir + + api = _get_cling_api() + if ":" in run: + if "/" in run: + entity, rest = run.split("/", 1) + else: + rest = run + project, run = rest.split(":", 1) + elif run.count("/") > 1: + entity, run = run.split("/", 1) + + project, run = api.parse_slug(run, project=project) + commit, json_config, patch_content, metadata = api.run_config( + project, run=run, entity=entity + ) + repo = metadata.get("git", {}).get("repo") + image = metadata.get("docker") + restore_message = """`wandb restore` needs to be run from the same git repository as the original run. +Run `git clone {}` and restore from there or pass the --no-git flag.""".format(repo) + if no_git: + commit = None + elif not api.git.enabled: + if repo: + raise ClickException(restore_message) + elif image: + wandb.termlog( + "Original run has no git history. Just restoring config and docker" + ) + + if commit and api.git.enabled: + wandb.termlog(f"Fetching origin and finding commit: {commit}") + subprocess.check_call(["git", "fetch", "--all"]) + try: + api.git.repo.commit(commit) + except ValueError: + wandb.termlog(f"Couldn't find original commit: {commit}") + commit = None + files = api.download_urls(project, run=run, entity=entity) + for filename in files: + if filename.startswith("upstream_diff_") and filename.endswith( + ".patch" + ): + commit = filename[len("upstream_diff_") : -len(".patch")] + try: + api.git.repo.commit(commit) + except ValueError: + commit = None + else: + break + + if commit: + wandb.termlog(f"Falling back to upstream commit: {commit}") + patch_path, _ = api.download_write_file(files[filename]) + else: + raise ClickException(restore_message) + else: + if patch_content: + patch_path = os.path.join(wandb_dir(), "diff.patch") + with open(patch_path, "w") as f: + f.write(patch_content) + else: + patch_path = None + + branch_name = "wandb/{}".format(run) + if branch and branch_name not in api.git.repo.branches: + api.git.repo.git.checkout(commit, b=branch_name) + wandb.termlog( + "Created branch {}".format(click.style(branch_name, bold=True)) + ) + elif branch: + wandb.termlog( + "Using existing branch, run `git branch -D {}` from master for a clean checkout".format( + branch_name + ) + ) + api.git.repo.git.checkout(branch_name) + else: + wandb.termlog("Checking out {} in detached mode".format(commit)) + api.git.repo.git.checkout(commit) + + if patch_path: + # we apply the patch from the repository root so git doesn't exclude + # things outside the current directory + root = api.git.root + patch_rel_path = os.path.relpath(patch_path, start=root) + # --reject is necessary or else this fails any time a binary file + # occurs in the diff + exit_code = subprocess.call( + ["git", "apply", "--reject", patch_rel_path], cwd=root + ) + if exit_code == 0: + wandb.termlog("Applied patch") + else: + wandb.termerror( + "Failed to apply patch, try un-staging any un-committed changes" + ) + + filesystem.mkdir_exists_ok(wandb_dir()) + config_path = os.path.join(wandb_dir(), "config.yaml") + config = Config() + for k, v in json_config.items(): + if k not in ("_wandb", "wandb_version"): + config[k] = v + s = b"wandb_version: 1" + s += b"\n\n" + yaml.dump( + config._as_dict(), + Dumper=yaml.SafeDumper, + default_flow_style=False, + allow_unicode=True, + encoding="utf-8", + ) + s = s.decode("utf-8") + with open(config_path, "w") as f: + f.write(s) + + wandb.termlog("Restored config variables to {}".format(config_path)) + if image: + if not metadata["program"].startswith("<") and metadata.get("args") is not None: + # TODO: we may not want to default to python here. + runner = util.find_runner(metadata["program"]) or ["python"] + command = runner + [metadata["program"]] + metadata["args"] + cmd = " ".join(command) + else: + wandb.termlog("Couldn't find original command, just restoring environment") + cmd = None + wandb.termlog("Docker image found, attempting to start") + ctx.invoke(docker, docker_run_args=[image], cmd=cmd) + + return commit, json_config, patch_content, repo, metadata + + +@cli.command(context_settings=CONTEXT, help="Run any script with wandb", hidden=True) +@click.pass_context +@click.argument("program") +@click.argument("args", nargs=-1) +@display_error +def magic(ctx, program, args): + def magic_run(cmd, globals, locals): + try: + exec(cmd, globals, locals) + finally: + pass + + sys.argv[:] = args + sys.argv.insert(0, program) + sys.path.insert(0, os.path.dirname(program)) + try: + with open(program, "rb") as fp: + code = compile(fp.read(), program, "exec") + except OSError: + click.echo( + click.style("Could not launch program: {}".format(program), fg="red") + ) + sys.exit(1) + globs = { + "__file__": program, + "__name__": "__main__", + "__package__": None, + "wandb_magic_install": magic_install, + } + prep = """ +import __main__ +__main__.__file__ = "{}" +wandb_magic_install() +""".format(program) + magic_run(prep, globs, None) + magic_run(code, globs, None) + + +@cli.command("online", help="Enable W&B sync") +@display_error +def online(): + api = InternalApi() + try: + api.clear_setting("disabled", persist=True) + api.clear_setting("mode", persist=True) + except configparser.Error: + pass + click.echo( + "W&B online. Running your script from this directory will now sync to the cloud." + ) + + +@cli.command("offline", help="Disable W&B sync") +@display_error +def offline(): + api = InternalApi() + try: + api.set_setting("disabled", "true", persist=True) + api.set_setting("mode", "offline", persist=True) + click.echo( + "W&B offline. Running your script from this directory will only write metadata locally. Use wandb disabled to completely turn off W&B." + ) + except configparser.Error: + click.echo( + "Unable to write config, copy and paste the following in your terminal to turn off W&B:\nexport WANDB_MODE=offline" + ) + + +@cli.command("on", hidden=True) +@click.pass_context +@display_error +def on(ctx): + ctx.invoke(online) + + +@cli.command("off", hidden=True) +@click.pass_context +@display_error +def off(ctx): + ctx.invoke(offline) + + +@cli.command("status", help="Show configuration settings") +@click.option( + "--settings/--no-settings", help="Show the current settings", default=True +) +def status(settings): + api = _get_cling_api() + if settings: + click.echo(click.style("Current Settings", bold=True)) + settings = api.settings() + click.echo( + json.dumps(settings, sort_keys=True, indent=2, separators=(",", ": ")) + ) + + +@cli.command("disabled", help="Disable W&B.") +@click.option( + "--service", + is_flag=True, + show_default=True, + default=True, + help="Disable W&B service", +) +def disabled(service): + api = InternalApi() + try: + api.set_setting("mode", "disabled", persist=True) + click.echo("W&B disabled.") + except configparser.Error: + click.echo( + "Unable to write config, copy and paste the following in your terminal to turn off W&B:\nexport WANDB_MODE=disabled" + ) + + +@cli.command("enabled", help="Enable W&B.") +@click.option( + "--service", + is_flag=True, + show_default=True, + default=True, + help="Enable W&B service", +) +def enabled(service): + api = InternalApi() + try: + api.set_setting("mode", "online", persist=True) + click.echo("W&B enabled.") + except configparser.Error: + click.echo( + "Unable to write config, copy and paste the following in your terminal to turn on W&B:\nexport WANDB_MODE=online" + ) + + +@cli.command(context_settings=CONTEXT, help="Verify your local instance") +@click.option("--host", default=None, help="Test a specific instance of W&B") +def verify(host): + # TODO: (kdg) Build this all into a WandbVerify object, and clean this up. + os.environ["WANDB_SILENT"] = "true" + os.environ["WANDB_PROJECT"] = "verify" + api = _get_cling_api() + reinit = False + if host is None: + host = api.settings("base_url") + print(f"Default host selected: {host}") + # if the given host does not match the default host, re-run init + elif host != api.settings("base_url"): + reinit = True + + tmp_dir = tempfile.mkdtemp() + print( + "Find detailed logs for this test at: {}".format(os.path.join(tmp_dir, "wandb")) + ) + os.chdir(tmp_dir) + os.environ["WANDB_BASE_URL"] = host + wandb.login(host=host) + if reinit: + api = _get_cling_api(reset=True) + if not wandb_verify.check_host(host): + sys.exit(1) + if not wandb_verify.check_logged_in(api, host): + sys.exit(1) + url_success, url = wandb_verify.check_graphql_put(api, host) + large_post_success = wandb_verify.check_large_post() + wandb_verify.check_secure_requests( + api.settings("base_url"), + "Checking requests to base url", + "Connections are not made over https. SSL required for secure communications.", + ) + if url: + wandb_verify.check_secure_requests( + url, + "Checking requests made over signed URLs", + "Signed URL requests not made over https. SSL is required for secure communications.", + ) + wandb_verify.check_cors_configuration(url, host) + wandb_verify.check_wandb_version(api) + check_run_success = wandb_verify.check_run(api) + check_artifacts_success = wandb_verify.check_artifacts() + if not ( + check_artifacts_success + and check_run_success + and large_post_success + and url_success + ): + sys.exit(1) diff --git a/parrot/lib/python3.10/site-packages/wandb/old/__init__.py b/parrot/lib/python3.10/site-packages/wandb/old/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f96058b267b119ee3fd8633a19856eb256142eab Binary files /dev/null and b/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/core.cpython-310.pyc b/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..633c7feb5143fcc6b55d47133d38a7ca829a8a92 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/core.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/settings.cpython-310.pyc b/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/settings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42b566b3efcf13b3efa00f9c028e9cfc6ef5c77e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/settings.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/summary.cpython-310.pyc b/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/summary.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aced4af31c0229aee26adeff590bdd3160b1a0c6 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/wandb/old/__pycache__/summary.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/wandb/old/core.py b/parrot/lib/python3.10/site-packages/wandb/old/core.py new file mode 100644 index 0000000000000000000000000000000000000000..4956fa7289cb13a9b60a44f887b7d13045f7817f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/old/core.py @@ -0,0 +1,131 @@ +"""Core variables, functions, and classes that we want in the wandb +module but are also used in modules that import the wandb module. + +The purpose of this module is to break circular imports. +""" + +import os +import sys +import tempfile +import time + +import click + +import wandb +from wandb import env + +# We use the hidden version if it already exists, otherwise non-hidden. +if os.path.exists(os.path.join(env.get_dir(os.getcwd()), ".wandb")): + __stage_dir__ = ".wandb" + os.sep +elif os.path.exists(os.path.join(env.get_dir(os.getcwd()), "wandb")): + __stage_dir__ = "wandb" + os.sep +else: + __stage_dir__ = None + +SCRIPT_PATH = os.path.abspath(sys.argv[0]) +wandb.START_TIME = time.time() +LIB_ROOT = os.path.join(os.path.dirname(__file__), "..") +IS_GIT = os.path.exists(os.path.join(LIB_ROOT, ".git")) + + +def wandb_dir(root_dir=None): + if root_dir is None or root_dir == "": + try: + cwd = os.getcwd() + except OSError: + termwarn("os.getcwd() no longer exists, using system temp directory") + cwd = tempfile.gettempdir() + root_dir = env.get_dir(cwd) + path = os.path.join(root_dir, __stage_dir__ or ("wandb" + os.sep)) + if not os.access(root_dir, os.W_OK): + termwarn( + f"Path {path} wasn't writable, using system temp directory", repeat=False + ) + path = os.path.join(tempfile.gettempdir(), __stage_dir__ or ("wandb" + os.sep)) + return path + + +def _set_stage_dir(stage_dir): + # Used when initing a new project with "wandb init" + global __stage_dir__ + __stage_dir__ = stage_dir + + +class Error(Exception): + """Base W&B Error""" + + def __init__(self, message): + super().__init__(message) + self.message = message + + # For python 2 support + def encode(self, encoding): + return self.message + + +class WandbWarning(Warning): + """Base W&B Warning""" + + pass + + +LOG_STRING = click.style("wandb", fg="blue", bold=True) +ERROR_STRING = click.style("ERROR", bg="red", fg="green") +WARN_STRING = click.style("WARNING", fg="yellow") +PRINTED_MESSAGES = set() + + +# TODO(adrian): if output has been redirected, make this write to the original STDERR +# so it doesn't get logged to the backend +def termlog(string="", newline=True, repeat=True): + """Log to standard error with formatting. + + Arguments: + string (str, optional): The string to print + newline (bool, optional): Print a newline at the end of the string + repeat (bool, optional): If set to False only prints the string once per process + """ + if string: + line = "\n".join([f"{LOG_STRING}: {s}" for s in string.split("\n")]) + else: + line = "" + if not repeat and line in PRINTED_MESSAGES: + return + # Repeated line tracking limited to 1k messages + if len(PRINTED_MESSAGES) < 1000: + PRINTED_MESSAGES.add(line) + if os.getenv(env.SILENT): + from wandb import util + from wandb.sdk.lib import filesystem + + filesystem.mkdir_exists_ok(os.path.dirname(util.get_log_file_path())) + with open(util.get_log_file_path(), "w") as log: + click.echo(line, file=log, nl=newline) + else: + click.echo(line, file=sys.stderr, nl=newline) + + +def termwarn(string, **kwargs): + string = "\n".join([f"{WARN_STRING} {s}" for s in string.split("\n")]) + termlog(string=string, newline=True, **kwargs) + + +def termerror(string, **kwargs): + string = "\n".join([f"{ERROR_STRING} {s}" for s in string.split("\n")]) + termlog(string=string, newline=True, **kwargs) + + +__all__ = [ + "__stage_dir__", + "SCRIPT_PATH", + "START_TIME", + "wandb_dir", + "_set_stage_dir", + "Error", + "WandbWarning", + "LOG_STRING", + "ERROR_STRING", + "termlog", + "termwarn", + "termerror", +] diff --git a/parrot/lib/python3.10/site-packages/wandb/old/summary.py b/parrot/lib/python3.10/site-packages/wandb/old/summary.py new file mode 100644 index 0000000000000000000000000000000000000000..e9b80b8aac1d790e5f1b11111cb36c0d1adc3a1a --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/old/summary.py @@ -0,0 +1,440 @@ +import json +import os +import time + +from wandb_gql import gql + +import wandb +from wandb import util +from wandb.apis.internal import Api +from wandb.sdk import lib as wandb_lib +from wandb.sdk.data_types.utils import val_to_json + +DEEP_SUMMARY_FNAME = "wandb.h5" +H5_TYPES = ("numpy.ndarray", "tensorflow.Tensor", "torch.Tensor") +h5py = util.get_module("h5py") +np = util.get_module("numpy") + + +class SummarySubDict: + """Nested dict-like object that proxies read and write operations through a root object. + + This lets us do synchronous serialization and lazy loading of large values. + """ + + def __init__(self, root=None, path=()): + self._path = tuple(path) + if root is None: + self._root = self + self._json_dict = {} + else: + self._root = root + json_dict = root._json_dict + for k in path: + json_dict = json_dict.get(k, {}) + + self._json_dict = json_dict + self._dict = {} + + # We use this to track which keys the user has set explicitly + # so that we don't automatically overwrite them when we update + # the summary from the history. + self._locked_keys = set() + + def __setattr__(self, k, v): + k = k.strip() + if k.startswith("_"): + object.__setattr__(self, k, v) + else: + self[k] = v + + def __getattr__(self, k): + k = k.strip() + if k.startswith("_"): + return object.__getattribute__(self, k) + else: + return self[k] + + def _root_get(self, path, child_dict): + """Load a value at a particular path from the root. + + This should only be implemented by the "_root" child class. + + We pass the child_dict so the item can be set on it or not as + appropriate. Returning None for a nonexistent path wouldn't be + distinguishable from that path being set to the value None. + """ + raise NotImplementedError + + def _root_set(self, path, new_keys_values): + """Set a value at a particular path in the root. + + This should only be implemented by the "_root" child class. + """ + raise NotImplementedError + + def _root_del(self, path): + """Delete a value at a particular path in the root. + + This should only be implemented by the "_root" child class. + """ + raise NotImplementedError + + def _write(self, commit=False): + # should only be implemented on the root summary + raise NotImplementedError + + def keys(self): + # _json_dict has the full set of keys, including those for h5 objects + # that may not have been loaded yet + return self._json_dict.keys() + + def get(self, k, default=None): + if isinstance(k, str): + k = k.strip() + if k not in self._dict: + self._root._root_get(self._path + (k,), self._dict) + return self._dict.get(k, default) + + def items(self): + # not all items may be loaded into self._dict, so we + # have to build the sequence of items from scratch + for k in self.keys(): + yield k, self[k] + + def __getitem__(self, k): + if isinstance(k, str): + k = k.strip() + + self.get(k) # load the value into _dict if it should be there + res = self._dict[k] + + return res + + def __contains__(self, k): + if isinstance(k, str): + k = k.strip() + + return k in self._json_dict + + def __setitem__(self, k, v): + if isinstance(k, str): + k = k.strip() + + path = self._path + + if isinstance(v, dict): + self._dict[k] = SummarySubDict(self._root, path + (k,)) + self._root._root_set(path, [(k, {})]) + self._dict[k].update(v) + else: + self._dict[k] = v + self._root._root_set(path, [(k, v)]) + + self._locked_keys.add(k) + + self._root._write() + + return v + + def __delitem__(self, k): + k = k.strip() + del self._dict[k] + self._root._root_del(self._path + (k,)) + + self._root._write() + + def __repr__(self): + # use a copy of _dict, except add placeholders for h5 objects, etc. + # that haven't been loaded yet + repr_dict = dict(self._dict) + for k in self._json_dict: + v = self._json_dict[k] + if ( + k not in repr_dict + and isinstance(v, dict) + and v.get("_type") in H5_TYPES + ): + # unloaded h5 objects may be very large. use a placeholder for them + # if we haven't already loaded them + repr_dict[k] = "..." + else: + repr_dict[k] = self[k] + + return repr(repr_dict) + + def update(self, key_vals=None, overwrite=True): + """Locked keys will be overwritten unless overwrite=False. + + Otherwise, written keys will be added to the "locked" list. + """ + if key_vals: + write_items = self._update(key_vals, overwrite) + self._root._root_set(self._path, write_items) + self._root._write(commit=True) + + def _update(self, key_vals, overwrite): + if not key_vals: + return + key_vals = {k.strip(): v for k, v in key_vals.items()} + if overwrite: + write_items = list(key_vals.items()) + self._locked_keys.update(key_vals.keys()) + else: + write_keys = set(key_vals.keys()) - self._locked_keys + write_items = [(k, key_vals[k]) for k in write_keys] + + for key, value in write_items: + if isinstance(value, dict): + self._dict[key] = SummarySubDict(self._root, self._path + (key,)) + self._dict[key]._update(value, overwrite) + else: + self._dict[key] = value + + return write_items + + +class Summary(SummarySubDict): + """Store summary metrics (eg. accuracy) during and after a run. + + You can manipulate this as if it's a Python dictionary but the keys + get mangled. .strip() is called on them, so spaces at the beginning + and end are removed. + """ + + def __init__(self, run, summary=None): + super().__init__() + self._run = run + self._h5_path = os.path.join(self._run.dir, DEEP_SUMMARY_FNAME) + # Lazy load the h5 file + self._h5 = None + + # Mirrored version of self._dict with versions of values that get written + # to JSON kept up to date by self._root_set() and self._root_del(). + self._json_dict = {} + + if summary is not None: + self._json_dict = summary + + def _json_get(self, path): + pass + + def _root_get(self, path, child_dict): + json_dict = self._json_dict + for key in path[:-1]: + json_dict = json_dict[key] + + key = path[-1] + if key in json_dict: + child_dict[key] = self._decode(path, json_dict[key]) + + def _root_del(self, path): + json_dict = self._json_dict + for key in path[:-1]: + json_dict = json_dict[key] + + val = json_dict[path[-1]] + del json_dict[path[-1]] + if isinstance(val, dict) and val.get("_type") in H5_TYPES: + if not h5py: + wandb.termerror("Deleting tensors in summary requires h5py") + else: + self.open_h5() + h5_key = "summary/" + ".".join(path) + del self._h5[h5_key] + self._h5.flush() + + def _root_set(self, path, new_keys_values): + json_dict = self._json_dict + for key in path: + json_dict = json_dict[key] + + for new_key, new_value in new_keys_values: + json_dict[new_key] = self._encode(new_value, path + (new_key,)) + + def write_h5(self, path, val): + # ensure the file is open + self.open_h5() + + if not self._h5: + wandb.termerror("Storing tensors in summary requires h5py") + else: + try: + del self._h5["summary/" + ".".join(path)] + except KeyError: + pass + self._h5["summary/" + ".".join(path)] = val + self._h5.flush() + + def read_h5(self, path, val=None): + # ensure the file is open + self.open_h5() + + if not self._h5: + wandb.termerror("Reading tensors from summary requires h5py") + else: + return self._h5.get("summary/" + ".".join(path), val) + + def open_h5(self): + if not self._h5 and h5py: + self._h5 = h5py.File(self._h5_path, "a", libver="latest") + + def _decode(self, path, json_value): + """Decode a `dict` encoded by `Summary._encode()`, loading h5 objects. + + h5 objects may be very large, so we won't have loaded them automatically. + """ + if isinstance(json_value, dict): + if json_value.get("_type") in H5_TYPES: + return self.read_h5(path, json_value) + elif json_value.get("_type") == "data-frame": + wandb.termerror( + "This data frame was saved via the wandb data API. Contact support@wandb.com for help." + ) + return None + # TODO: transform wandb objects and plots + else: + return SummarySubDict(self, path) + else: + return json_value + + def _encode(self, value, path_from_root): + """Normalize, compress, and encode sub-objects for backend storage. + + value: Object to encode. + path_from_root: `tuple` of key strings from the top-level summary to the + current `value`. + + Returns: + A new tree of dict's with large objects replaced with dictionaries + with "_type" entries that say which type the original data was. + """ + + # Constructs a new `dict` tree in `json_value` that discards and/or + # encodes objects that aren't JSON serializable. + + if isinstance(value, dict): + json_value = {} + for key, value in value.items(): + json_value[key] = self._encode(value, path_from_root + (key,)) + return json_value + else: + path = ".".join(path_from_root) + friendly_value, converted = util.json_friendly( + val_to_json(self._run, path, value, namespace="summary") + ) + json_value, compressed = util.maybe_compress_summary( + friendly_value, util.get_h5_typename(value) + ) + if compressed: + self.write_h5(path_from_root, friendly_value) + + return json_value + + +def download_h5(run_id, entity=None, project=None, out_dir=None): + api = Api() + meta = api.download_url( + project or api.settings("project"), + DEEP_SUMMARY_FNAME, + entity=entity or api.settings("entity"), + run=run_id, + ) + if meta and "md5" in meta and meta["md5"] is not None: + # TODO: make this non-blocking + wandb.termlog("Downloading summary data...") + path, res = api.download_write_file(meta, out_dir=out_dir) + return path + + +def upload_h5(file, run_id, entity=None, project=None): + api = Api() + wandb.termlog("Uploading summary data...") + with open(file, "rb") as f: + api.push( + {os.path.basename(file): f}, run=run_id, project=project, entity=entity + ) + + +class FileSummary(Summary): + def __init__(self, run): + super().__init__(run) + self._fname = os.path.join(run.dir, wandb_lib.filenames.SUMMARY_FNAME) + self.load() + + def load(self): + try: + with open(self._fname) as f: + self._json_dict = json.load(f) + except (OSError, ValueError): + self._json_dict = {} + + def _write(self, commit=False): + # TODO: we just ignore commit to ensure backward capability + with open(self._fname, "w") as f: + f.write(util.json_dumps_safer(self._json_dict)) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + if self._h5: + self._h5.close() + self._h5 = None + if wandb.run and wandb.run._jupyter_agent: + wandb.run._jupyter_agent.start() + + +class HTTPSummary(Summary): + def __init__(self, run, client, summary=None): + super().__init__(run, summary=summary) + self._run = run + self._client = client + self._started = time.time() + + def __delitem__(self, key): + if key not in self._json_dict: + raise KeyError(key) + del self._json_dict[key] + + def load(self): + pass + + def open_h5(self): + if not self._h5 and h5py: + download_h5( + self._run.id, + entity=self._run.entity, + project=self._run.project, + out_dir=self._run.dir, + ) + super().open_h5() + + def _write(self, commit=False): + mutation = gql( + """ + mutation UpsertBucket( $id: String, $summaryMetrics: JSONString) { + upsertBucket(input: { id: $id, summaryMetrics: $summaryMetrics}) { + bucket { id } + } + } + """ + ) + if commit: + if self._h5: + self._h5.close() + self._h5 = None + res = self._client.execute( + mutation, + variable_values={ + "id": self._run.storage_id, + "summaryMetrics": util.json_dumps_safer(self._json_dict), + }, + ) + assert res["upsertBucket"]["bucket"]["id"] + entity, project, run = self._run.path + if ( + os.path.exists(self._h5_path) + and os.path.getmtime(self._h5_path) >= self._started + ): + upload_h5(self._h5_path, run, entity=entity, project=project) + else: + return False diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/__init__.py b/parrot/lib/python3.10/site-packages/wandb/plot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b6220af7cd0395cafbbbe1088120d241f693260 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/plot/__init__.py @@ -0,0 +1,19 @@ +from wandb.plot.bar import bar +from wandb.plot.confusion_matrix import confusion_matrix +from wandb.plot.histogram import histogram +from wandb.plot.line import line +from wandb.plot.line_series import line_series +from wandb.plot.pr_curve import pr_curve +from wandb.plot.roc_curve import roc_curve +from wandb.plot.scatter import scatter + +__all__ = [ + "line", + "histogram", + "scatter", + "bar", + "roc_curve", + "pr_curve", + "confusion_matrix", + "line_series", +] diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/__pycache__/confusion_matrix.cpython-310.pyc b/parrot/lib/python3.10/site-packages/wandb/plot/__pycache__/confusion_matrix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2adab8c46c5a9cead9dfc10b1263844664494cb4 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/wandb/plot/__pycache__/confusion_matrix.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/__pycache__/histogram.cpython-310.pyc b/parrot/lib/python3.10/site-packages/wandb/plot/__pycache__/histogram.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d85e085ee9fe9aaf694bf803034f53427edd3d7c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/wandb/plot/__pycache__/histogram.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/__pycache__/scatter.cpython-310.pyc b/parrot/lib/python3.10/site-packages/wandb/plot/__pycache__/scatter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c415d385110066c33f7909b8cf5a191ee5155bdb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/wandb/plot/__pycache__/scatter.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/bar.py b/parrot/lib/python3.10/site-packages/wandb/plot/bar.py new file mode 100644 index 0000000000000000000000000000000000000000..a78bec2aed357bfe5aef5e3d78f9b77e9a0fd27f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/plot/bar.py @@ -0,0 +1,42 @@ +from typing import Optional + +import wandb + + +def bar( + table: wandb.Table, + label: str, + value: str, + title: Optional[str] = None, + split_table: Optional[bool] = False, +): + """Construct a bar plot. + + Arguments: + table (wandb.Table): Table of data. + label (string): Name of column to use as each bar's label. + value (string): Name of column to use as each bar's value. + title (string): Plot title. + split_table (bool): If True, adds "Custom Chart Tables/" to the key of the table so that it's logged in a different section. + + Returns: + A plot object, to be passed to wandb.log() + + Example: + ``` + table = wandb.Table(data=[ + ['car', random.random()], + ['bus', random.random()], + ['road', random.random()], + ['person', random.random()], + ], columns=["class", "acc"]) + wandb.log({'bar-plot1': wandb.plot.bar(table, "class", "acc")}) + ``` + """ + return wandb.plot_table( + "wandb/bar/v0", + table, + {"label": label, "value": value}, + {"title": title}, + split_table=split_table, + ) diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/confusion_matrix.py b/parrot/lib/python3.10/site-packages/wandb/plot/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..0f44430e560272faba7a6aac532e07ca55eb3fe6 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/plot/confusion_matrix.py @@ -0,0 +1,99 @@ +from typing import Optional, Sequence + +import wandb +from wandb import util + +chart_limit = wandb.Table.MAX_ROWS + + +def confusion_matrix( + probs: Optional[Sequence[Sequence]] = None, + y_true: Optional[Sequence] = None, + preds: Optional[Sequence] = None, + class_names: Optional[Sequence[str]] = None, + title: Optional[str] = None, + split_table: Optional[bool] = False, +): + """Compute a multi-run confusion matrix. + + Arguments: + probs (2-d arr): Shape [n_examples, n_classes] + y_true (arr): Array of label indices. + preds (arr): Array of predicted label indices. + class_names (arr): Array of class names. + split_table (bool): If True, adds "Custom Chart Tables/" to the key of the table so that it's logged in a different section. + + Returns: + Nothing. To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ``` + vals = np.random.uniform(size=(10, 5)) + probs = np.exp(vals)/np.sum(np.exp(vals), keepdims=True, axis=1) + y_true = np.random.randint(0, 5, size=(10)) + labels = ["Cat", "Dog", "Bird", "Fish", "Horse"] + wandb.log({'confusion_matrix': wandb.plot.confusion_matrix(probs, y_true=y_true, class_names=labels)}) + ``` + """ + np = util.get_module( + "numpy", + required="confusion matrix requires the numpy library, install with `pip install numpy`", + ) + # change warning + assert probs is None or len(probs.shape) == 2, ( + "confusion_matrix has been updated to accept" + " probabilities as the default first argument. Use preds=..." + ) + + assert (probs is None or preds is None) and not ( + probs is None and preds is None + ), "Must provide probabilities or predictions but not both to confusion matrix" + + if probs is not None: + preds = np.argmax(probs, axis=1).tolist() + + assert len(preds) == len( + y_true + ), "Number of predictions and label indices must match" + + if class_names is not None: + n_classes = len(class_names) + class_inds = [i for i in range(n_classes)] + assert max(preds) <= len( + class_names + ), "Higher predicted index than number of classes" + assert max(y_true) <= len( + class_names + ), "Higher label class index than number of classes" + else: + class_inds = set(preds).union(set(y_true)) + n_classes = len(class_inds) + class_names = [f"Class_{i}" for i in range(1, n_classes + 1)] + + # get mapping of inds to class index in case user has weird prediction indices + class_mapping = {} + for i, val in enumerate(sorted(list(class_inds))): + class_mapping[val] = i + counts = np.zeros((n_classes, n_classes)) + for i in range(len(preds)): + counts[class_mapping[y_true[i]], class_mapping[preds[i]]] += 1 + + data = [] + for i in range(n_classes): + for j in range(n_classes): + data.append([class_names[i], class_names[j], counts[i, j]]) + + fields = { + "Actual": "Actual", + "Predicted": "Predicted", + "nPredictions": "nPredictions", + } + title = title or "" + return wandb.plot_table( + "wandb/confusion_matrix/v1", + wandb.Table(columns=["Actual", "Predicted", "nPredictions"], data=data), + fields, + {"title": title}, + split_table=split_table, + ) diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/histogram.py b/parrot/lib/python3.10/site-packages/wandb/plot/histogram.py new file mode 100644 index 0000000000000000000000000000000000000000..6e294fd3b41de940812d84ad20c297eb95c08444 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/plot/histogram.py @@ -0,0 +1,36 @@ +from typing import Optional + +import wandb + + +def histogram( + table: wandb.Table, + value: str, + title: Optional[str] = None, + split_table: Optional[bool] = False, +): + """Construct a histogram plot. + + Arguments: + table (wandb.Table): Table of data. + value (string): Name of column to use as data for bucketing. + title (string): Plot title. + split_table (bool): If True, adds "Custom Chart Tables/" to the key of the table so that it's logged in a different section. + + Returns: + A plot object, to be passed to wandb.log() + + Example: + ``` + data = [[i, random.random() + math.sin(i / 10)] for i in range(100)] + table = wandb.Table(data=data, columns=["step", "height"]) + wandb.log({'histogram-plot1': wandb.plot.histogram(table, "height")}) + ``` + """ + return wandb.plot_table( + "wandb/histogram/v0", + table, + {"value": value}, + {"title": title}, + split_table=split_table, + ) diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/line.py b/parrot/lib/python3.10/site-packages/wandb/plot/line.py new file mode 100644 index 0000000000000000000000000000000000000000..4fb8f06bd955afa51d7923b90a154e072ec7008e --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/plot/line.py @@ -0,0 +1,40 @@ +from typing import Optional + +import wandb + + +def line( + table: wandb.Table, + x: str, + y: str, + stroke: Optional[str] = None, + title: Optional[str] = None, + split_table: Optional[bool] = False, +): + """Construct a line plot. + + Arguments: + table (wandb.Table): Table of data. + x (string): Name of column to as for x-axis values. + y (string): Name of column to as for y-axis values. + stroke (string): Name of column to map to the line stroke scale. + title (string): Plot title. + split_table (bool): If True, adds "Custom Chart Tables/" to the key of the table so that it's logged in a different section. + + Returns: + A plot object, to be passed to wandb.log() + + Example: + ``` + data = [[i, random.random() + math.sin(i / 10)] for i in range(100)] + table = wandb.Table(data=data, columns=["step", "height"]) + wandb.log({'line-plot1': wandb.plot.line(table, "step", "height")}) + ``` + """ + return wandb.plot_table( + "wandb/line/v0", + table, + {"x": x, "y": y, "stroke": stroke}, + {"title": title}, + split_table=split_table, + ) diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/pr_curve.py b/parrot/lib/python3.10/site-packages/wandb/plot/pr_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..59f1f436869adcfc47cc576047b819ed94fdc083 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/plot/pr_curve.py @@ -0,0 +1,136 @@ +from typing import Optional + +import wandb +from wandb import util + +from .utils import test_missing, test_types + + +def pr_curve( + y_true=None, + y_probas=None, + labels=None, + classes_to_plot=None, + interp_size=21, + title=None, + split_table: Optional[bool] = False, +): + """Compute the tradeoff between precision and recall for different thresholds. + + A high area under the curve represents both high recall and high precision, where + high precision relates to a low false positive rate, and high recall relates to a + low false negative rate. High scores for both show that the classifier is returning + accurate results (high precision), and returning a majority of all positive results + (high recall). PR curve is useful when the classes are very imbalanced. + + Arguments: + y_true (arr): true sparse labels y_probas (arr): Target scores, can either be + probability estimates, confidence values, or non-thresholded measure of + decisions. shape: (*y_true.shape, num_classes) + labels (list): Named labels for target variable (y). Makes plots easier to read + by replacing target values with corresponding index. For example labels = + ['dog', 'cat', 'owl'] all 0s are replaced by 'dog', 1s by 'cat'. + classes_to_plot (list): unique values of y_true to include in the plot + interp_size (int): the recall values will be fixed to `interp_size` points + uniform on [0, 1] and the precision will be interpolated for these recall + values. + split_table (bool): If True, adds "Custom Chart Tables/" to the key of the table so that it's logged in a different section. + + Returns: + Nothing. To see plots, go to your W&B run page then expand the 'media' tab under + 'auto visualizations'. + + Example: + ``` + wandb.log({"pr-curve": wandb.plot.pr_curve(y_true, y_probas, labels)}) + ``` + """ + np = util.get_module( + "numpy", + required="roc requires the numpy library, install with `pip install numpy`", + ) + pd = util.get_module( + "pandas", + required="roc requires the pandas library, install with `pip install pandas`", + ) + sklearn_metrics = util.get_module( + "sklearn.metrics", + "roc requires the scikit library, install with `pip install scikit-learn`", + ) + sklearn_utils = util.get_module( + "sklearn.utils", + "roc requires the scikit library, install with `pip install scikit-learn`", + ) + + def _step(x): + y = np.array(x) + for i in range(1, len(y)): + y[i] = max(y[i], y[i - 1]) + return y + + y_true = np.array(y_true) + y_probas = np.array(y_probas) + + if not test_missing(y_true=y_true, y_probas=y_probas): + return + if not test_types(y_true=y_true, y_probas=y_probas): + return + + classes = np.unique(y_true) + if classes_to_plot is None: + classes_to_plot = classes + + precision = dict() + interp_recall = np.linspace(0, 1, interp_size)[::-1] + indices_to_plot = np.where(np.isin(classes, classes_to_plot))[0] + for i in indices_to_plot: + if labels is not None and ( + isinstance(classes[i], int) or isinstance(classes[0], np.integer) + ): + class_label = labels[classes[i]] + else: + class_label = classes[i] + + cur_precision, cur_recall, _ = sklearn_metrics.precision_recall_curve( + y_true, y_probas[:, i], pos_label=classes[i] + ) + # smooth the precision (monotonically increasing) + cur_precision = _step(cur_precision) + + # reverse order so that recall in ascending + cur_precision = cur_precision[::-1] + cur_recall = cur_recall[::-1] + indices = np.searchsorted(cur_recall, interp_recall, side="left") + precision[class_label] = cur_precision[indices] + + df = pd.DataFrame( + { + "class": np.hstack([[k] * len(v) for k, v in precision.items()]), + "precision": np.hstack(list(precision.values())), + "recall": np.tile(interp_recall, len(precision)), + } + ) + df = df.round(3) + + if len(df) > wandb.Table.MAX_ROWS: + wandb.termwarn( + "wandb uses only %d data points to create the plots." % wandb.Table.MAX_ROWS + ) + # different sampling could be applied, possibly to ensure endpoints are kept + df = sklearn_utils.resample( + df, + replace=False, + n_samples=wandb.Table.MAX_ROWS, + random_state=42, + stratify=df["class"], + ).sort_values(["precision", "recall", "class"]) + + table = wandb.Table(dataframe=df) + title = title or "Precision v. Recall" + return wandb.plot_table( + "wandb/area-under-curve/v0", + table, + {"x": "recall", "y": "precision", "class": "class"}, + {"title": title}, + split_table=split_table, + ) diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/roc_curve.py b/parrot/lib/python3.10/site-packages/wandb/plot/roc_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..99ca16d66cb8fad39eb05f5ebf617c3ff65926f5 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/plot/roc_curve.py @@ -0,0 +1,118 @@ +from typing import Optional + +import wandb +from wandb import util + +from .utils import test_missing, test_types + + +def roc_curve( + y_true=None, + y_probas=None, + labels=None, + classes_to_plot=None, + title=None, + split_table: Optional[bool] = False, +): + """Calculate and visualize receiver operating characteristic (ROC) scores. + + Arguments: + y_true (arr): true sparse labels + y_probas (arr): Target scores, can either be probability estimates, confidence + values, or non-thresholded measure of decisions. + shape: (*y_true.shape, num_classes) + labels (list): Named labels for target variable (y). Makes plots easier to + read by replacing target values with corresponding index. + For example labels = ['dog', 'cat', 'owl'] all 0s are + replaced by 'dog', 1s by 'cat'. + classes_to_plot (list): unique values of y_true to include in the plot + split_table (bool): If True, adds "Custom Chart Tables/" to the key of the table so that it's logged in a different section. + + Returns: + Nothing. To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ``` + wandb.log({'roc-curve': wandb.plot.roc_curve(y_true, y_probas, labels)}) + ``` + """ + np = util.get_module( + "numpy", + required="roc requires the numpy library, install with `pip install numpy`", + ) + pd = util.get_module( + "pandas", + required="roc requires the pandas library, install with `pip install pandas`", + ) + sklearn_metrics = util.get_module( + "sklearn.metrics", + "roc requires the scikit library, install with `pip install scikit-learn`", + ) + sklearn_utils = util.get_module( + "sklearn.utils", + "roc requires the scikit library, install with `pip install scikit-learn`", + ) + + y_true = np.array(y_true) + y_probas = np.array(y_probas) + + if not test_missing(y_true=y_true, y_probas=y_probas): + return + if not test_types(y_true=y_true, y_probas=y_probas): + return + + classes = np.unique(y_true) + if classes_to_plot is None: + classes_to_plot = classes + + fpr = dict() + tpr = dict() + indices_to_plot = np.where(np.isin(classes, classes_to_plot))[0] + for i in indices_to_plot: + if labels is not None and ( + isinstance(classes[i], int) or isinstance(classes[0], np.integer) + ): + class_label = labels[classes[i]] + else: + class_label = classes[i] + + fpr[class_label], tpr[class_label], _ = sklearn_metrics.roc_curve( + y_true, y_probas[..., i], pos_label=classes[i] + ) + + df = pd.DataFrame( + { + "class": np.hstack([[k] * len(v) for k, v in fpr.items()]), + "fpr": np.hstack(list(fpr.values())), + "tpr": np.hstack(list(tpr.values())), + } + ) + df = df.round(3) + + if len(df) > wandb.Table.MAX_ROWS: + wandb.termwarn( + "wandb uses only %d data points to create the plots." % wandb.Table.MAX_ROWS + ) + # different sampling could be applied, possibly to ensure endpoints are kept + df = sklearn_utils.resample( + df, + replace=False, + n_samples=wandb.Table.MAX_ROWS, + random_state=42, + stratify=df["class"], + ).sort_values(["fpr", "tpr", "class"]) + + table = wandb.Table(dataframe=df) + title = title or "ROC" + return wandb.plot_table( + "wandb/area-under-curve/v0", + table, + {"x": "fpr", "y": "tpr", "class": "class"}, + { + "title": title, + "x-axis-title": "False positive rate", + "y-axis-title": "True positive rate", + }, + split_table=split_table, + ) diff --git a/parrot/lib/python3.10/site-packages/wandb/plot/utils.py b/parrot/lib/python3.10/site-packages/wandb/plot/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b00dc6a97b3a18b3c6ea9a36e5801e62e53a4016 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/plot/utils.py @@ -0,0 +1,183 @@ +from typing import Iterable, Sequence + +import wandb +from wandb import util + + +def test_missing(**kwargs): + np = util.get_module("numpy", required="Logging plots requires numpy") + pd = util.get_module("pandas", required="Logging dataframes requires pandas") + scipy = util.get_module("scipy", required="Logging scipy matrices requires scipy") + + test_passed = True + for k, v in kwargs.items(): + # Missing/empty params/datapoint arrays + if v is None: + wandb.termerror("{} is None. Please try again.".format(k)) + test_passed = False + if (k == "X") or (k == "X_test"): + if isinstance(v, scipy.sparse.csr.csr_matrix): + v = v.toarray() + elif isinstance(v, (pd.DataFrame, pd.Series)): + v = v.to_numpy() + elif isinstance(v, list): + v = np.asarray(v) + + # Warn the user about missing values + missing = 0 + missing = np.count_nonzero(pd.isnull(v)) + if missing > 0: + wandb.termwarn("%s contains %d missing values. " % (k, missing)) + test_passed = False + # Ensure the dataset contains only integers + non_nums = 0 + if v.ndim == 1: + non_nums = sum( + 1 + for val in v + if ( + not isinstance(val, (int, float, complex)) + and not isinstance(val, np.number) + ) + ) + else: + non_nums = sum( + 1 + for sl in v + for val in sl + if ( + not isinstance(val, (int, float, complex)) + and not isinstance(val, np.number) + ) + ) + if non_nums > 0: + wandb.termerror( + f"{k} contains values that are not numbers. Please vectorize, " + f"label encode or one hot encode {k} and call the plotting function again." + ) + test_passed = False + return test_passed + + +def test_fitted(model): + np = util.get_module("numpy", required="Logging plots requires numpy") + _ = util.get_module("pandas", required="Logging dataframes requires pandas") + _ = util.get_module("scipy", required="Logging scipy matrices requires scipy") + scikit_utils = util.get_module( + "sklearn.utils", + required="roc requires the scikit utils submodule, install with `pip install scikit-learn`", + ) + scikit_exceptions = util.get_module( + "sklearn.exceptions", + "roc requires the scikit preprocessing submodule, install with `pip install scikit-learn`", + ) + + try: + model.predict(np.zeros((7, 3))) + except scikit_exceptions.NotFittedError: + wandb.termerror("Please fit the model before passing it in.") + return False + except AttributeError: + # Some clustering models (LDA, PCA, Agglomerative) don't implement ``predict`` + try: + scikit_utils.validation.check_is_fitted( + model, + [ + "coef_", + "estimator_", + "labels_", + "n_clusters_", + "children_", + "components_", + "n_components_", + "n_iter_", + "n_batch_iter_", + "explained_variance_", + "singular_values_", + "mean_", + ], + all_or_any=any, + ) + return True + except scikit_exceptions.NotFittedError: + wandb.termerror("Please fit the model before passing it in.") + return False + except Exception: + # Assume it's fitted, since ``NotFittedError`` wasn't raised + return True + + +def encode_labels(df): + _ = util.get_module("pandas", required="Logging dataframes requires pandas") + preprocessing = util.get_module( + "sklearn.preprocessing", + "roc requires the scikit preprocessing submodule, install with `pip install scikit-learn`", + ) + + le = preprocessing.LabelEncoder() + # apply le on categorical feature columns + categorical_cols = df.select_dtypes( + exclude=["int", "float", "float64", "float32", "int32", "int64"] + ).columns + df[categorical_cols] = df[categorical_cols].apply(lambda col: le.fit_transform(col)) + + +def test_types(**kwargs): + np = util.get_module("numpy", required="Logging plots requires numpy") + pd = util.get_module("pandas", required="Logging dataframes requires pandas") + _ = util.get_module("scipy", required="Logging scipy matrices requires scipy") + + base = util.get_module( + "sklearn.base", + "roc requires the scikit base submodule, install with `pip install scikit-learn`", + ) + + test_passed = True + for k, v in kwargs.items(): + # check for incorrect types + if ( + (k == "X") + or (k == "X_test") + or (k == "y") + or (k == "y_test") + or (k == "y_true") + or (k == "y_probas") + or (k == "x_labels") + or (k == "y_labels") + or (k == "matrix_values") + ): + # FIXME: do this individually + if not isinstance( + v, + ( + Sequence, + Iterable, + np.ndarray, + np.generic, + pd.DataFrame, + pd.Series, + list, + ), + ): + wandb.termerror("{} is not an array. Please try again.".format(k)) + test_passed = False + # check for classifier types + if k == "model": + if (not base.is_classifier(v)) and (not base.is_regressor(v)): + wandb.termerror( + "{} is not a classifier or regressor. Please try again.".format(k) + ) + test_passed = False + elif k == "clf" or k == "binary_clf": + if not (base.is_classifier(v)): + wandb.termerror("{} is not a classifier. Please try again.".format(k)) + test_passed = False + elif k == "regressor": + if not base.is_regressor(v): + wandb.termerror("{} is not a regressor. Please try again.".format(k)) + test_passed = False + elif k == "clusterer": + if not (getattr(v, "_estimator_type", None) == "clusterer"): + wandb.termerror("{} is not a clusterer. Please try again.".format(k)) + test_passed = False + return test_passed diff --git a/parrot/lib/python3.10/site-packages/wandb/proto/__pycache__/wandb_generate_deprecated.cpython-310.pyc b/parrot/lib/python3.10/site-packages/wandb/proto/__pycache__/wandb_generate_deprecated.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8c83d21578ceeeb82adaabb11cecc7a6724ce92 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/wandb/proto/__pycache__/wandb_generate_deprecated.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/wandb/proto/v3/wandb_server_pb2.py b/parrot/lib/python3.10/site-packages/wandb/proto/v3/wandb_server_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed806410041aaa3210c854ad28b830e454ff398 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/proto/v3/wandb_server_pb2.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: wandb/proto/wandb_server.proto +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2 +from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2 +from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ewandb/proto/wandb_server.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\"D\n\x15ServerShutdownRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x18\n\x16ServerShutdownResponse\"B\n\x13ServerStatusRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x16\n\x14ServerStatusResponse\"r\n\x17ServerInformInitRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1a\n\x18ServerInformInitResponse\"s\n\x18ServerInformStartRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1b\n\x19ServerInformStartResponse\"H\n\x19ServerInformFinishRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformFinishResponse\"H\n\x19ServerInformAttachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"u\n\x1aServerInformAttachResponse\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"H\n\x19ServerInformDetachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformDetachResponse\"]\n\x1bServerInformTeardownRequest\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1e\n\x1cServerInformTeardownResponse\"\xa4\x04\n\rServerRequest\x12\x30\n\x0erecord_publish\x18\x01 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12\x34\n\x12record_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12>\n\x0binform_init\x18\x03 \x01(\x0b\x32\'.wandb_internal.ServerInformInitRequestH\x00\x12\x42\n\rinform_finish\x18\x04 \x01(\x0b\x32).wandb_internal.ServerInformFinishRequestH\x00\x12\x42\n\rinform_attach\x18\x05 \x01(\x0b\x32).wandb_internal.ServerInformAttachRequestH\x00\x12\x42\n\rinform_detach\x18\x06 \x01(\x0b\x32).wandb_internal.ServerInformDetachRequestH\x00\x12\x46\n\x0finform_teardown\x18\x07 \x01(\x0b\x32+.wandb_internal.ServerInformTeardownRequestH\x00\x12@\n\x0cinform_start\x18\x08 \x01(\x0b\x32(.wandb_internal.ServerInformStartRequestH\x00\x42\x15\n\x13server_request_type\"\xb0\x04\n\x0eServerResponse\x12\x34\n\x12result_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.ResultH\x00\x12H\n\x14inform_init_response\x18\x03 \x01(\x0b\x32(.wandb_internal.ServerInformInitResponseH\x00\x12L\n\x16inform_finish_response\x18\x04 \x01(\x0b\x32*.wandb_internal.ServerInformFinishResponseH\x00\x12L\n\x16inform_attach_response\x18\x05 \x01(\x0b\x32*.wandb_internal.ServerInformAttachResponseH\x00\x12L\n\x16inform_detach_response\x18\x06 \x01(\x0b\x32*.wandb_internal.ServerInformDetachResponseH\x00\x12P\n\x18inform_teardown_response\x18\x07 \x01(\x0b\x32,.wandb_internal.ServerInformTeardownResponseH\x00\x12J\n\x15inform_start_response\x18\x08 \x01(\x0b\x32).wandb_internal.ServerInformStartResponseH\x00\x42\x16\n\x14server_response_typeB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3') + + + +_SERVERSHUTDOWNREQUEST = DESCRIPTOR.message_types_by_name['ServerShutdownRequest'] +_SERVERSHUTDOWNRESPONSE = DESCRIPTOR.message_types_by_name['ServerShutdownResponse'] +_SERVERSTATUSREQUEST = DESCRIPTOR.message_types_by_name['ServerStatusRequest'] +_SERVERSTATUSRESPONSE = DESCRIPTOR.message_types_by_name['ServerStatusResponse'] +_SERVERINFORMINITREQUEST = DESCRIPTOR.message_types_by_name['ServerInformInitRequest'] +_SERVERINFORMINITRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformInitResponse'] +_SERVERINFORMSTARTREQUEST = DESCRIPTOR.message_types_by_name['ServerInformStartRequest'] +_SERVERINFORMSTARTRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformStartResponse'] +_SERVERINFORMFINISHREQUEST = DESCRIPTOR.message_types_by_name['ServerInformFinishRequest'] +_SERVERINFORMFINISHRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformFinishResponse'] +_SERVERINFORMATTACHREQUEST = DESCRIPTOR.message_types_by_name['ServerInformAttachRequest'] +_SERVERINFORMATTACHRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformAttachResponse'] +_SERVERINFORMDETACHREQUEST = DESCRIPTOR.message_types_by_name['ServerInformDetachRequest'] +_SERVERINFORMDETACHRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformDetachResponse'] +_SERVERINFORMTEARDOWNREQUEST = DESCRIPTOR.message_types_by_name['ServerInformTeardownRequest'] +_SERVERINFORMTEARDOWNRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformTeardownResponse'] +_SERVERREQUEST = DESCRIPTOR.message_types_by_name['ServerRequest'] +_SERVERRESPONSE = DESCRIPTOR.message_types_by_name['ServerResponse'] +ServerShutdownRequest = _reflection.GeneratedProtocolMessageType('ServerShutdownRequest', (_message.Message,), { + 'DESCRIPTOR' : _SERVERSHUTDOWNREQUEST, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerShutdownRequest) + }) +_sym_db.RegisterMessage(ServerShutdownRequest) + +ServerShutdownResponse = _reflection.GeneratedProtocolMessageType('ServerShutdownResponse', (_message.Message,), { + 'DESCRIPTOR' : _SERVERSHUTDOWNRESPONSE, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerShutdownResponse) + }) +_sym_db.RegisterMessage(ServerShutdownResponse) + +ServerStatusRequest = _reflection.GeneratedProtocolMessageType('ServerStatusRequest', (_message.Message,), { + 'DESCRIPTOR' : _SERVERSTATUSREQUEST, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerStatusRequest) + }) +_sym_db.RegisterMessage(ServerStatusRequest) + +ServerStatusResponse = _reflection.GeneratedProtocolMessageType('ServerStatusResponse', (_message.Message,), { + 'DESCRIPTOR' : _SERVERSTATUSRESPONSE, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerStatusResponse) + }) +_sym_db.RegisterMessage(ServerStatusResponse) + +ServerInformInitRequest = _reflection.GeneratedProtocolMessageType('ServerInformInitRequest', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMINITREQUEST, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformInitRequest) + }) +_sym_db.RegisterMessage(ServerInformInitRequest) + +ServerInformInitResponse = _reflection.GeneratedProtocolMessageType('ServerInformInitResponse', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMINITRESPONSE, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformInitResponse) + }) +_sym_db.RegisterMessage(ServerInformInitResponse) + +ServerInformStartRequest = _reflection.GeneratedProtocolMessageType('ServerInformStartRequest', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMSTARTREQUEST, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformStartRequest) + }) +_sym_db.RegisterMessage(ServerInformStartRequest) + +ServerInformStartResponse = _reflection.GeneratedProtocolMessageType('ServerInformStartResponse', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMSTARTRESPONSE, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformStartResponse) + }) +_sym_db.RegisterMessage(ServerInformStartResponse) + +ServerInformFinishRequest = _reflection.GeneratedProtocolMessageType('ServerInformFinishRequest', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMFINISHREQUEST, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformFinishRequest) + }) +_sym_db.RegisterMessage(ServerInformFinishRequest) + +ServerInformFinishResponse = _reflection.GeneratedProtocolMessageType('ServerInformFinishResponse', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMFINISHRESPONSE, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformFinishResponse) + }) +_sym_db.RegisterMessage(ServerInformFinishResponse) + +ServerInformAttachRequest = _reflection.GeneratedProtocolMessageType('ServerInformAttachRequest', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMATTACHREQUEST, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformAttachRequest) + }) +_sym_db.RegisterMessage(ServerInformAttachRequest) + +ServerInformAttachResponse = _reflection.GeneratedProtocolMessageType('ServerInformAttachResponse', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMATTACHRESPONSE, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformAttachResponse) + }) +_sym_db.RegisterMessage(ServerInformAttachResponse) + +ServerInformDetachRequest = _reflection.GeneratedProtocolMessageType('ServerInformDetachRequest', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMDETACHREQUEST, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformDetachRequest) + }) +_sym_db.RegisterMessage(ServerInformDetachRequest) + +ServerInformDetachResponse = _reflection.GeneratedProtocolMessageType('ServerInformDetachResponse', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMDETACHRESPONSE, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformDetachResponse) + }) +_sym_db.RegisterMessage(ServerInformDetachResponse) + +ServerInformTeardownRequest = _reflection.GeneratedProtocolMessageType('ServerInformTeardownRequest', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMTEARDOWNREQUEST, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformTeardownRequest) + }) +_sym_db.RegisterMessage(ServerInformTeardownRequest) + +ServerInformTeardownResponse = _reflection.GeneratedProtocolMessageType('ServerInformTeardownResponse', (_message.Message,), { + 'DESCRIPTOR' : _SERVERINFORMTEARDOWNRESPONSE, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformTeardownResponse) + }) +_sym_db.RegisterMessage(ServerInformTeardownResponse) + +ServerRequest = _reflection.GeneratedProtocolMessageType('ServerRequest', (_message.Message,), { + 'DESCRIPTOR' : _SERVERREQUEST, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerRequest) + }) +_sym_db.RegisterMessage(ServerRequest) + +ServerResponse = _reflection.GeneratedProtocolMessageType('ServerResponse', (_message.Message,), { + 'DESCRIPTOR' : _SERVERRESPONSE, + '__module__' : 'wandb.proto.wandb_server_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ServerResponse) + }) +_sym_db.RegisterMessage(ServerResponse) + +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto' + _SERVERSHUTDOWNREQUEST._serialized_start=148 + _SERVERSHUTDOWNREQUEST._serialized_end=216 + _SERVERSHUTDOWNRESPONSE._serialized_start=218 + _SERVERSHUTDOWNRESPONSE._serialized_end=242 + _SERVERSTATUSREQUEST._serialized_start=244 + _SERVERSTATUSREQUEST._serialized_end=310 + _SERVERSTATUSRESPONSE._serialized_start=312 + _SERVERSTATUSRESPONSE._serialized_end=334 + _SERVERINFORMINITREQUEST._serialized_start=336 + _SERVERINFORMINITREQUEST._serialized_end=450 + _SERVERINFORMINITRESPONSE._serialized_start=452 + _SERVERINFORMINITRESPONSE._serialized_end=478 + _SERVERINFORMSTARTREQUEST._serialized_start=480 + _SERVERINFORMSTARTREQUEST._serialized_end=595 + _SERVERINFORMSTARTRESPONSE._serialized_start=597 + _SERVERINFORMSTARTRESPONSE._serialized_end=624 + _SERVERINFORMFINISHREQUEST._serialized_start=626 + _SERVERINFORMFINISHREQUEST._serialized_end=698 + _SERVERINFORMFINISHRESPONSE._serialized_start=700 + _SERVERINFORMFINISHRESPONSE._serialized_end=728 + _SERVERINFORMATTACHREQUEST._serialized_start=730 + _SERVERINFORMATTACHREQUEST._serialized_end=802 + _SERVERINFORMATTACHRESPONSE._serialized_start=804 + _SERVERINFORMATTACHRESPONSE._serialized_end=921 + _SERVERINFORMDETACHREQUEST._serialized_start=923 + _SERVERINFORMDETACHREQUEST._serialized_end=995 + _SERVERINFORMDETACHRESPONSE._serialized_start=997 + _SERVERINFORMDETACHRESPONSE._serialized_end=1025 + _SERVERINFORMTEARDOWNREQUEST._serialized_start=1027 + _SERVERINFORMTEARDOWNREQUEST._serialized_end=1120 + _SERVERINFORMTEARDOWNRESPONSE._serialized_start=1122 + _SERVERINFORMTEARDOWNRESPONSE._serialized_end=1152 + _SERVERREQUEST._serialized_start=1155 + _SERVERREQUEST._serialized_end=1703 + _SERVERRESPONSE._serialized_start=1706 + _SERVERRESPONSE._serialized_end=2266 +# @@protoc_insertion_point(module_scope) diff --git a/parrot/lib/python3.10/site-packages/wandb/proto/v5/wandb_server_pb2.py b/parrot/lib/python3.10/site-packages/wandb/proto/v5/wandb_server_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..013d9f7916cefd645dc0f201c5974ffc8b057c17 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/wandb/proto/v5/wandb_server_pb2.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: wandb/proto/wandb_server.proto +# Protobuf Python Version: 5.26.1 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2 +from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2 +from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ewandb/proto/wandb_server.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\"D\n\x15ServerShutdownRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x18\n\x16ServerShutdownResponse\"B\n\x13ServerStatusRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x16\n\x14ServerStatusResponse\"r\n\x17ServerInformInitRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1a\n\x18ServerInformInitResponse\"s\n\x18ServerInformStartRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1b\n\x19ServerInformStartResponse\"H\n\x19ServerInformFinishRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformFinishResponse\"H\n\x19ServerInformAttachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"u\n\x1aServerInformAttachResponse\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"H\n\x19ServerInformDetachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformDetachResponse\"]\n\x1bServerInformTeardownRequest\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1e\n\x1cServerInformTeardownResponse\"\xa4\x04\n\rServerRequest\x12\x30\n\x0erecord_publish\x18\x01 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12\x34\n\x12record_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12>\n\x0binform_init\x18\x03 \x01(\x0b\x32\'.wandb_internal.ServerInformInitRequestH\x00\x12\x42\n\rinform_finish\x18\x04 \x01(\x0b\x32).wandb_internal.ServerInformFinishRequestH\x00\x12\x42\n\rinform_attach\x18\x05 \x01(\x0b\x32).wandb_internal.ServerInformAttachRequestH\x00\x12\x42\n\rinform_detach\x18\x06 \x01(\x0b\x32).wandb_internal.ServerInformDetachRequestH\x00\x12\x46\n\x0finform_teardown\x18\x07 \x01(\x0b\x32+.wandb_internal.ServerInformTeardownRequestH\x00\x12@\n\x0cinform_start\x18\x08 \x01(\x0b\x32(.wandb_internal.ServerInformStartRequestH\x00\x42\x15\n\x13server_request_type\"\xb0\x04\n\x0eServerResponse\x12\x34\n\x12result_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.ResultH\x00\x12H\n\x14inform_init_response\x18\x03 \x01(\x0b\x32(.wandb_internal.ServerInformInitResponseH\x00\x12L\n\x16inform_finish_response\x18\x04 \x01(\x0b\x32*.wandb_internal.ServerInformFinishResponseH\x00\x12L\n\x16inform_attach_response\x18\x05 \x01(\x0b\x32*.wandb_internal.ServerInformAttachResponseH\x00\x12L\n\x16inform_detach_response\x18\x06 \x01(\x0b\x32*.wandb_internal.ServerInformDetachResponseH\x00\x12P\n\x18inform_teardown_response\x18\x07 \x01(\x0b\x32,.wandb_internal.ServerInformTeardownResponseH\x00\x12J\n\x15inform_start_response\x18\x08 \x01(\x0b\x32).wandb_internal.ServerInformStartResponseH\x00\x42\x16\n\x14server_response_typeB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_server_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto' + _globals['_SERVERSHUTDOWNREQUEST']._serialized_start=148 + _globals['_SERVERSHUTDOWNREQUEST']._serialized_end=216 + _globals['_SERVERSHUTDOWNRESPONSE']._serialized_start=218 + _globals['_SERVERSHUTDOWNRESPONSE']._serialized_end=242 + _globals['_SERVERSTATUSREQUEST']._serialized_start=244 + _globals['_SERVERSTATUSREQUEST']._serialized_end=310 + _globals['_SERVERSTATUSRESPONSE']._serialized_start=312 + _globals['_SERVERSTATUSRESPONSE']._serialized_end=334 + _globals['_SERVERINFORMINITREQUEST']._serialized_start=336 + _globals['_SERVERINFORMINITREQUEST']._serialized_end=450 + _globals['_SERVERINFORMINITRESPONSE']._serialized_start=452 + _globals['_SERVERINFORMINITRESPONSE']._serialized_end=478 + _globals['_SERVERINFORMSTARTREQUEST']._serialized_start=480 + _globals['_SERVERINFORMSTARTREQUEST']._serialized_end=595 + _globals['_SERVERINFORMSTARTRESPONSE']._serialized_start=597 + _globals['_SERVERINFORMSTARTRESPONSE']._serialized_end=624 + _globals['_SERVERINFORMFINISHREQUEST']._serialized_start=626 + _globals['_SERVERINFORMFINISHREQUEST']._serialized_end=698 + _globals['_SERVERINFORMFINISHRESPONSE']._serialized_start=700 + _globals['_SERVERINFORMFINISHRESPONSE']._serialized_end=728 + _globals['_SERVERINFORMATTACHREQUEST']._serialized_start=730 + _globals['_SERVERINFORMATTACHREQUEST']._serialized_end=802 + _globals['_SERVERINFORMATTACHRESPONSE']._serialized_start=804 + _globals['_SERVERINFORMATTACHRESPONSE']._serialized_end=921 + _globals['_SERVERINFORMDETACHREQUEST']._serialized_start=923 + _globals['_SERVERINFORMDETACHREQUEST']._serialized_end=995 + _globals['_SERVERINFORMDETACHRESPONSE']._serialized_start=997 + _globals['_SERVERINFORMDETACHRESPONSE']._serialized_end=1025 + _globals['_SERVERINFORMTEARDOWNREQUEST']._serialized_start=1027 + _globals['_SERVERINFORMTEARDOWNREQUEST']._serialized_end=1120 + _globals['_SERVERINFORMTEARDOWNRESPONSE']._serialized_start=1122 + _globals['_SERVERINFORMTEARDOWNRESPONSE']._serialized_end=1152 + _globals['_SERVERREQUEST']._serialized_start=1155 + _globals['_SERVERREQUEST']._serialized_end=1703 + _globals['_SERVERRESPONSE']._serialized_start=1706 + _globals['_SERVERRESPONSE']._serialized_end=2266 +# @@protoc_insertion_point(module_scope)