diff --git a/dlccore/project/__main__.py b/dlccore/project/__main__.py new file mode 100644 index 0000000..81591fc --- /dev/null +++ b/dlccore/project/__main__.py @@ -0,0 +1,17 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +import sys + +from dlccore.project.cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/dlccore/project/cli/__init__.py b/dlccore/project/cli/__init__.py new file mode 100644 index 0000000..48178ac --- /dev/null +++ b/dlccore/project/cli/__init__.py @@ -0,0 +1,86 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""Command-line entry point for `dlc-octopus`.""" + +from __future__ import annotations + +import argparse +import sys +from importlib.metadata import version +from pathlib import Path + +from dlccore.project.cli.ascii_logo import DISTRIBUTION, logo_banner + + +def build_parser() -> argparse.ArgumentParser: + """Return the `dlc-octopus` argument parser.""" + parser = argparse.ArgumentParser(prog="dlc-octopus") + parser.add_argument("--version", action="store_true", help="Print the logo and version, then exit.") + parser.add_argument("--no-art", action="store_true", help="Disable ASCII art.") + commands = parser.add_subparsers(dest="command") + inspect = commands.add_parser("inspect", help="Inspect a project and print its tree and findings.") + inspect.add_argument("project", type=Path, help="A project root, or its config.yaml.") + inspect.add_argument( + "--markdown", action="store_true", help="Print the findings as a Markdown table, project root redacted." + ) + inspect.add_argument( + "--fail-on-error", action="store_true", help="Exit with status 1 if a finding has blocking severity." + ) + return parser + + +def main(argv: list[str] | None = None) -> int: + """Run the `dlc-octopus` command. + + Args: + argv: Arguments without the program name; defaults to `sys.argv[1:]`. + + Returns: + Process exit code: 1 for blocking findings under ``--fail-on-error``, 2 for a path that is not a project. + """ + parser = build_parser() + args = parser.parse_args(argv) + if args.command == "inspect": + return _inspect(args.project, markdown=args.markdown, fail_on_error=args.fail_on_error) + if not args.version: + parser.print_help() + return 0 + + line = f"{DISTRIBUTION} {version(DISTRIBUTION)}" + banner = None + if not args.no_art: + try: + banner = logo_banner(version_line=line) + except (ImportError, OSError, RuntimeError, ValueError): + banner = None + print(banner or line) + return 0 + + +def _inspect(project: Path, *, markdown: bool, fail_on_error: bool) -> int: + """Print a project's report, or its findings as Markdown, and return the exit code.""" + from dlccore.project.api import inspect_project + from dlccore.project.api.helpers import get_blocking_findings + from dlccore.project.visualization import render_findings_markdown, render_project_report + + try: + snapshot = inspect_project(project) + except (FileNotFoundError, ValueError) as error: + print(f"dlc-octopus inspect: {error}", file=sys.stderr) + return 2 + + if markdown: + print(render_findings_markdown(snapshot.findings, project_root=snapshot.project_root)) + else: + print(render_project_report(snapshot)) + + return 1 if fail_on_error and get_blocking_findings(snapshot.findings) else 0 diff --git a/dlccore/project/cli/ascii_logo.py b/dlccore/project/cli/ascii_logo.py new file mode 100644 index 0000000..2bcac57 --- /dev/null +++ b/dlccore/project/cli/ascii_logo.py @@ -0,0 +1,594 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""Ported from DeepLabCut-live-GUI dlclivegui/assets/ascii_art.py by its sole author.""" + +from __future__ import annotations + +import itertools +import json +import math +import os +import re +import shutil +import sys +from collections.abc import Callable +from dataclasses import dataclass +from importlib import metadata, resources +from pathlib import Path +from typing import TYPE_CHECKING, Literal + +if TYPE_CHECKING: + import numpy as np + +ColorMode = Literal["auto", "always", "never"] +Cells = list[list[str]] +Colors = list[list[tuple[int, int, int]]] + +ASCII_RAMP_SIMPLE = "@%#*+=-:. " +ASCII_RAMP_FINE = "@$B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. " +LOGO_FILENAME = "logo.png" +KEYPOINTS_FILENAME = "logo_keypoints.json" +BODY_RGB = (128, 128, 128) +EDGE_DIM = 0.55 +"""Weight of the group colour against `BODY_RGB` in skeleton edges.""" +EDGE_GLYPHS = "─╲│╱" # noqa: RUF001 +EDGE_GLYPHS_ASCII = "-\\|/" +KEYPOINT_MARKER = "●" +KEYPOINT_MARKER_ASCII = "O" +TITLE_RGB = (176, 176, 176) +TITLE_LETTER_WIDTH = 10 +TITLE_TOP = tuple( + r""" + ___ ___ ___ + /\ \ /\__\ /\ \ + /::\ \ /:/ / /::\ \ + /:/\:\__\ /:/__/ /:/\:\__\ + \:\/:/ / \:\ \ \:\ \/__/ + \::/ / \:\__\ \:\__\ + \/__/ \/__/ \/__/ +""".strip("\n").splitlines() +) +"""Letters from the FIGlet font smisome1 (Lennert Stock, Kent Nassen, M. Lindsey), as are those of `TITLE_BOTTOM`.""" +TITLE_BOTTOM = tuple( + r""" + ___ ___ ___ ___ ___ ___ ___ + /\ \ /\ \ /\ \ /\ \ /\ \ /\__\ /\ \ + /::\ \ /::\ \ \:\ \ /::\ \ /::\ \ /:/ _/_ /::\ \ + /:/\:\__\ /:/\:\__\ /::\__\ /:/\:\__\ /::\:\__\ /:/_/\__\ /\:\:\__\ + \:\/:/ / \:\ \/__/ /:/\/__/ \:\/:/ / \/\::/ / \:\/:/ / \:\:\/__/ + \::/ / \:\__\ \/__/ \::/ / \/__/ \::/ / \::/ / + \/__/ \/__/ \/__/ \/__/ \/__/ +""".strip("\n").splitlines() +) +DISTRIBUTION = "dlccore" +ONLY_ADOPTING_ARMS = True +"""Draw an arm only once its library depends on `DISTRIBUTION`; False draws every arm.""" +HUB = "hub" +CORE_ARM = "arm-4" +"""dlccore's arm: the package itself, not an adopter, so drawn like the head and hub.""" +ALWAYS_SHOWN = frozenset({"head", HUB, CORE_ARM}) +"""Keypoint groups drawn whatever is installed.""" +ADOPTERS = { + "arm-1": ("napari-deeplabcut", None), + "arm-2": ("scene-pipelines", "dlc"), + "arm-3": ("deeplabcut", None), + "arm-5": ("deeplabcut", "gui"), + "arm-6": ("deeplabcut-live", None), + "arm-7": ("deeplabcut-live-gui", None), +} +"""Each arm's distribution and extra; the arm is drawn once that distribution, with that extra, requires dlccore.""" +ARM_LABELS = { + "arm-1": "napari-DLC", + "arm-2": "SCENE-pipelines", + "arm-3": "DLC", + "arm-4": "dlccore", + "arm-5": "DLC-GUI", + "arm-6": "DLC-Live", + "arm-7": "DLC-Live-GUI", +} +"""Text drawn by each arm's tip, in the arm's colour.""" +SHOW_ARM_LABELS = True +"""Draw `ARM_LABELS` by the tips of the drawn arms; False draws no labels.""" +COPYRIGHT = "© A. & M.W. Mathis Labs · deeplabcut.org" +"""From DeepLabCut's source file header; centred under the banner in `TITLE_RGB`.""" +COPYRIGHT_ASCII = "(c) A. & M.W. Mathis Labs - deeplabcut.org" +SHOW_COPYRIGHT = True +"""End the banner with `COPYRIGHT`, or `COPYRIGHT_ASCII` where stdout cannot encode it.""" +SHOW_TITLE = True +"""Draw `TITLE_TOP` and `TITLE_BOTTOM`; False draws the logo alone. Labels are not placed around the title.""" + + +@dataclass(frozen=True) +class KeypointGroup: + """One skeleton group of the logo, in 0-1 image coordinates (x right, y down).""" + + name: str + color: tuple[int, int, int] + points: tuple[tuple[float, float], ...] + lines: tuple[tuple[tuple[float, float], ...], ...] + + +def enable_windows_ansi_support() -> None: + """Enable ANSI escape support in Windows terminals; no-op elsewhere.""" + if os.name == "nt": + os.system("") + + +def get_terminal_width(default: int = 80) -> int: + """Return terminal width in columns, or `default` if stdout is not a TTY.""" + try: + if not sys.stdout.isatty(): + return default + return shutil.get_terminal_size((default, 24)).columns + except (OSError, ValueError): + return default + + +def should_use_color(mode: ColorMode = "auto") -> bool: + """Return whether to emit ANSI color: `auto` means a TTY with NO_COLOR unset.""" + if mode == "never": + return False + if mode == "always": + return True + if os.environ.get("NO_COLOR"): + return False + return sys.stdout.isatty() + + +def terminal_is_wide_enough(min_width: int = 60) -> bool: + """Return whether stdout is a TTY at least `min_width` columns wide.""" + if not sys.stdout.isatty(): + return False + return get_terminal_width() >= min_width + + +def _resource_path(filename: str) -> Path: + """Return `filename` as shipped with this package.""" + return Path(str(resources.files(__package__) / filename)) + + +def logo_path() -> Path: + """Return the path of the logo image.""" + return _resource_path(LOGO_FILENAME) + + +def keypoints_path() -> Path: + """Return the path of the logo keypoint file.""" + return _resource_path(KEYPOINTS_FILENAME) + + +def _parse_group(group: dict) -> KeypointGroup: + r, g, b = group["color"] + return KeypointGroup( + name=str(group["name"]), + color=(int(r), int(g), int(b)), + points=tuple((float(x), float(y)) for x, y in group["points"]), + lines=tuple(tuple((float(x), float(y)) for x, y in line) for line in group["lines"]), + ) + + +def load_keypoints(path: Path) -> list[KeypointGroup] | None: + """Return the logo keypoint groups in draw order, or None if `path` does not exist. + + Raises: + ValueError: If the file is not a valid keypoint file. + """ + if not path.is_file(): + return None + try: + return [_parse_group(g) for g in json.loads(path.read_text(encoding="utf-8"))["groups"]] + except (KeyError, TypeError) as e: + raise ValueError(f"Invalid logo keypoint file {path}: {e!r}") from e + + +def _normalize(name: str) -> str: + return re.sub(r"[-_.]+", "-", name).lower() + + +def _installed_requirements(distribution: str) -> list[str] | None: + """Return the requirement lines of an installed `distribution`, or None if it is not installed.""" + try: + return metadata.requires(distribution) or [] + except metadata.PackageNotFoundError: + return None + + +def adopting_arms(requires: Callable[[str], list[str] | None] = _installed_requirements) -> frozenset[str]: + """Return the arms of `ADOPTERS` whose distribution, with its extra, requires `DISTRIBUTION`. + + Raises: + ImportError: If packaging is not installed. + ValueError: If a requirement line cannot be parsed. + """ + from packaging.requirements import Requirement + + arms = set() + for arm, (distribution, extra) in ADOPTERS.items(): + for line in requires(distribution) or (): + requirement = Requirement(line) + if _normalize(requirement.name) != DISTRIBUTION: + continue + if requirement.marker is None or requirement.marker.evaluate({"extra": extra or ""}): + arms.add(arm) + return frozenset(arms) + + +def shown_groups(groups: list[KeypointGroup], arms: frozenset[str]) -> list[KeypointGroup]: + """Return `groups` keeping `ALWAYS_SHOWN` and the given `arms` only.""" + return [group for group in groups if group.name in ALWAYS_SHOWN or group.name in arms] + + +def _to_bgr(img: np.ndarray) -> np.ndarray: + import cv2 as cv + + if img.ndim == 2: + return cv.cvtColor(img, cv.COLOR_GRAY2BGR) + if img.ndim == 3 and img.shape[2] == 3: + return img + raise ValueError(f"Unsupported image shape for BGR conversion: {img.shape!r}") + + +def _composite_over_color(img: np.ndarray, bg_bgr: tuple[int, int, int]) -> np.ndarray: + import numpy as np + + if img.ndim == 3 and img.shape[2] == 4: + alpha = (img[..., 3].astype(np.float32) / 255.0)[..., None] + bgr = img[..., :3].astype(np.float32) + bg = np.empty_like(bgr) + bg[...] = bg_bgr + out = alpha * bgr + (1.0 - alpha) * bg + return np.clip(out, 0, 255).astype(np.uint8) + return _to_bgr(img) + + +def _content_box(img_bgra: np.ndarray, alpha_thresh: int, pad: int) -> tuple[int, int, int, int]: + """Return the inclusive (x0, y0, x1, y1) box around pixels with alpha above `alpha_thresh`.""" + import numpy as np + + mask = img_bgra[..., 3] > alpha_thresh + h, w = mask.shape + if not mask.any(): + return 0, 0, w - 1, h - 1 + ys, xs = np.where(mask) + return max(0, xs.min() - pad), max(0, ys.min() - pad), min(w - 1, xs.max() + pad), min(h - 1, ys.max() + pad) + + +def _resize_for_terminal(img: np.ndarray, width: int, aspect: float) -> np.ndarray: + import cv2 as cv + + h, w = img.shape[:2] + width = max(20, int(width)) + new_h = max(1, int((h / w) * width * aspect)) + return cv.resize(img, (width, new_h), interpolation=cv.INTER_AREA) + + +def _map_luminance_to_chars(gray: np.ndarray, ramp: str) -> list[str]: + import numpy as np + + ramp_arr = np.array(list(ramp), dtype=" bool: + try: + text.encode(sys.stdout.encoding or "ascii") + except (LookupError, UnicodeEncodeError): + return False + return True + + +def _edge_glyph(dx: float, dy: float, aspect: float, glyphs: str) -> str: + """Return the glyph of `glyphs` (horizontal, down-right, vertical, up-right) nearest a cell step.""" + angle = math.degrees(math.atan2(dy / aspect, dx)) % 180 + return glyphs[int((angle + 22.5) % 180 // 45)] + + +def _place_label( + text: str, tip: tuple[int, int], shape: tuple[int, int], blocked: set[tuple[int, int]], *, aspect: float +) -> tuple[int, int] | None: + """Return the (row, column) nearest `tip` where `text` and one cell either side avoid `blocked`, or None. + + Distance runs from `tip` to the nearest character of `text`, a row counting as `1 / aspect` columns; ties go to + the placement whose middle is nearest `tip`'s column. + """ + (n_rows, n_cols), (ti, tj) = shape, tip + + def distance(cell: tuple[int, int]) -> tuple[float, float]: + i, j = cell + return math.hypot((i - ti) / aspect, max(j - tj, 0, tj - j - len(text) + 1)), abs(j + (len(text) - 1) / 2 - tj) + + for i, j in sorted(itertools.product(range(n_rows), range(n_cols - len(text) + 1)), key=distance): + if all((i, k) not in blocked for k in range(max(0, j - 1), min(n_cols, j + len(text) + 1))): + return i, j + return None + + +def _draw_keypoints( + chars: Cells, + keypoints: list[KeypointGroup], + box: tuple[int, int, int, int], + image_size: tuple[int, int], + *, + aspect: float, + labels: dict[str, str] | None = None, +) -> tuple[Cells, Colors]: + """Draw keypoint edges and markers over body `chars`, which cover `box` of an image of `image_size`. + + Each group named in `labels` then gets its text over the body as near its last point as the skeleton allows. + """ + n_rows, n_cols = len(chars), len(chars[0]) + x0, y0, x1, y1 = box + sx, sy = image_size[0] / (x1 - x0 + 1) * n_cols, image_size[1] / (y1 - y0 + 1) * n_rows + ox, oy = x0 / image_size[0] * sx, y0 / image_size[1] * sy + + unicode_ok = _stdout_can_encode(EDGE_GLYPHS + KEYPOINT_MARKER) + glyphs = EDGE_GLYPHS if unicode_ok else EDGE_GLYPHS_ASCII + marker = KEYPOINT_MARKER if unicode_ok else KEYPOINT_MARKER_ASCII + diagonals = {glyphs[1], glyphs[3]} + # Several edges leave the hub; a diagonal beside it on its own row reads as leaving it upward. + beside_hub = { + (math.floor(y * sy - oy), math.floor(x * sx - ox) + side) + for group in keypoints + if group.name == HUB + for x, y in group.points + for side in (-1, 1) + } + colors = [[BODY_RGB] * n_cols for _ in chars] + skeleton: set[tuple[int, int]] = set() + + def put(col: float, row: float, ch: str, rgb: tuple[int, int, int]) -> None: + i, j = int(row), int(col) + if 0 <= i < n_rows and 0 <= j < n_cols: + chars[i][j], colors[i][j] = ch, rgb + skeleton.add((i, j)) + + for group in keypoints: + edge_rgb = tuple(round(c * EDGE_DIM + b * (1 - EDGE_DIM)) for c, b in zip(group.color, BODY_RGB, strict=True)) + for line in group.lines: + cells = [(x * sx - ox, y * sy - oy) for x, y in line] + for (ax, ay), (bx, by) in itertools.pairwise(cells): + ch = _edge_glyph(bx - ax, by - ay, aspect, glyphs) + (ci, cj), (di, dj) = (math.floor(ay), math.floor(ax)), (math.floor(by), math.floor(bx)) + n = max(1, abs(di - ci), abs(dj - cj)) + for k in range(n + 1): + i, j = math.floor(ci + (di - ci) * k / n + 0.5), math.floor(cj + (dj - cj) * k / n + 0.5) + if ch not in diagonals or (i, j) not in beside_hub: + put(j, i, ch, edge_rgb) + for x, y in group.points: + put(x * sx - ox, y * sy - oy, marker, group.color) + + for group in keypoints: + text = (labels or {}).get(group.name) + if text is None or not group.points: + continue + x, y = group.points[-1] # an arm's points run from the hub to its tip + at = _place_label(text, (int(y * sy - oy), int(x * sx - ox)), (n_rows, n_cols), skeleton, aspect=aspect) + if at is None: + continue + i, j = at + for k in range(max(0, j - 1), min(n_cols, j + len(text) + 1)): + chars[i][k] = " " + skeleton.add((i, k)) + for k, ch in enumerate(text): + chars[i][j + k], colors[i][j + k] = ch, group.color + return chars, colors + + +def _emit(chars: Cells, colors: Colors, *, use_color: bool) -> list[str]: + """Join character cells into lines, with 24-bit ANSI color if `use_color`.""" + if not use_color: + return ["".join(row).rstrip() for row in chars] + lines = [] + for char_row, color_row in zip(chars, colors, strict=True): + parts: list[str] = [] + prev = None + for ch, rgb in zip(char_row, color_row, strict=True): + if rgb != prev and ch != " ": + parts.append(f"\x1b[38;2;{rgb[0]};{rgb[1]};{rgb[2]}m") + prev = rgb + parts.append(ch) + lines.append("".join(parts).rstrip() + "\x1b[0m") + return lines + + +def _ascii_cells( + image_path: Path, + *, + width: int, + aspect: float = 0.5, + fine: bool = False, + invert: bool = False, + crop_content: bool = False, + alpha_thresh: int = 1, + crop_pad: int = 0, + bg_bgr: tuple[int, int, int] = (255, 255, 255), + keypoints: list[KeypointGroup] | None = None, + labels: dict[str, str] | None = None, +) -> tuple[Cells, Colors]: + """Return the image as character cells and their RGB colors. + + Arguments are as for `generate_ascii_lines`, plus `labels`: text drawn by the tip of each named keypoint group. + """ + import cv2 as cv + + if not image_path.is_file(): + raise FileNotFoundError(image_path) + img = cv.imread(str(image_path), cv.IMREAD_UNCHANGED) + if img is None: + raise RuntimeError(f"Failed to load image with OpenCV: {image_path}") + + image_size = (img.shape[1], img.shape[0]) + box = (0, 0, image_size[0] - 1, image_size[1] - 1) + has_alpha = img.ndim == 3 and img.shape[2] == 4 + if crop_content and has_alpha: + box = _content_box(img, alpha_thresh, crop_pad) + img = img[box[1] : box[3] + 1, box[0] : box[2] + 1, :] + if keypoints is not None and has_alpha: + img = img.copy() + img[..., :3] = 0 # the skeleton is redrawn from `keypoints` + img_bgr = _resize_for_terminal(_composite_over_color(img, bg_bgr), width, aspect) + + gray = cv.cvtColor(img_bgr, cv.COLOR_BGR2GRAY) + if invert: + gray = 255 - gray + chars = [list(row) for row in _map_luminance_to_chars(gray, ASCII_RAMP_FINE if fine else ASCII_RAMP_SIMPLE)] + if keypoints is None: + return chars, [[(r, g, b) for b, g, r in row] for row in img_bgr.tolist()] + return _draw_keypoints(chars, keypoints, box, image_size, aspect=aspect, labels=labels) + + +def generate_ascii_lines( + image_path: Path, + *, + width: int, + aspect: float = 0.5, + color: ColorMode = "auto", + fine: bool = False, + invert: bool = False, + crop_content: bool = False, + alpha_thresh: int = 1, + crop_pad: int = 0, + bg_bgr: tuple[int, int, int] = (255, 255, 255), + keypoints: list[KeypointGroup] | None = None, +) -> list[str]: + """Load an image and return it as ASCII art lines. + + Args: + image_path: Input image. + width: Output width in characters. + aspect: Character cell height/width ratio. + color: ANSI color mode. + fine: Use the 70-character ramp instead of the 10-character one. + invert: Invert the luminance mapping. + crop_content: Crop to pixels with alpha above `alpha_thresh`, if the image has alpha. + alpha_thresh: Alpha threshold for cropping (0-255). + crop_pad: Pixels of padding kept around the cropped content. + bg_bgr: Background color transparency is composited over. + keypoints: If set, the body is drawn in grey from its silhouette and these skeletons over it. + + Returns: + One string per terminal row. + + Raises: + ImportError: If numpy or OpenCV is not installed. + FileNotFoundError: If `image_path` does not exist. + RuntimeError: If OpenCV cannot decode the image. + """ + chars, colors = _ascii_cells( + image_path, + width=width, + aspect=aspect, + fine=fine, + invert=invert, + crop_content=crop_content, + alpha_thresh=alpha_thresh, + crop_pad=crop_pad, + bg_bgr=bg_bgr, + keypoints=keypoints, + ) + use_color = should_use_color(color) + if use_color: + enable_windows_ansi_support() + return _emit(chars, colors, use_color=use_color) + + +def _place_title(rows: tuple[str, ...], chars: Cells, colors: Colors, *, top: int) -> None: + """Draw `rows` centred, `top` rows down, blanking the cells each letter covers plus one either side.""" + text_width = max(len(row) for row in rows) + left = (len(chars[0]) - text_width) // 2 + for i, row in enumerate(rows): + if top + i == len(chars): + chars.append([" "] * len(chars[0])) + colors.append([TITLE_RGB] * len(chars[0])) + row = row.ljust(text_width) + for x0 in range(0, text_width, TITLE_LETTER_WIDTH): + strokes = [j for j in range(x0, min(x0 + TITLE_LETTER_WIDTH, text_width)) if row[j] != " "] + if not strokes: + continue + for j in range(max(0, strokes[0] - 1), min(text_width, strokes[-1] + 2)): + chars[top + i][left + j], colors[top + i][left + j] = row[j], TITLE_RGB + + +def _add_title(chars: Cells, colors: Colors) -> tuple[Cells, Colors]: + """Put `TITLE_TOP` above the logo and `TITLE_BOTTOM` below it, a blank row apart; omit what does not fit.""" + width = len(chars[0]) + while chars and not "".join(chars[-1]).strip(): + chars, colors = chars[:-1], colors[:-1] + if max(len(row) for row in TITLE_TOP) > width: + return chars, colors + gap = len(TITLE_TOP) + 1 + chars = [[" "] * width for _ in range(gap)] + chars + colors = [[TITLE_RGB] * width for _ in range(gap)] + colors + _place_title(TITLE_TOP, chars, colors, top=0) + if max(len(row) for row in TITLE_BOTTOM) <= width: + chars.append([" "] * width) + colors.append([TITLE_RGB] * width) + _place_title(TITLE_BOTTOM, chars, colors, top=len(chars)) + return chars, colors + + +def _add_footer(chars: Cells, colors: Colors, text: str, *, gap: bool = True) -> tuple[Cells, Colors]: + """Put `text` centred below the last drawn row, a blank row apart unless not `gap`; omit it if it does not fit.""" + width = len(chars[0]) + while chars and not "".join(chars[-1]).strip(): + chars, colors = chars[:-1], colors[:-1] + if len(text) > width: + return chars, colors + left = (width - len(text)) // 2 + row = [" "] * left + list(text) + [" "] * (width - left - len(text)) + blank = [[" "] * width] if gap else [] + return [*chars, *blank, row], [*colors, *([[TITLE_RGB] * width] if gap else []), [TITLE_RGB] * width] + + +def logo_banner( + *, color: ColorMode = "auto", min_width: int = 60, max_width: int = 120, version_line: str | None = None +) -> str | None: + """Return the titled logo as ASCII art, or None if the terminal is not a TTY or too narrow. + + Args: + color: When to colour the output. + min_width: Narrowest terminal the logo is drawn in. + max_width: Widest the logo is drawn. + version_line: Drawn last, centred in the copyright's colour, directly under the copyright when shown. + + Raises: + ImportError: If numpy or OpenCV is not installed. + FileNotFoundError: If the logo is missing. + RuntimeError: If OpenCV cannot decode the logo. + ValueError: If the logo keypoint file is invalid, or an installed requirement cannot be parsed. + """ + if not terminal_is_wide_enough(min_width): + return None + width = max(min(get_terminal_width(default=max_width), max_width), min_width) + keypoints = load_keypoints(keypoints_path()) + if keypoints is not None and ONLY_ADOPTING_ARMS: + keypoints = shown_groups(keypoints, adopting_arms()) + chars, colors = _ascii_cells( + logo_path(), + width=width, + fine=True, + crop_content=True, + crop_pad=1, + keypoints=keypoints, + labels=ARM_LABELS if SHOW_ARM_LABELS else None, + ) + if SHOW_TITLE: + chars, colors = _add_title(chars, colors) + if SHOW_COPYRIGHT: + chars, colors = _add_footer(chars, colors, COPYRIGHT if _stdout_can_encode(COPYRIGHT) else COPYRIGHT_ASCII) + if version_line: + chars, colors = _add_footer(chars, colors, version_line, gap=not SHOW_COPYRIGHT) + use_color = should_use_color(color) + if use_color: + enable_windows_ansi_support() + return "\n".join(_emit(chars, colors, use_color=use_color)) diff --git a/dlccore/project/cli/logo.png b/dlccore/project/cli/logo.png new file mode 100644 index 0000000..39bfab6 Binary files /dev/null and b/dlccore/project/cli/logo.png differ diff --git a/dlccore/project/cli/logo_keypoints.json b/dlccore/project/cli/logo_keypoints.json new file mode 100644 index 0000000..de82f67 --- /dev/null +++ b/dlccore/project/cli/logo_keypoints.json @@ -0,0 +1 @@ +{"groups":[{"name":"arm-1","color":[56,109,249],"points":[[0.3373,0.4569],[0.2671,0.3772],[0.252,0.2847],[0.2448,0.2113],[0.2049,0.1699],[0.1515,0.1683],[0.1188,0.2041],[0.1316,0.2608],[0.1707,0.26]],"lines":[[[0.5,0.4952],[0.4797,0.4904],[0.4593,0.4856],[0.439,0.4809],[0.4187,0.4761],[0.3983,0.4713],[0.378,0.4665],[0.3577,0.4617],[0.3373,0.4569]],[[0.3373,0.4569],[0.3237,0.449],[0.312,0.4402],[0.3018,0.4306],[0.293,0.4205],[0.2854,0.4099],[0.2787,0.399],[0.2727,0.3881],[0.2671,0.3772]],[[0.2671,0.3772],[0.2626,0.3661],[0.2593,0.3545],[0.2571,0.3426],[0.2556,0.3305],[0.2547,0.3185],[0.2539,0.3068],[0.2531,0.2954],[0.252,0.2847]],[[0.252,0.2847],[0.2509,0.2744],[0.2504,0.2643],[0.2502,0.2544],[0.25,0.2448],[0.2496,0.2357],[0.2487,0.227],[0.2472,0.2188],[0.2448,0.2113]],[[0.2448,0.2113],[0.2415,0.2043],[0.2375,0.1978],[0.2329,0.1917],[0.2278,0.1861],[0.2223,0.1811],[0.2166,0.1767],[0.2108,0.1729],[0.2049,0.1699]],[[0.2049,0.1699],[0.1988,0.1675],[0.1921,0.1658],[0.185,0.1647],[0.1778,0.1642],[0.1706,0.1644],[0.1637,0.1651],[0.1573,0.1664],[0.1515,0.1683]],[[0.1515,0.1683],[0.1461,0.1708],[0.1408,0.1741],[0.1357,0.1781],[0.131,0.1826],[0.1268,0.1875],[0.1233,0.1928],[0.1206,0.1984],[0.1188,0.2041]],[[0.1188,0.2041],[0.1181,0.2106],[0.1182,0.2182],[0.1191,0.2264],[0.1207,0.2347],[0.1229,0.2428],[0.1255,0.2502],[0.1284,0.2563],[0.1316,0.2608]],[[0.1316,0.2608],[0.1355,0.2634],[0.1404,0.2646],[0.146,0.2646],[0.1519,0.2639],[0.1577,0.2627],[0.163,0.2615],[0.1675,0.2604],[0.1707,0.26]]]},{"name":"arm-2","color":[18,200,230],"points":[[0.3301,0.5359],[0.244,0.508],[0.1898,0.4553],[0.1364,0.4258],[0.0885,0.4458],[0.0734,0.5032],[0.0965,0.5455],[0.1499,0.5391]],"lines":[[[0.5,0.4952],[0.4788,0.5003],[0.4575,0.5054],[0.4363,0.5105],[0.4151,0.5156],[0.3938,0.5206],[0.3726,0.5257],[0.3514,0.5308],[0.3301,0.5359]],[[0.3301,0.5359],[0.3152,0.5358],[0.302,0.5343],[0.2903,0.5315],[0.2799,0.5278],[0.2703,0.5233],[0.2613,0.5183],[0.2527,0.5131],[0.244,0.508]],[[0.244,0.508],[0.2357,0.5024],[0.2282,0.496],[0.2213,0.489],[0.2149,0.4818],[0.2087,0.4745],[0.2025,0.4675],[0.1963,0.461],[0.1898,0.4553]],[[0.1898,0.4553],[0.183,0.4502],[0.1762,0.4452],[0.1695,0.4404],[0.1627,0.4361],[0.156,0.4323],[0.1493,0.4292],[0.1428,0.427],[0.1364,0.4258]],[[0.1364,0.4258],[0.1299,0.4257],[0.1232,0.4265],[0.1166,0.428],[0.11,0.4304],[0.1038,0.4334],[0.098,0.437],[0.0929,0.4412],[0.0885,0.4458]],[[0.0885,0.4458],[0.0848,0.4513],[0.0815,0.4578],[0.0788,0.4652],[0.0765,0.4731],[0.0748,0.4811],[0.0737,0.489],[0.0732,0.4965],[0.0734,0.5032]],[[0.0734,0.5032],[0.0742,0.5095],[0.0757,0.516],[0.0779,0.5223],[0.0806,0.5283],[0.0839,0.5338],[0.0877,0.5387],[0.0919,0.5426],[0.0965,0.5455]],[[0.0965,0.5455],[0.1021,0.5469],[0.109,0.5471],[0.1167,0.5463],[0.1247,0.5449],[0.1325,0.5431],[0.1396,0.5414],[0.1456,0.5399],[0.1499,0.5391]]]},{"name":"arm-3","color":[90,248,200],"points":[[0.3971,0.6132],[0.3142,0.6619],[0.2384,0.6475],[0.1707,0.6411],[0.122,0.6818],[0.1148,0.744],[0.1443,0.7831],[0.1906,0.7919],[0.2201,0.7624]],"lines":[[[0.5,0.4952],[0.4871,0.51],[0.4743,0.5247],[0.4614,0.5395],[0.4486,0.5542],[0.4357,0.569],[0.4228,0.5837],[0.41,0.5985],[0.3971,0.6132]],[[0.3971,0.6132],[0.3858,0.6231],[0.3748,0.6318],[0.3643,0.6393],[0.354,0.6458],[0.3439,0.6513],[0.334,0.6558],[0.3241,0.6593],[0.3142,0.6619]],[[0.3142,0.6619],[0.3043,0.663],[0.2946,0.6625],[0.2849,0.6608],[0.2754,0.6581],[0.2659,0.6551],[0.2566,0.652],[0.2475,0.6494],[0.2384,0.6475]],[[0.2384,0.6475],[0.2295,0.646],[0.2205,0.6443],[0.2116,0.6425],[0.2029,0.6409],[0.1943,0.6397],[0.1861,0.6392],[0.1782,0.6396],[0.1707,0.6411]],[[0.1707,0.6411],[0.1634,0.6438],[0.1562,0.6475],[0.1492,0.652],[0.1425,0.6572],[0.1364,0.6629],[0.1308,0.669],[0.126,0.6754],[0.122,0.6818]],[[0.122,0.6818],[0.1189,0.6887],[0.1164,0.6964],[0.1147,0.7046],[0.1135,0.713],[0.113,0.7214],[0.1131,0.7296],[0.1137,0.7372],[0.1148,0.744]],[[0.1148,0.744],[0.1167,0.7502],[0.1192,0.7561],[0.1225,0.7617],[0.1262,0.7669],[0.1304,0.7717],[0.1349,0.776],[0.1396,0.7798],[0.1443,0.7831]],[[0.1443,0.7831],[0.1494,0.7859],[0.1551,0.7883],[0.1612,0.7903],[0.1675,0.7918],[0.1737,0.7927],[0.1798,0.7931],[0.1855,0.7928],[0.1906,0.7919]],[[0.1906,0.7919],[0.1953,0.7898],[0.1998,0.7865],[0.2042,0.7823],[0.2082,0.7777],[0.2119,0.7729],[0.2152,0.7686],[0.2179,0.7649],[0.2201,0.7624]]]},{"name":"arm-4","color":[164,248,159],"points":[[0.4992,0.6571],[0.4601,0.7313],[0.3947,0.7735],[0.3907,0.8405],[0.4378,0.8732],[0.4888,0.8636],[0.5096,0.8254]],"lines":[[[0.5,0.4952],[0.4999,0.5155],[0.4998,0.5357],[0.4997,0.5559],[0.4996,0.5762],[0.4995,0.5964],[0.4994,0.6166],[0.4993,0.6369],[0.4992,0.6571]],[[0.4992,0.6571],[0.4963,0.6708],[0.4927,0.6826],[0.4885,0.6927],[0.4837,0.7017],[0.4784,0.7096],[0.4726,0.717],[0.4665,0.7241],[0.4601,0.7313]],[[0.4601,0.7313],[0.4528,0.7379],[0.4442,0.7435],[0.4348,0.7484],[0.4252,0.7528],[0.4159,0.7573],[0.4074,0.762],[0.4002,0.7673],[0.3947,0.7735]],[[0.3947,0.7735],[0.391,0.7809],[0.3882,0.7893],[0.3865,0.7983],[0.3857,0.8076],[0.3858,0.8168],[0.3867,0.8256],[0.3884,0.8336],[0.3907,0.8405]],[[0.3907,0.8405],[0.3942,0.8465],[0.3988,0.8521],[0.4045,0.8571],[0.4108,0.8616],[0.4176,0.8655],[0.4246,0.8688],[0.4314,0.8714],[0.4378,0.8732]],[[0.4378,0.8732],[0.4442,0.8742],[0.451,0.8745],[0.458,0.874],[0.465,0.8729],[0.4717,0.8712],[0.4781,0.869],[0.4839,0.8665],[0.4888,0.8636]],[[0.4888,0.8636],[0.493,0.86],[0.4966,0.8552],[0.4997,0.8497],[0.5024,0.8439],[0.5046,0.8382],[0.5066,0.8329],[0.5082,0.8285],[0.5096,0.8254]]]},{"name":"arm-5","color":[236,200,111],"points":[[0.61,0.6196],[0.7041,0.6619],[0.7943,0.638],[0.866,0.6667],[0.886,0.7384],[0.8581,0.7951],[0.8046,0.8166],[0.7671,0.7679]],"lines":[[[0.5,0.4952],[0.5138,0.5108],[0.5275,0.5263],[0.5413,0.5419],[0.555,0.5574],[0.5688,0.573],[0.5825,0.5885],[0.5963,0.6041],[0.61,0.6196]],[[0.61,0.6196],[0.6226,0.6293],[0.6348,0.6375],[0.6467,0.6444],[0.6583,0.65],[0.6699,0.6545],[0.6813,0.6579],[0.6927,0.6603],[0.7041,0.6619]],[[0.7041,0.6619],[0.7157,0.6617],[0.7274,0.6593],[0.739,0.6554],[0.7506,0.6508],[0.762,0.646],[0.7731,0.6418],[0.7839,0.6389],[0.7943,0.638]],[[0.7943,0.638],[0.8045,0.6387],[0.8147,0.6404],[0.8248,0.643],[0.8345,0.6463],[0.8437,0.6504],[0.8522,0.6552],[0.8597,0.6607],[0.866,0.6667]],[[0.866,0.6667],[0.8713,0.6737],[0.8758,0.6819],[0.8794,0.6911],[0.8822,0.7008],[0.8843,0.7107],[0.8856,0.7206],[0.8861,0.7299],[0.886,0.7384]],[[0.886,0.7384],[0.8849,0.7465],[0.8829,0.7545],[0.8801,0.7623],[0.8766,0.7699],[0.8725,0.7771],[0.8679,0.7837],[0.8631,0.7898],[0.8581,0.7951]],[[0.8581,0.7951],[0.8525,0.7999],[0.8461,0.8046],[0.8392,0.8088],[0.8319,0.8124],[0.8246,0.8152],[0.8175,0.817],[0.8107,0.8175],[0.8046,0.8166]],[[0.8046,0.8166],[0.7989,0.8135],[0.7933,0.8082],[0.7878,0.8013],[0.7825,0.7936],[0.7778,0.7857],[0.7735,0.7783],[0.7699,0.7722],[0.7671,0.7679]]]},{"name":"arm-6","color":[255,109,56],"points":[[0.6667,0.5335],[0.7464,0.512],[0.8006,0.4545],[0.8525,0.4139],[0.9091,0.4322],[0.9282,0.4872],[0.9043,0.5319],[0.8573,0.5231]],"lines":[[[0.5,0.4952],[0.5208,0.5],[0.5417,0.5048],[0.5625,0.5096],[0.5833,0.5144],[0.6042,0.5191],[0.625,0.5239],[0.6458,0.5287],[0.6667,0.5335]],[[0.6667,0.5335],[0.681,0.5339],[0.6933,0.5332],[0.7041,0.5314],[0.7136,0.5287],[0.7222,0.5253],[0.7303,0.5213],[0.7383,0.5168],[0.7464,0.512]],[[0.7464,0.512],[0.7544,0.5064],[0.7618,0.4997],[0.7687,0.4923],[0.7753,0.4844],[0.7816,0.4764],[0.7878,0.4686],[0.7941,0.4612],[0.8006,0.4545]],[[0.8006,0.4545],[0.8072,0.4483],[0.8137,0.4418],[0.82,0.4355],[0.8264,0.4295],[0.8328,0.4241],[0.8392,0.4195],[0.8458,0.416],[0.8525,0.4139]],[[0.8525,0.4139],[0.8596,0.4131],[0.8672,0.4135],[0.875,0.4148],[0.8828,0.4171],[0.8904,0.4201],[0.8975,0.4237],[0.9038,0.4278],[0.9091,0.4322]],[[0.9091,0.4322],[0.9136,0.4374],[0.9175,0.4436],[0.9209,0.4506],[0.9237,0.4581],[0.9259,0.4658],[0.9274,0.4734],[0.9282,0.4806],[0.9282,0.4872]],[[0.9282,0.4872],[0.9275,0.4937],[0.9258,0.5004],[0.9234,0.5071],[0.9204,0.5136],[0.9169,0.5195],[0.9129,0.5247],[0.9087,0.5289],[0.9043,0.5319]],[[0.9043,0.5319],[0.8992,0.5333],[0.8931,0.5333],[0.8863,0.5321],[0.8793,0.5303],[0.8725,0.5281],[0.8663,0.526],[0.861,0.5242],[0.8573,0.5231]]]},{"name":"arm-7","color":[255,0,0],"points":[[0.6547,0.4601],[0.7273,0.3931],[0.7432,0.2943],[0.7679,0.2073],[0.827,0.1722],[0.8764,0.1978],[0.8876,0.2432],[0.8341,0.2783]],"lines":[[[0.5,0.4952],[0.5193,0.4908],[0.5387,0.4864],[0.558,0.4821],[0.5774,0.4777],[0.5967,0.4733],[0.616,0.4689],[0.6354,0.4645],[0.6547,0.4601]],[[0.6547,0.4601],[0.6681,0.4535],[0.6799,0.4464],[0.6904,0.4387],[0.6997,0.4306],[0.7078,0.422],[0.715,0.4129],[0.7215,0.4033],[0.7273,0.3931]],[[0.7273,0.3931],[0.7319,0.3822],[0.735,0.3704],[0.737,0.3579],[0.7382,0.3449],[0.7391,0.3319],[0.7399,0.3189],[0.7412,0.3063],[0.7432,0.2943]],[[0.7432,0.2943],[0.7457,0.2825],[0.748,0.2705],[0.7503,0.2585],[0.7529,0.2468],[0.7558,0.2356],[0.7591,0.2251],[0.7632,0.2156],[0.7679,0.2073]],[[0.7679,0.2073],[0.7737,0.2001],[0.7805,0.1935],[0.788,0.1877],[0.7959,0.1828],[0.804,0.1787],[0.8121,0.1755],[0.8198,0.1734],[0.827,0.1722]],[[0.827,0.1722],[0.8339,0.1724],[0.8409,0.1739],[0.8479,0.1765],[0.8547,0.18],[0.8611,0.1841],[0.867,0.1886],[0.8721,0.1932],[0.8764,0.1978]],[[0.8764,0.1978],[0.8801,0.2026],[0.8834,0.208],[0.8862,0.2138],[0.8884,0.2199],[0.8898,0.2261],[0.8902,0.2321],[0.8895,0.2379],[0.8876,0.2432]],[[0.8876,0.2432],[0.8836,0.2483],[0.8775,0.2535],[0.8699,0.2587],[0.8615,0.2636],[0.8531,0.2682],[0.8452,0.2722],[0.8387,0.2757],[0.8341,0.2783]]]},{"name":"head","color":[128,0,255],"points":[[0.5,0.4274],[0.4242,0.3278],[0.5,0.1603],[0.5758,0.3278]],"lines":[[[0.5,0.4952],[0.5,0.4274]],[[0.5,0.4274],[0.4242,0.3278]],[[0.4242,0.3278],[0.5,0.1603]],[[0.5,0.1603],[0.5758,0.3278]],[[0.5758,0.3278],[0.5,0.4274]]]},{"name":"hub","color":[230,230,230],"points":[[0.5,0.4952]],"lines":[]}]} diff --git a/pyproject.toml b/pyproject.toml index e68fa21..574d42d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,9 +33,11 @@ optional-dependencies.hdf5 = [ "pandas[hdf5]", "tables>=3.10.1", "typing-extensi optional-dependencies.video = [ "opencv-python-headless>=4.10.0.84" ] urls.Homepage = "https://github.com/DeepLabCut/dlccore" urls.Repository = "https://github.com/DeepLabCut/dlccore" +scripts.dlc-octopus = "dlccore.project.cli:main" [tool.setuptools] packages.find.include = [ "dlccore*" ] +package-data."dlccore.project.cli" = [ "logo.png", "logo_keypoints.json" ] [tool.setuptools_scm] diff --git a/tests/project/cli/test_ascii_logo.py b/tests/project/cli/test_ascii_logo.py new file mode 100644 index 0000000..ff34508 --- /dev/null +++ b/tests/project/cli/test_ascii_logo.py @@ -0,0 +1,341 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""The `--version` logo: an octopus whose arms each stand for one DeepLabCut library. + +An arm's keypoints are drawn only once that library, installed, declares a dependency on dlccore. The head and the +hub are always drawn. +""" + +import re +from collections.abc import Callable +from pathlib import Path + +import pytest + +from dlccore.project.cli import ascii_logo +from dlccore.project.cli.ascii_logo import ( + ADOPTERS, + ALWAYS_SHOWN, + ARM_LABELS, + COPYRIGHT, + COPYRIGHT_ASCII, + CORE_ARM, + EDGE_GLYPHS, + KEYPOINT_MARKER, + TITLE_BOTTOM, + TITLE_TOP, + adopting_arms, + keypoints_path, + load_keypoints, + logo_banner, + shown_groups, +) + +_, DOWN_RIGHT, _, UP_RIGHT = EDGE_GLYPHS + +# Which library each arm stands for. Changing an arm's meaning means changing this table, on purpose. +ARM_MEANINGS = { + "arm-1": "napari-deeplabcut", + "arm-2": "scene-pipelines[dlc]", + "arm-3": "deeplabcut (core)", + "arm-5": "deeplabcut[gui]", + "arm-6": "deeplabcut-live", + "arm-7": "deeplabcut-live-gui", +} + + +def _installed(**requirements: list[str]) -> Callable[[str], list[str] | None]: + """Fake installed distributions: name -> requirement lines; anything else is not installed.""" + return lambda distribution: requirements.get(distribution) + + +def test_a_missing_keypoint_file_loads_as_none(tmp_path: Path) -> None: + assert load_keypoints(tmp_path / "absent.json") is None + + +@pytest.mark.parametrize( + "content", + ['{"group": []}', '{"groups": [{"points": [], "lines": []}]}', '{"groups": [{"color": 3}]}', "not json"], +) +def test_a_malformed_keypoint_file_raises_value_error(tmp_path: Path, content: str) -> None: + path = tmp_path / "keypoints.json" + path.write_text(content, encoding="utf-8") + + with pytest.raises(ValueError): + load_keypoints(path) + + +def test_each_arm_stands_for_the_library_listed_here() -> None: + meanings = {arm: f"{name}[{extra}]" if extra else name for arm, (name, extra) in ADOPTERS.items()} + + assert meanings == {arm: meaning.split(" ")[0] for arm, meaning in ARM_MEANINGS.items()} + + +def test_the_shipped_logo_has_exactly_the_head_the_hub_and_one_group_per_arm() -> None: + groups = load_keypoints(keypoints_path()) + + assert groups is not None + assert sorted(group.name for group in groups) == sorted([*ALWAYS_SHOWN, *ARM_MEANINGS]) + assert all(group.points for group in groups) + + +def test_no_library_installed_lights_no_arm() -> None: + assert adopting_arms(_installed()) == frozenset() + + +def test_an_installed_library_that_does_not_depend_on_dlccore_lights_no_arm() -> None: + assert adopting_arms(_installed(deeplabcut=["numpy", "dlccore-extras"])) == frozenset() + + +@pytest.mark.parametrize("line", ["dlccore", "DLCCore>=0.1", "dlccore ; python_version >= '3'"]) +def test_a_library_depending_on_dlccore_lights_its_arm(line: str) -> None: + assert adopting_arms(_installed(**{"napari-deeplabcut": [line]})) == {"arm-1"} + + +def test_a_dependency_under_the_dlc_extra_lights_the_scene_pipelines_arm() -> None: + assert adopting_arms(_installed(**{"scene-pipelines": ["dlccore ; extra == 'dlc'"]})) == {"arm-2"} + + +def test_a_dependency_under_the_gui_extra_lights_only_the_gui_arm() -> None: + arms = adopting_arms(_installed(deeplabcut=["dlccore ; extra == 'gui'"])) + + assert arms == {"arm-5"} + + +def test_a_core_dependency_lights_both_core_and_gui_arms() -> None: + # A GUI install pulls in core's dependencies, so it uses dlccore too. + assert adopting_arms(_installed(deeplabcut=["dlccore"])) == {"arm-3", "arm-5"} + + +def test_every_library_depending_on_dlccore_lights_every_arm() -> None: + every = {name: ["dlccore"] for name, _ in ADOPTERS.values()} + + assert adopting_arms(_installed(**every)) == set(ARM_MEANINGS) + + +def test_head_and_hub_are_kept_and_only_lit_arms_are_kept() -> None: + groups = load_keypoints(keypoints_path()) + assert groups is not None + + kept = shown_groups(groups, frozenset({"arm-2"})) + + assert sorted(group.name for group in kept) == sorted([*ALWAYS_SHOWN, "arm-2"]) + + +def _banner( + monkeypatch: pytest.MonkeyPatch, + arms: frozenset[str], + *, + width: int = 120, + unicode: bool = True, + color: ascii_logo.ColorMode = "never", + version_line: str | None = None, +) -> str: + """The banner on a simulated TTY of `width` columns, with `arms` adopting dlccore.""" + monkeypatch.setattr(ascii_logo, "terminal_is_wide_enough", lambda *_: True) + monkeypatch.setattr(ascii_logo, "get_terminal_width", lambda *_, **__: width) + monkeypatch.setattr(ascii_logo, "_stdout_can_encode", lambda *_: unicode) + monkeypatch.setattr(ascii_logo, "adopting_arms", lambda: arms) + + banner = logo_banner(color=color, version_line=version_line) + + assert banner is not None + return banner + + +def _markers_in_banner(monkeypatch: pytest.MonkeyPatch, arms: frozenset[str]) -> int: + return _banner(monkeypatch, arms).count(KEYPOINT_MARKER) + + +def _labelled_arms(banner: str) -> set[str]: + """Arms whose label appears whole in `banner`; `DLC` does not match inside `DLC-GUI`.""" + return {arm for arm, text in ARM_LABELS.items() if re.search(rf"(? None: + none = _markers_in_banner(monkeypatch, frozenset()) + one = _markers_in_banner(monkeypatch, frozenset({"arm-1"})) + every = _markers_in_banner(monkeypatch, frozenset(ARM_MEANINGS)) + + assert 0 < none < one < every + + +def test_turning_the_toggle_off_draws_every_arm_whatever_is_installed(monkeypatch: pytest.MonkeyPatch) -> None: + every = _markers_in_banner(monkeypatch, frozenset(ARM_MEANINGS)) + monkeypatch.setattr(ascii_logo, "ONLY_ADOPTING_ARMS", False) + + assert _markers_in_banner(monkeypatch, frozenset()) == every + + +def test_a_diagonal_edge_leaves_its_keypoint_on_the_next_row_not_beside_it(monkeypatch: pytest.MonkeyPatch) -> None: + # The keypoint sits near the top of its cell and the edge drops under a row in its first step: the first up-right + # diagonal still belongs below-left of the keypoint, not beside it. + monkeypatch.setattr(ascii_logo, "_stdout_can_encode", lambda *_: True) + group = ascii_logo.KeypointGroup(name="arm-3", color=(0, 0, 0), points=(), lines=(((0.60, 0.511), (0.43, 0.61)),)) + chars = [[" "] * 10 for _ in range(10)] + + chars, _ = ascii_logo._draw_keypoints(chars, [group], (0, 0, 9, 9), (10, 10), aspect=0.5) + + assert chars[5][5] == " " + assert chars[6][5] == UP_RIGHT + + +@pytest.mark.parametrize("width", [60, 80, 120]) +def test_no_diagonal_glyph_sits_right_beside_the_hub(monkeypatch: pytest.MonkeyPatch, width: int) -> None: + monkeypatch.setattr(ascii_logo, "_stdout_can_encode", lambda *_: True) + groups = load_keypoints(keypoints_path()) + chars, colors = ascii_logo._ascii_cells( + ascii_logo.logo_path(), width=width, fine=True, crop_content=True, crop_pad=1, keypoints=groups + ) + hub = next(group for group in groups if group.name == "hub") + row, col = next( + (i, j) + for i, line in enumerate(chars) + for j, ch in enumerate(line) + if ch == KEYPOINT_MARKER and colors[i][j] == hub.color + ) + + assert {chars[row][col - 1], chars[row][col + 1]}.isdisjoint({UP_RIGHT, DOWN_RIGHT}) + + +ANSI = re.compile(r"\x1b\[[0-9;]*m") +NOT_IN_RAMP = "=" + + +def test_every_arm_has_a_label() -> None: + assert set(ARM_LABELS) == {*ADOPTERS, CORE_ARM} + + +@pytest.mark.parametrize("arms", [frozenset(), frozenset({"arm-1", "arm-2"}), frozenset(ADOPTERS)]) +def test_a_label_is_drawn_exactly_by_the_drawn_arms(monkeypatch: pytest.MonkeyPatch, arms: frozenset[str]) -> None: + assert _labelled_arms(_banner(monkeypatch, arms)) == {*arms, CORE_ARM} + + +def test_turning_labels_off_draws_none(monkeypatch: pytest.MonkeyPatch) -> None: + assert _labelled_arms(_banner(monkeypatch, frozenset(ARM_LABELS))) == set(ARM_LABELS) + monkeypatch.setattr(ascii_logo, "SHOW_ARM_LABELS", False) + + assert _labelled_arms(_banner(monkeypatch, frozenset(ARM_LABELS))) == set() + + +def test_labels_never_cover_the_skeleton(monkeypatch: pytest.MonkeyPatch) -> None: + def skeleton(banner: str) -> list[int]: + return [banner.count(glyph) for glyph in EDGE_GLYPHS + KEYPOINT_MARKER] + + labelled = _banner(monkeypatch, frozenset(ARM_LABELS)) + monkeypatch.setattr(ascii_logo, "SHOW_ARM_LABELS", False) + unlabelled = _banner(monkeypatch, frozenset(ARM_LABELS)) + + assert labelled != unlabelled + assert skeleton(labelled) == skeleton(unlabelled) + + +@pytest.mark.parametrize("width", [60, 61, 69, 70, 79, 80, 99, 120]) +def test_every_label_fits_and_no_line_is_wider_than_the_terminal(monkeypatch: pytest.MonkeyPatch, width: int) -> None: + for color in ("never", "always"): + lines = ANSI.sub("", _banner(monkeypatch, frozenset(ARM_LABELS), width=width, color=color)).splitlines() + + assert _labelled_arms("\n".join(lines)) == set(ARM_LABELS) + assert max(len(line) for line in lines) == width # the logo reaches the edge, so the bound is tight + + +def test_colour_on_and_off_carry_the_same_characters(monkeypatch: pytest.MonkeyPatch) -> None: + off = _banner(monkeypatch, frozenset(ARM_LABELS), color="never") + on = _banner(monkeypatch, frozenset(ARM_LABELS), color="always") + + assert on != off + assert [line.rstrip() for line in ANSI.sub("", on).splitlines()] == off.splitlines() + + +def test_the_ascii_fallback_is_pure_ascii_and_keeps_the_labels(monkeypatch: pytest.MonkeyPatch) -> None: + assert not _banner(monkeypatch, frozenset(ARM_LABELS)).isascii() + + banner = _banner(monkeypatch, frozenset(ARM_LABELS), unicode=False) + + assert banner.isascii() + assert banner.splitlines()[-1].strip() == COPYRIGHT_ASCII + assert _labelled_arms(banner) == set(ARM_LABELS) + + +def test_a_label_too_wide_for_the_terminal_is_dropped_not_clipped(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setitem(ARM_LABELS, "arm-1", NOT_IN_RAMP * 20) + assert NOT_IN_RAMP * 20 in _banner(monkeypatch, frozenset({"arm-1"}), width=60) + + monkeypatch.setitem(ARM_LABELS, "arm-1", NOT_IN_RAMP * 61) + banner = _banner(monkeypatch, frozenset({"arm-1"}), width=60) + + assert NOT_IN_RAMP not in banner + assert max(len(line) for line in banner.splitlines()) <= 60 + + +def test_a_label_lands_by_the_last_point_not_the_point_farthest_from_the_hub(monkeypatch: pytest.MonkeyPatch) -> None: + # Cells are (row, column) = (20 y, 40 x): hub at (10, 20), farthest point at (10, 4), last point at (10, 12). + monkeypatch.setattr(ascii_logo, "_stdout_can_encode", lambda *_: True) + points = ((0.45, 0.5), (0.1, 0.5), (0.3, 0.5)) + arm = ascii_logo.KeypointGroup(name="arm-1", color=(0, 0, 0), points=points, lines=(points,)) + hub = ascii_logo.KeypointGroup(name="hub", color=(0, 0, 0), points=((0.5, 0.5),), lines=()) + chars = [[" "] * 40 for _ in range(20)] + + chars, _ = ascii_logo._draw_keypoints( + chars, [arm, hub], (0, 0, 39, 19), (40, 20), aspect=0.5, labels={"arm-1": "abc"} + ) + + row, col = next((i, "".join(line).index("abc")) for i, line in enumerate(chars) if "abc" in "".join(line)) + assert abs(row - 10) <= 1 + assert col == 11 # "abc" is centred on column 12; by the farthest point it would sit near 4 + assert chars[10][12] == KEYPOINT_MARKER + + +def test_the_title_is_drawn_until_switched_off(monkeypatch: pytest.MonkeyPatch) -> None: + assert TITLE_TOP[1] in _banner(monkeypatch, frozenset()) + monkeypatch.setattr(ascii_logo, "SHOW_TITLE", False) + + assert TITLE_TOP[1] not in _banner(monkeypatch, frozenset()) + + +def test_the_version_line_is_drawn_directly_under_the_copyright(monkeypatch: pytest.MonkeyPatch) -> None: + lines = _banner(monkeypatch, frozenset(), version_line="dlccore 1.2.3").splitlines() + + assert [line.strip() for line in lines[-2:]] == [COPYRIGHT, "dlccore 1.2.3"] + + +def test_without_the_copyright_the_version_line_follows_a_blank_row(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(ascii_logo, "SHOW_COPYRIGHT", False) + + lines = _banner(monkeypatch, frozenset(), version_line="dlccore 1.2.3").splitlines() + + assert [line.strip() for line in lines[-2:]] == ["", "dlccore 1.2.3"] + + +def test_the_copyright_is_the_last_line_until_switched_off(monkeypatch: pytest.MonkeyPatch) -> None: + assert _banner(monkeypatch, frozenset()).splitlines()[-1].strip() == COPYRIGHT + monkeypatch.setattr(ascii_logo, "SHOW_COPYRIGHT", False) + + assert COPYRIGHT not in _banner(monkeypatch, frozenset()) + + +def test_the_title_leaves_the_logo_and_its_labels_untouched(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(ascii_logo, "SHOW_COPYRIGHT", False) + monkeypatch.setattr(ascii_logo, "SHOW_TITLE", False) + logo = _banner(monkeypatch, frozenset(ARM_LABELS)).rstrip("\n ").splitlines() + monkeypatch.setattr(ascii_logo, "SHOW_TITLE", True) + + titled = _banner(monkeypatch, frozenset(ARM_LABELS)).splitlines() + + top = len(TITLE_TOP) + 1 + assert _labelled_arms("\n".join(logo)) == set(ARM_LABELS) + assert titled[top : top + len(logo)] == logo + assert [line.strip() for line in titled[-len(TITLE_BOTTOM) :]] == [row.strip() for row in TITLE_BOTTOM] + + +def test_no_arm_label_is_a_placeholder() -> None: + assert not [text for text in ARM_LABELS.values() if text.startswith("[PH]")] diff --git a/tests/project/cli/test_cli.py b/tests/project/cli/test_cli.py new file mode 100644 index 0000000..266d527 --- /dev/null +++ b/tests/project/cli/test_cli.py @@ -0,0 +1,105 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from importlib.metadata import version +from pathlib import Path + +import pytest + +from dlccore.project import cli +from dlccore.project.cli.ascii_logo import DISTRIBUTION + +LINE = f"{DISTRIBUTION} {version(DISTRIBUTION)}" + + +def _version_output( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], banner: object, *argv: str +) -> str: + def fake_banner(**kwargs: object) -> str | None: + if isinstance(banner, Exception): + raise banner + return None if banner is None else f"ART\n{kwargs['version_line']}" + + monkeypatch.setattr(cli, "logo_banner", fake_banner) + assert cli.main(["--version", *argv]) == 0 + return capsys.readouterr().out + + +def test_the_version_is_printed_once_inside_the_banner( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + assert _version_output(monkeypatch, capsys, "banner") == f"ART\n{LINE}\n" + + +@pytest.mark.parametrize( + ("banner", "argv"), + [(None, ()), ("banner", ("--no-art",)), (ImportError("no OpenCV"), ())], + ids=["no-tty-or-too-narrow", "no-art", "logo-unavailable"], +) +def test_without_a_banner_the_version_is_printed_plain( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], banner: object, argv: tuple[str, ...] +) -> None: + assert _version_output(monkeypatch, capsys, banner, *argv) == f"{LINE}\n" + + +def _inspect(capsys: pytest.CaptureFixture[str], *argv: str) -> tuple[int, str, str]: + code = cli.main(["inspect", *argv]) + out, err = capsys.readouterr() + return code, out, err + + +def test_inspect_prints_the_tree_of_a_valid_project(valid_project: Path, capsys: pytest.CaptureFixture[str]) -> None: + code, out, _ = _inspect(capsys, str(valid_project)) + + assert code == 0 + assert "No findings were reported" in out + assert "labeled-data [labeled_data_directory, present]" in out + + +def test_inspect_reports_findings_and_exits_zero_unless_asked_to_fail( + invalid_project: Path, capsys: pytest.CaptureFixture[str] +) -> None: + code, out, _ = _inspect(capsys, str(invalid_project)) + + assert code == 0 + assert "ERROR CONFIG_VALIDATION_ERROR" in out + + +def test_inspect_fails_on_a_blocking_finding_when_asked( + invalid_project: Path, capsys: pytest.CaptureFixture[str] +) -> None: + assert _inspect(capsys, str(invalid_project), "--fail-on-error")[0] == 1 + + +def test_inspect_passes_a_valid_project_when_asked_to_fail_on_errors( + valid_project: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Control: --fail-on-error does not fail every project. + assert _inspect(capsys, str(valid_project), "--fail-on-error")[0] == 0 + + +def test_inspect_prints_findings_as_markdown_with_the_root_redacted( + invalid_project: Path, capsys: pytest.CaptureFixture[str] +) -> None: + code, out, _ = _inspect(capsys, str(invalid_project), "--markdown") + + assert code == 0 + assert "CONFIG_VALIDATION_ERROR" in out + assert "|" in out + assert str(invalid_project) not in out + + +def test_inspect_refuses_a_path_that_is_not_a_project(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + code, out, err = _inspect(capsys, str(tmp_path / "missing")) + + assert code == 2 + assert out == "" + assert "dlc-octopus inspect:" in err