"""Command-line interface built with typed-argument-parser. See DESIGN.md, "CLI"."""
from __future__ import annotations
import functools
import inspect
import json
import os
import sys
import warnings
from argparse import SUPPRESS, Action, ArgumentParser, ArgumentTypeError
from collections.abc import Callable
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, NoReturn, TypedDict
from pydantic import BaseModel, TypeAdapter
from tap import Positional, Tap
from jabara import _codec_list, _config, _help, _man
from jabara.assign import Assigner
from jabara.bench import BenchReport, BenchRow, candidates_for, compare
from jabara.codecs import codec_ids
from jabara.container import Archive, ArchiveInfo, TensorStats
from jabara.errors import JabaraError, RolesUnknownWarning
from jabara.files import (
SUFFIX,
ParentScan,
check_source,
checkpoint_dirs,
checkpoint_files,
compress_dir,
compress_file,
decompress_dir,
decompress_file,
export_weights,
load_records,
missing_base,
open_bases,
refuse_to_orphan,
)
from jabara.formats import directory_patterns
if TYPE_CHECKING:
from typing_extensions import Self, Unpack
class _HelpOptions(TypedDict):
"""What `add_argument` hands `_HelpSpelling` besides the option strings and dest."""
help: str
[ドキュメント]
class Listing(BaseModel, frozen=True, extra="forbid"):
"""One archive and the stats of its tensors. `jabara ls --json` prints a list of these."""
#: The path of the archive.
path: str
#: The stats of each tensor.
tensors: list[TensorStats]
def _one_line(message: object) -> str:
return " ".join(str(message).split())
def _guard(fn: Callable[..., None]) -> Callable[..., None]:
@functools.wraps(fn)
def run(*args: object, **kwargs: object) -> None:
try:
with warnings.catch_warnings():
warnings.simplefilter("always", RolesUnknownWarning)
shown = warnings.showwarning
def show(message: Warning | str, category: type[Warning], *rest: Any, **kw: Any) -> None: # noqa: ANN401 - warnings.showwarning's own signature
if issubclass(category, RolesUnknownWarning):
print(f"jabara: {_one_line(message)}", file=sys.stderr, flush=True)
else:
shown(message, category, *rest, **kw)
warnings.showwarning = show
fn(*args, **kwargs)
except (JabaraError, OSError, ValueError) as e:
print(f"jabara: {_one_line(e)}", file=sys.stderr)
raise SystemExit(1) from None
return run
def _count(n: int, noun: str) -> str:
return f"{n} {noun}{'' if n == 1 else 's'}"
def _archives_in(directory: Path) -> list[Path]:
return sorted(f for f in directory.glob(f"*{SUFFIX}") if f.is_file())
def _recursive_hint(directory: Path) -> str:
"""For a directory that holds nothing of its own to work on: the checkpoint directories it holds, if any."""
try:
found = [d for d in checkpoint_dirs(directory) if d != directory]
except OSError:
return ""
if not found:
return ""
names = ", ".join(d.name for d in found[:3]) + (", ..." if len(found) > 3 else "") # noqa: PLR2004 - how many to name
what = "1 checkpoint directory" if len(found) == 1 else f"{len(found)} checkpoint directories"
return f"; it holds {what} ({names}), pass --recursive to take them all"
def _archives(path: str | os.PathLike[str]) -> list[Path]:
p = Path(path)
if p.is_dir():
found = _archives_in(p)
if not found:
raise FileNotFoundError(f"{p}: no *{SUFFIX} archives in this directory{_recursive_hint(p)}")
return found
if not p.exists():
raise FileNotFoundError(f"{p}: no such file or directory")
return [p]
def _parent_dirs(path: str | os.PathLike[str]) -> list[Path]:
"""The checkpoint directories of the parent `path` (see `checkpoint_dirs`); at least one."""
dirs = checkpoint_dirs(path)
if not dirs:
raise ValueError(
f"{path}: no checkpoint directories (holding {', '.join(directory_patterns())}, or *{SUFFIX}) in it"
)
return dirs
def _sizes(raw: int, stored: int) -> str:
"""`<raw> -> <stored> bytes (<stored/raw as a percentage> of original)`, the measure the paper reports."""
share = f"{100 * stored / raw:.1f}% of original" if raw else "empty"
return f"{raw} -> {stored} bytes ({share})"
def _report(info: ArchiveInfo) -> None:
print(f"{info.path}: {_sizes(info.raw_bytes, info.stored_bytes)}")
def _refuse_pairs(pairs: list[tuple[Path, Path]]) -> None:
"""Each pair is (checkpoint file, its archive). A file next to its archive is ambiguous: `compress` would
overwrite the archive and `decompress` would overwrite the file, so name it before changing anything."""
for original, archive in pairs:
if original.exists() and archive.exists():
raise ValueError(f"{original.parent}: holds both {original.name} and {archive.name}; remove one")
def _compress_targets(path: Path) -> list[Path]:
if path.is_dir():
return checkpoint_files(path)
return [path]
def _walk(dirs: list[Path], work: Callable[[Path], tuple[int, int, int] | None], skip: str) -> None:
"""Run `work` on each checkpoint directory in turn and stop at the first failure. `work` prints its own lines and
returns the number of archives with their raw and stored bytes, or None for a directory with nothing to do."""
raw = stored = skipped = 0
for i, d in enumerate(dirs):
try:
done = work(d)
except (JabaraError, OSError, ValueError) as e:
raise ValueError(
f"{d}: {_one_line(e)}; stopped there: {_count(i, 'checkpoint')} done or skipped before it, "
f"this one and {len(dirs) - i - 1} after it left as they were"
) from e
if done is None:
print(f"{d}: skipped, {skip}", flush=True)
skipped += 1
continue
n, r, s = done
print(f"{d}: {_count(n, 'archive')}, {_sizes(r, s)}", flush=True)
raw, stored = raw + r, stored + s
print(f"total: {_count(len(dirs), 'checkpoint')}, {skipped} skipped, {_sizes(raw, stored)}")
class PathArg(str):
"""A path on the command line. An empty one is refused, and so is one that starts with "-"; argparse decides by
Python version whether a token like -1e3 is a value or a flag, so refusing a leading "-" in every value makes
such a token a usage error on every version."""
#: How the help names the values it takes.
label = "path"
def __new__(cls, text: str) -> Self:
if not text:
raise ArgumentTypeError("an empty path is not accepted")
if text.startswith("-"):
raise ArgumentTypeError(f"{text!r} starts with '-'; write the path as ./{text}")
return super().__new__(cls, text)
class PositiveInt(int):
"""A positive integer, written in ASCII digits on the command line. It also takes an `int`, which is how a default
of this type is built and how `copy.deepcopy` (which Tap applies to each default) rebuilds it."""
label = "positive integer"
def __new__(cls, value: str | int) -> Self:
text = str(value)
if not (text.isascii() and text.isdigit()) or int(text) < 1:
raise ArgumentTypeError(f"must be a positive integer, got {text!r}")
return super().__new__(cls, text)
class CodecList(list[str]):
"""Codec ids, comma-separated."""
label = "codec ids, comma-separated"
def __init__(self, text: str) -> None:
if text.startswith("-"):
raise ArgumentTypeError(f"{text!r} starts with '-'")
super().__init__(text.split(","))
class _HelpSpelling(Action):
"""`main` answers -h, -H and --help before parsing, so argparse reaches this only for another spelling (-hx, -hh,
-Hh, --help=x), which argparse would otherwise treat differently across Python versions."""
def __init__(
self,
option_strings: list[str],
dest: str, # noqa: ARG002 - argparse.Action's signature
**kwargs: Unpack[_HelpOptions],
) -> None:
super().__init__(option_strings, dest=SUPPRESS, default=SUPPRESS, nargs=0, **kwargs)
def __call__(self, parser: ArgumentParser, *_: object) -> NoReturn:
parser.error("write -h, -H or --help on its own")
class _Parser(Tap):
"""The parser settings every command shares. The help text of each argument is written in `arguments`, not as a
comment on the attribute: Tap reads those comments from the class's source, and without the source (a .pyc-only
install) it would drop them without a word.
No Tap feature that reads on its own is reachable: there are no `config_files`, `fromfile_prefix_chars` stays
unset, and `main` always hands `parse_args` a list, so `sys.argv` is never read.
"""
# Tap builds its subparsers from this class with Tap.__init__'s own keyword arguments, so every one passes through.
def __init__(self, **kwargs: Any) -> None: # noqa: ANN401 - forwarded to Tap.__init__, which types them
kwargs.setdefault("underscores_to_dashes", True) # Tap hands it on to the subparsers it builds
super().__init__(allow_abbrev=False, add_help=False, **kwargs)
def configure(self) -> None:
ArgumentParser.add_argument(
self, "-h", "-H", "--help", action=_HelpSpelling, help="print the short (-h) or the full help and exit"
)
self.arguments()
def arguments(self) -> None:
"""Describe the arguments declared as attributes: their help text and metavar."""
def switch(self, name: str, text: str) -> None:
"""`--name`, `--name=true` and `--name=false` for the bool attribute `name` (`dry-run` for `dry_run`)."""
dest = name.replace("-", "_")
self.add_argument(f"--{name}", help=f"{text} (also --{name}=true or --{name}=false)")
# argparse matches a whole token against the option strings before it splits at "=", so these two spellings
# are the only values the switch takes; any other --name=VALUE is "ignored explicit argument", exit 2.
ArgumentParser.add_argument(self, f"--{name}=true", dest=dest, action="store_true", help=SUPPRESS)
ArgumentParser.add_argument(
self, f"--{name}=false", dest=dest, action="store_false", default=False, help=SUPPRESS
)
class _Command(_Parser):
def run(self) -> None:
raise NotImplementedError
#: The destinations of `_Configured` that are not keys of a configuration file.
_NOT_KEYS = frozenset({"config", "show_config"})
class _Configured(_Command):
"""A command whose options can also come from a file (see `_config`)."""
# Declared for the type checker only. Tap orders the attributes of a class by reading its source, which a .pyc-only
# install lacks, and then lists those of a base class first; `configure` adds both after the others instead.
if TYPE_CHECKING:
config: PathArg | None
show_config: bool
def configure(self) -> None:
super().configure()
self.add_argument(
"--config",
type=PathArg,
metavar="FILE",
default=None,
help="read options from a .json, .yaml, .yml, or .toml file",
)
self.add_argument(
"--show-config",
action="store_true",
default=False,
help="print the settings to be used, as JSON, and exit",
)
ArgumentParser.add_argument(self, "--show-config=true", dest="show_config", action="store_true", help=SUPPRESS)
ArgumentParser.add_argument(
self, "--show-config=false", dest="show_config", action="store_false", default=False, help=SUPPRESS
)
class _Archives(_Configured):
"""What the commands that work on the archives of a PATH share. Each declares its own attributes, in the order of
its `arguments`: Tap lists inherited ones in another order when it cannot read the source."""
if TYPE_CHECKING:
recursive: bool
base: PathArg | None
def process_args(self) -> None:
if self.recursive and self.base is not None:
self.error(
"--recursive finds the base archives among the checkpoints itself; do not combine it with --base"
)
class Compress(_Archives):
"""Compress a checkpoint file, or the files it recognises in a checkpoint directory.
With --base BASE (an archive of an earlier checkpoint, or the directory of one), float tensors are stored as
differences from the tensors of the same name in it. With --recursive, PATH holds several checkpoint directories
(checkpoint-100, checkpoint-200, ...): each is compressed in turn as a directory is, the first failure stops the
run, --delta first codes every checkpoint but the first against the first, and --delta previous codes each
against the one before it, a chain that restores in order. --dry-run lists what would be compressed and changes
nothing.
"""
path: Positional[PathArg]
threads: PositiveInt | None = None
base: PathArg | None = None
recursive: bool = False
keep: bool = False
dry_run: bool = False
delta: Literal["first", "previous"] | None = None
def arguments(self) -> None:
self.add_argument(
"path", metavar="PATH", help="a file, a checkpoint directory, or with --recursive their parent"
)
self.add_argument("--threads", metavar="N", help="worker threads (default: up to 8)")
self.add_argument("--base", metavar="BASE", help="an archive of an earlier checkpoint, or its directory")
self.switch("recursive", "take every checkpoint directory in PATH, one level down")
self.switch("keep", "keep the input files")
self.switch("dry-run", "print what would be compressed, with its size on disk, and change nothing")
self.add_argument(
"--delta",
metavar="MODE",
help="with --recursive: first or previous, the checkpoint each one is coded against",
)
def process_args(self) -> None:
if self.delta is not None and not self.recursive:
self.error(
"--delta needs --recursive: it codes the checkpoints of a parent directory against the first or the previous one"
)
if self.delta is not None and self.base is not None:
self.error(f"--delta {self.delta} chooses the base itself; do not combine it with --base")
super().process_args()
@_guard
def run(self) -> None:
p = Path(self.path)
if self.recursive:
self._compress_parent(p)
return
targets = _compress_targets(p)
if p.is_dir() and not targets:
raise ValueError(
f"{p}: no checkpoint files to compress ({', '.join(directory_patterns())}){_recursive_hint(p)}"
)
_refuse_pairs([(t, t.with_name(t.name + SUFFIX)) for t in targets])
if self.dry_run:
if not p.is_dir():
check_source(p)
with open_bases(self.base, to_write=True): # as a real run opens it: refuses an unusable base
pass
sizes = [t.stat().st_size for t in targets]
for t, n in zip(targets, sizes, strict=True):
print(f"{t}: would compress, {n} bytes on disk")
print(f"total: {_count(len(targets), 'file')}, {sum(sizes)} bytes on disk")
return
infos = (
compress_dir(p, keep=self.keep, threads=self.threads, base=self.base)
if p.is_dir()
else [compress_file(p, keep=self.keep, threads=self.threads, base=self.base)]
)
for info in infos:
_report(info)
def _compress_parent(self, root: Path) -> None:
dirs = _parent_dirs(root)
targets = {d: _compress_targets(d) for d in dirs}
_refuse_pairs([(t, t.with_name(t.name + SUFFIX)) for found in targets.values() for t in found])
first = dirs[0] if self.delta is not None else None
if first is not None:
for a in _archives_in(first):
with Archive.open(a) as archive:
if archive.index.base_refs():
raise ValueError(
f"{a}: is a delta archive; the first checkpoint is the base of the others, so it must hold full archives"
)
def base_of(d: Path) -> Path | None:
if self.delta is None or d == first:
return None
return first if self.delta == "first" else dirs[dirs.index(d) - 1]
if self.dry_run:
self._plan_parent(dirs, targets, base_of)
return
def work(d: Path) -> tuple[int, int, int] | None:
if not targets[d]:
return None
infos = compress_dir(d, keep=self.keep, threads=self.threads, base=base_of(d))
for info in infos:
_report(info)
return len(infos), sum(i.raw_bytes for i in infos), sum(i.stored_bytes for i in infos)
_walk(dirs, work, "already compressed")
@staticmethod
def _plan_parent(
dirs: list[Path], targets: dict[Path, list[Path]], base_of: Callable[[Path], Path | None]
) -> None:
skipped = files = size = 0
for d in dirs:
if not targets[d]:
print(f"{d}: skipped, already compressed")
skipped += 1
continue
sizes = [t.stat().st_size for t in targets[d]]
for t, n in zip(targets[d], sizes, strict=True):
print(f"{t}: would compress, {n} bytes on disk")
against = f", delta against {base}" if (base := base_of(d)) is not None else ""
print(f"{d}: {_count(len(sizes), 'file')}, {sum(sizes)} bytes on disk{against}")
files, size = files + len(sizes), size + sum(sizes)
print(
f"total: {_count(len(dirs), 'checkpoint')}, {skipped} skipped, {_count(files, 'file')}, {size} bytes on disk"
)
class Decompress(_Archives):
"""Restore the original file from an archive, or every archive in a directory.
An archive written with --base needs the same --base BASE here. With --recursive, PATH holds several checkpoint
directories: each is restored in turn as a directory is, dependants of another checkpoint's archives first, and
the first failure stops the run. Without --keep, a checkpoint whose archives a sibling checkpoint still needs as
its base is not restored before that sibling.
"""
path: Positional[PathArg]
threads: PositiveInt | None = None
base: PathArg | None = None
recursive: bool = False
keep: bool = False
def arguments(self) -> None:
self.add_argument(
"path", metavar="PATH", help="an archive, a checkpoint directory, or with --recursive their parent"
)
self.add_argument("--threads", metavar="N", help="worker threads (default: up to 8)")
self.add_argument("--base", metavar="BASE", help="an archive of an earlier checkpoint, or its directory")
self.switch("recursive", "take every checkpoint directory in PATH, one level down")
self.switch("keep", "keep the input files")
@_guard
def run(self) -> None:
p = Path(self.path)
if self.recursive:
self._decompress_parent(p)
return
if p.is_dir():
archives = _archives(p)
_refuse_pairs([(a.with_suffix(""), a) for a in archives])
if not self.keep:
refuse_to_orphan(p, archives)
outs = decompress_dir(p, keep=self.keep, threads=self.threads, base=self.base)
else:
if not self.keep and p.suffix == SUFFIX:
refuse_to_orphan(p.parent, [p])
outs = [decompress_file(p, keep=self.keep, threads=self.threads, base=self.base)]
for out in outs:
print(out)
def _decompress_parent(self, root: Path) -> None:
dirs = _parent_dirs(root)
scan = ParentScan(dirs)
_refuse_pairs([(a.with_suffix(""), a) for d in dirs for a in scan.archives(d)])
if not self.keep and root in dirs: # the order protects the checkpoints inside PATH, not what sits beside it
refuse_to_orphan(root, scan.archives(root))
try:
bases = {d: scan.bases(d) for d in dirs}
except ValueError as e:
raise ValueError(f"{e}; nothing was restored") from e
def work(d: Path) -> tuple[int, int, int] | None:
archives = scan.archives(d)
if not archives:
return None
raw, stored = scan.sizes(d)
for out in decompress_dir(d, keep=self.keep, threads=self.threads, base=bases[d]):
print(out)
return len(archives), raw, stored
# Restoring deletes archives, so a directory goes before any directory that holds the bases it needs.
_walk(scan.restore_order(), work, "already decompressed")
class Ls(_Configured):
"""List the tensors of an archive, or of every archive in a directory. A directory without one is an error.
With --recursive, PATH holds several checkpoint directories, and the archives of each are listed.
"""
path: Positional[PathArg]
json: bool = False
recursive: bool = False
def arguments(self) -> None:
self.add_argument("path", metavar="PATH", help="an archive or a directory, or with --recursive their parent")
self.switch("json", "print JSON")
self.switch("recursive", "take every checkpoint directory in PATH, one level down")
@_guard
def run(self) -> None:
listings = []
for p in _all_archives(self.path, recursive=self.recursive):
with Archive.open(p) as archive:
listings.append(Listing(path=str(p), tensors=archive.stats()))
if self.json:
print(TypeAdapter(list[Listing]).dump_json(listings, indent=2).decode())
return
for item in listings:
raw = sum(t.raw_bytes for t in item.tensors)
stored = sum(t.stored_bytes for t in item.tensors)
print(f"{item.path}: {len(item.tensors)} tensors, {_sizes(raw, stored)}")
for t in item.tensors:
print(
f" {t.meta.name} {t.meta.dtype} {list(t.meta.shape)} {t.meta.role} {t.codec} "
f"{_sizes(t.raw_bytes, t.stored_bytes)}"
)
def _all_archives(path: str | os.PathLike[str], *, recursive: bool) -> list[Path]:
if not recursive:
return _archives(path)
found = [a for d in _parent_dirs(path) for a in _archives_in(d)]
if not found:
raise FileNotFoundError(f"{path}: no *{SUFFIX} archives in its checkpoint directories")
return found
class Verify(_Archives):
"""Decode every chunk of an archive, or of every archive in a directory, and check its checksum.
A directory without an archive is an error. A delta archive needs --base BASE, as for decompress. With
--recursive, PATH holds several checkpoint directories: every archive of each is checked, a delta archive against
the archives of the other checkpoints that it names, and a failure does not stop the others.
"""
path: Positional[PathArg]
threads: PositiveInt | None = None
base: PathArg | None = None
recursive: bool = False
def arguments(self) -> None:
self.add_argument("path", metavar="PATH", help="an archive or a directory, or with --recursive their parent")
self.add_argument("--threads", metavar="N", help="worker threads (default: up to 8)")
self.add_argument("--base", metavar="BASE", help="the base archive of a delta archive, or its directory")
self.switch("recursive", "take every checkpoint directory in PATH, one level down")
@_guard
def run(self) -> None:
if self.recursive:
self._verify_parent(Path(self.path))
return
archives = _archives(self.path)
with open_bases(self.base) as bases:
for p in archives:
with Archive.open(p, base=bases) as archive:
archive.verify(threads=self.threads)
print(f"ok {p}")
def _verify_in(self, scan: ParentScan, archive: Path) -> None:
_, missing = scan.chain(archive)
if missing:
owner, ref = missing
raise ValueError(missing_base(ref) if owner == archive else f"{owner}: {missing_base(ref)}")
with open_bases(scan.resolve(archive)[0]) as bases, Archive.open(archive, base=bases) as opened:
opened.verify(threads=self.threads)
def _verify_parent(self, root: Path) -> None:
scan = ParentScan(_parent_dirs(root))
checked = failed = 0
for a in (a for d in scan.dirs for a in scan.archives(d)):
checked += 1
try:
self._verify_in(scan, a)
except (JabaraError, OSError, ValueError) as e:
print(f"FAILED {a}: {_one_line(e).removeprefix(f'{a}: ')}")
failed += 1
else:
print(f"ok {a}")
if not checked:
raise FileNotFoundError(f"{root}: no *{SUFFIX} archives in its checkpoint directories")
if failed:
raise ValueError(f"{failed} of {checked} archives failed")
class ExportWeights(_Configured):
"""Write the weight tensors of ARCHIVE as a safetensors file."""
archive: Positional[PathArg]
out: Positional[PathArg]
def arguments(self) -> None:
self.add_argument("archive", metavar="ARCHIVE", help="")
self.add_argument("out", metavar="OUT", help="the safetensors file to write; must not exist")
@_guard
def run(self) -> None:
if Path(self.out).exists():
if Path(self.archive).exists() and Path(self.archive).samefile(self.out):
raise ValueError(f"{self.out}: is the archive itself")
raise FileExistsError(f"{self.out}: already exists")
export_weights(self.archive, self.out)
def _candidates(names: list[str] | None, *, with_base: bool) -> dict[str, Assigner]:
"""`candidates_for`, with each skipped-codec warning printed as a `jabara:` line on stderr."""
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
found = candidates_for(names, with_base=with_base)
for w in caught:
if issubclass(w.category, UserWarning) and str(w.message).startswith("candidates_for skipped "):
print(f"jabara: {_one_line(w.message).removeprefix('candidates_for ')}", file=sys.stderr)
else:
warnings.warn_explicit(w.message, w.category, w.filename, w.lineno)
return found
class Bench(_Configured):
"""Compare codecs in memory on the tensors of PATH: an archive, a safetensors or torch file, or a directory.
Default candidates are the lossless codecs that need no base; with --base (a path of the same kinds) the
delta codecs join them. --candidates a,b,c names codecs instead, lossy ones included. It takes no --recursive:
it holds every tensor in memory, and a parent of several checkpoints would multiply that.
"""
path: Positional[PathArg]
json: bool = False
base: PathArg | None = None
repeats: PositiveInt = PositiveInt(3)
threads: PositiveInt | None = None
candidates: CodecList | None = None
def arguments(self) -> None:
self.add_argument("path", metavar="PATH", help="an archive, a safetensors or torch file, or a directory")
self.switch("json", "print the report as JSON")
self.add_argument("--base", metavar="BASE", help="the base tensors, a path of the same kinds")
self.add_argument("--repeats", metavar="N", help="timed runs per codec")
self.add_argument("--threads", metavar="N", help="worker threads (default: up to 8)")
self.add_argument("--candidates", metavar="a,b,c", help="the codecs to compare instead of the default ones")
@_guard
def run(self) -> None:
report = compare(
load_records(self.path, threads=self.threads),
_candidates(self.candidates, with_base=self.base is not None),
base=load_records(self.base, threads=self.threads) if self.base is not None else None,
threads=self.threads,
repeats=self.repeats,
)
if self.json:
print(report.model_dump_json())
return
_print_bench(report)
# From this rate up, whole MB/s; below it, two significant digits.
_WHOLE_MB_S = 10
def _rate(nbytes: int, seconds: float) -> str:
mb_s = nbytes / seconds / 1e6
return f"{mb_s:.0f} MB/s" if mb_s >= _WHOLE_MB_S else f"{mb_s:.2g} MB/s"
def _row_line(r: BenchRow) -> str:
enc = _rate(r.raw_bytes, r.encode_seconds) if r.encode_seconds else "encode time 0"
if r.decode_error is not None:
dec = f"decode failed ({_one_line(r.decode_error)})"
elif r.decode_seconds:
dec = f"decode {_rate(r.raw_bytes, r.decode_seconds)}"
else:
dec = "decode time 0"
err = "" if r.max_abs_err is None or r.lossless else f" max_abs_err={r.max_abs_err:g}"
n = r.fallback_tensors
fallback = f", {n} tensor{'' if n == 1 else 's'} used the fallback" if n else ""
return (
f"{r.candidate} {r.role}: {_sizes(r.raw_bytes, r.stored_bytes)}, encode {enc}, {dec}, "
f"{'exact' if r.bit_exact else 'NOT EXACT'}{err}{fallback}"
)
def _print_bench(report: BenchReport) -> None:
env = report.environment
print(f"{env.threads} threads, best of {env.repeats}, {env.warmup_passes} warm-up, chunk {env.chunk_size} bytes")
for r in report.rows:
print(_row_line(r))
class Codecs(_Configured):
"""List the registered codecs: their ids, or with --long, --json or an ID what each is and builds on."""
codec: Positional[str | None] = None
long: bool = False
json: bool = False
def arguments(self) -> None:
self.add_argument("codec", metavar="ID", nargs="?", help="show everything about this codec")
self.switch("long", "show each codec's properties and references")
self.switch("json", "print JSON: a list of codecs, or one codec for an ID")
@_guard
def run(self) -> None:
if self.codec is not None:
one = _codec_list.entry(self.codec)
_help.emit(one.model_dump_json(indent=2) + "\n" if self.json else _codec_list.show_text(one))
elif self.json:
listing = TypeAdapter(list[_codec_list.CodecEntry]).dump_json(_codec_list.entries(), indent=2)
_help.emit(listing.decode() + "\n")
elif self.long:
_help.emit(_codec_list.long_text(_codec_list.entries()))
else:
print("\n".join(codec_ids()))
class _CommandName(str):
"""A command of `jabara`, the argument of `help` and `man`."""
label = "command name"
def __new__(cls, text: str) -> Self:
if text not in COMMANDS:
raise ArgumentTypeError(f"no command {text!r}; the commands are {', '.join(COMMANDS)}")
return super().__new__(cls, text)
class Help(_Command):
"""Print the full help of jabara or of a command."""
command: Positional[_CommandName | None] = None
def arguments(self) -> None:
self.add_argument("command", metavar="COMMAND", nargs="?", help="a command; jabara itself without it")
def run(self) -> None:
_help.emit(_help.full_text(_page(self.command)))
class Man(Help):
"""Show the manual page of jabara or of a command."""
@_guard
def run(self) -> None:
_man.show(_page(self.command))
COMMANDS: dict[str, type[_Command]] = {
"compress": Compress,
"decompress": Decompress,
"ls": Ls,
"verify": Verify,
"export-weights": ExportWeights,
"bench": Bench,
"codecs": Codecs,
"help": Help,
"man": Man,
}
class Overview(_Parser):
"""Compress and restore training checkpoints."""
# Only its help and its refusal of a first argument that is no command are used: Tap's subparsers fill one
# namespace with the arguments of every command, so `main` parses with the command's own class instead.
def arguments(self) -> None:
self.add_subparsers(dest="command", required=True, metavar="COMMAND")
for name, command in COMMANDS.items():
self.add_subparser(name, command, help=(inspect.getdoc(command) or "").split("\n")[0])
def _parsers() -> tuple[Overview, dict[str, _Command]]:
return Overview(prog="jabara"), {name: command(prog=f"jabara {name}") for name, command in COMMANDS.items()}
def _page(name: str | None, parser: _Parser | None = None) -> _help.Page:
"""The help page of the command `name`, or of `jabara` for None, from `parser` if it is already built."""
if name is None:
docs = {n: inspect.getdoc(c) or "" for n, c in COMMANDS.items()}
return _help.overview_page(parser or Overview(prog="jabara"), docs)
return _help.command_page(name, parser or COMMANDS[name](prog=f"jabara {name}"))
[ドキュメント]
def main(argv: list[str] | None = None) -> None:
"""Run the `jabara` command with `argv`, or with `sys.argv` when `argv` is None.
The whole argument list is parsed and checked before a command runs, so a usage error (exit 2) or a help
request (exit 0) changes nothing. A `JabaraError`, `OSError`, or `ValueError` from a command prints one line to
standard error and exits with status 1.
"""
argv = sys.argv[1:] if argv is None else argv
if not argv:
# A usage error (status 2): the short help goes to stderr, where usage errors go.
print(_help.short_text(_page(None)), end="", file=sys.stderr)
raise SystemExit(2)
command = COMMANDS.get(argv[0])
parser: _Parser = Overview(prog="jabara") if command is None else command(prog=f"jabara {argv[0]}")
# Looked for before parsing: argparse would report an error in an earlier argument instead of the help.
if "-H" in argv or "--help" in argv or "-h" in argv:
page = _page(argv[0] if command is not None else None, parser)
full = "-H" in argv or "--help" in argv
_help.emit(_help.full_text(page) if full else _help.short_text(page))
raise SystemExit(0)
# argparse reads "--" differently across Python versions and positions (on 3.10 `export-weights a -- --` binds
# OUT to an empty list; `-- compress ckpt` runs on 3.13 and is refused on 3.10), so no "--" reaches it.
if "--" in argv:
parser.error("'--' is not accepted; write a path that starts with '-' as ./-name")
if not isinstance(parser, _Command):
parser.parse_args(argv) # exits with status 2: the first argument is no command
raise SystemExit(2)
args = argv[1:]
if isinstance(parser, _Configured):
try:
args = _config.merge(parser, args, option="config", skip=_NOT_KEYS)
except _config.ConfigError as e:
print(f"jabara: {_one_line(e)}", file=sys.stderr)
raise SystemExit(2) from None
except (JabaraError, OSError) as e:
print(f"jabara: {_one_line(e)}", file=sys.stderr)
raise SystemExit(1) from None
parsed = parser.parse_args(args)
if isinstance(parsed, _Configured) and parsed.show_config:
settings = {d: getattr(parsed, d) for d in _config.keys(parsed, _NOT_KEYS)}
print(json.dumps({"command": argv[0], "config": parsed.config, "settings": settings}, indent=2))
return
parsed.run()