• Stars
    star
    438
  • Rank 95,961 (Top 2 %)
  • Language
    Python
  • License
    MIT License
  • Created over 5 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿฃ A lightweight console printing and formatting toolkit

wasabi: A lightweight console printing and formatting toolkit

Over the years, I've written countless implementations of coloring and formatting utilities to output messages in our libraries like spaCy, Thinc and Prodigy. While there are many other great open-source options, I've always ended up wanting something slightly different or slightly custom.

This package is still a work in progress and aims to bundle those utilities in a standardised way so they can be shared across our other projects. It's super lightweight, has zero dependencies and works with Python 3.6+.

tests PyPi conda GitHub Code style: black

๐Ÿ’ฌ FAQ

Are you going to add more features?

Yes, there's still a few of helpers and features to port over. However, the new features will be heavily biased by what we (think we) need. I always appreciate pull requests to improve the existing functionality โ€“ but I want to keep this library as simple, lightweight and specific as possible.

Can I use this for my projects?

Sure, if you like it, feel free to adopt it! Just keep in mind that the package is very specific and not intended to be a full-featured and fully customisable formatting library. If that's what you're looking for, you might want to try other packages โ€“ for example, colored, crayons, colorful, tabulate, console or py-term, to name a few.

Why wasabi?

I was looking for a short and descriptive name, but everything was already taken. So I ended up naming this package after one of my rats, Wasabi. ๐Ÿ€

โŒ›๏ธ Installation

pip install wasabi

๐ŸŽ› API

function msg

An instance of Printer, initialized with the default config. Useful as a quick shortcut if you don't need to customize initialization.

from wasabi import msg

msg.good("Success!")

class Printer

method Printer.__init__

from wasabi import Printer

msg = Printer()
Argument Type Description Default
pretty bool Pretty-print output with colors and icons. True
no_print bool Don't actually print, just return. False
colors dict Add or overwrite color values, names mapped to 0-256. None
icons dict Add or overwrite icon. Name mapped to unicode. None
line_max int Maximum line length (for divider). 80
animation str Steps of loading animation for Printer.loading. "โ ™โ นโ ธโ ผโ ดโ ฆโ งโ ‡โ "
animation_ascii str Alternative animation for ASCII terminals. "|/-\\"
hide_animation bool Don't display animation, e.g. for logs. False
ignore_warnings bool Don't output messages of type MESSAGE.WARN. False
env_prefix str Prefix for environment variables, e.g. WASABI_LOG_FRIENDLY. "WASABI"
timestamp bool Add timestamp before output. False
RETURNS Printer The initialized printer. -

method Printer.text

msg = Printer()
msg.text("Hello world!")
Argument Type Description Default
title str The main text to print. ""
text str Optional additional text to print. ""
color ย unicode / int Color name or value. None
icon str Name of icon to add. None
show bool Whether to print or not. Can be used to only output messages under certain condition, e.g. if --verbose flag is set. True
spaced bool Whether to add newlines around the output. False
no_print bool Don't actually print, just return. Overwrites global setting. False
exits int If set, perform a system exit with the given code after printing. None

method Printer.good, Printer.fail, Printer.warn, Printer.info

Print special formatted messages.

msg = Printer()
msg.good("Success")
msg.fail("Error")
msg.warn("Warning")
msg.info("Info")
Argument Type Description Default
title str The main text to print. ""
text str Optional additional text to print. ""
show bool Whether to print or not. Can be used to only output messages under certain condition, e.g. if --verbose flag is set. True
exits int If set, perform a system exit with the given code after printing. None

method Printer.divider

Print a formatted divider.

msg = Printer()
msg.divider("Heading")
Argument Type Description Default
text str Headline text. If empty, only the line is printed. ""
char str Single line character to repeat. "="
show bool Whether to print or not. Can be used to only output messages under certain condition, e.g. if --verbose flag is set. True
icon str Optional icon to use with title. None

contextmanager Printer.loading

msg = Printer()
with msg.loading("Loading..."):
    # Do something here that takes longer
    time.sleep(10)
msg.good("Successfully loaded something!")
Argument Type Description Default
text str The text to display while loading. "Loading..."

method Printer.table, Printer.row

See Tables.

property Printer.counts

Get the counts of how often the special printers were fired, e.g. MESSAGES.GOOD. Can be used to print an overview like "X warnings"

msg = Printer()
msg.good("Success")
msg.fail("Error")
msg.warn("Error")

print(msg.counts)
# Counter({'good': 1, 'fail': 2, 'warn': 0, 'info': 0})
Argument Type Description
RETURNS Counter The counts for the individual special message types.

Tables

function table

Lightweight helper to format tabular data.

from wasabi import table

data = [("a1", "a2", "a3"), ("b1", "b2", "b3")]
header = ("Column 1", "Column 2", "Column 3")
widths = (8, 9, 10)
aligns = ("r", "c", "l")
formatted = table(data, header=header, divider=True, widths=widths, aligns=aligns)
Column 1   Column 2    Column 3
--------   ---------   ----------
      a1      a2       a3
      b1      b2       b3
Argument Type Description Default
data iterable / dict The data to render. Either a list of lists (one per row) or a dict for two-column tables.
header iterable Optional header columns. None
footer iterable Optional footer columns. None
divider bool Show a divider line between header/footer and body. False
widths iterable / "auto" Column widths in order. If "auto", widths will be calculated automatically based on the largest value. "auto"
max_col int Maximum column width. 30
spacing int Number of spaces between columns. 3
aligns iterable / unicode Columns alignments in order. "l" (left, default), "r" (right) or "c" (center). If If a string, value is used for all columns. None
multiline bool If a cell value is a list of a tuple, render it on multiple lines, with one value per line. False
env_prefix unicode Prefix for environment variables, e.g. WASABI_LOG_FRIENDLY. "WASABI"
color_values dict Add or overwrite color values, name mapped to value. None
fg_colors iterable Foreground colors, one per column. None can be specified for individual columns to retain the default background color. None
bg_colors iterable Background colors, one per column. None can be specified for individual columns to retain the default background color. None
RETURNS str The formatted table.

function row

from wasabi import row

data = ("a1", "a2", "a3")
formatted = row(data)
a1   a2   a3
Argument Type Description Default
data iterable The individual columns to format.
widths list / int / "auto" Column widths, either one integer for all columns or an iterable of values. If "auto", widths will be calculated automatically based on the largest value. "auto"
spacing int Number of spaces between columns. 3
aligns list Columns alignments in order. "l" (left), "r" (right) or "c" (center). None
env_prefix unicode Prefix for environment variables, e.g. WASABI_LOG_FRIENDLY. "WASABI"
fg_colors list Foreground colors for the columns, in order. None can be specified for individual columns to retain the default foreground color. None
bg_colors list Background colors for the columns, in order. None can be specified for individual columns to retain the default background color. None
RETURNS str The formatted row.

class TracebackPrinter

Helper to output custom formatted tracebacks and error messages. Currently used in Thinc.

method TracebackPrinter.__init__

Initialize a traceback printer.

from wasabi import TracebackPrinter

tb = TracebackPrinter(tb_base="thinc", tb_exclude=("check.py",))
Argument Type Description Default
color_error str / int Color name or code for errors (passed to color helper). "red"
color_tb str / int Color name or code for traceback headline (passed to color helper). "blue"
color_highlight str / int Color name or code for highlighted text (passed to color helper). "yellow"
indent int Number of spaces to use for indentation. 2
tb_base str Name of directory to use to show relative paths. For example, "thinc" will look for the last occurence of "/thinc/" in a path and only show path to the right of it. None
tb_exclude tuple List of filenames to exclude from traceback. tuple()
RETURNS TracebackPrinter The traceback printer.

method TracebackPrinter.__call__

Output custom formatted tracebacks and errors.

from wasabi import TracebackPrinter
import traceback

tb = TracebackPrinter(tb_base="thinc", tb_exclude=("check.py",))

error = tb("Some error", "Error description", highlight="kwargs", tb=traceback.extract_stack())
raise ValueError(error)
  Some error
  Some error description

  Traceback:
  โ”œโ”€ <lambda> [61] in .env/lib/python3.6/site-packages/pluggy/manager.py
  โ”œโ”€โ”€โ”€ _multicall [187] in .env/lib/python3.6/site-packages/pluggy/callers.py
  โ””โ”€โ”€โ”€โ”€โ”€ pytest_fixture_setup [969] in .env/lib/python3.6/site-packages/_pytest/fixtures.py
         >>> result = call_fixture_func(fixturefunc, request, kwargs)
Argument Type Description Default
title str The message title.
*texts str Optional texts to print (one per line).
highlight str Optional sequence to highlight in the traceback, e.g. the bad value that caused the error. False
tb iterable The traceback, e.g. generated by traceback.extract_stack(). None
RETURNS str The formatted traceback. Can be printed or raised by custom exception.

class MarkdownRenderer

Helper to create Markdown-formatted content. Will store the blocks added to the Markdown document in order.

from wasabi import MarkdownRenderer

md = MarkdownRenderer()
md.add(md.title(1, "Hello world"))
md.add("This is a paragraph")
print(md.text)

method MarkdownRenderer.__init__

Initialize a Markdown renderer.

from wasabi import MarkdownRenderer

md = MarkdownRenderer()
Argument Type Description Default
no_emoji bool Don't include emoji in titles. False
RETURNS MarkdownRenderer The renderer.

method MarkdownRenderer.add

Add a block to the Markdown document.

from wasabi import MarkdownRenderer

md = MarkdownRenderer()
md.add("This is a paragraph")
Argument Type Description Default
text str The content to add.

property MarkdownRenderer.text

The rendered Markdown document.

md = MarkdownRenderer()
md.add("This is a paragraph")
print(md.text)
Argument Type Description Default
RETURNS str The document as a single string.

method MarkdownRenderer.table

Create a Markdown-formatted table.

md = MarkdownRenderer()
table = md.table([("a", "b"), ("c", "d")], ["Column 1", "Column 2"])
md.add(table)
| Column 1 | Column 2 |
| --- | --- |
| a | b |
| c | d |
Argument Type Description Default
data Iterable[Iterable[str]] The body, one iterable per row, containig an interable of column contents.
header Iterable[str] The column names.
aligns Iterable[str] Columns alignments in order. "l" (left, default), "r" (right) or "c" (center). None
RETURNS str The table.

method MarkdownRenderer.title

Create a Markdown-formatted heading.

md = MarkdownRenderer()
md.add(md.title(1, "Hello world"))
md.add(md.title(2, "Subheading", "๐Ÿ’–"))
# Hello world

## ๐Ÿ’– Subheading
Argument Type Description Default
level int The heading level, e.g. 3 for ###.
text str The heading text.
emoji str Optional emoji to show before heading. None
RETURNS str The rendered title.

method MarkdownRenderer.list

Create a Markdown-formatted non-nested list.

md = MarkdownRenderer()
md.add(md.list(["item", "other item"]))
md.add(md.list(["first item", "second item"], numbered=True))
- item
- other item

1. first item
2. second item
Argument Type Description Default
items Iterable[str] The list items.
numbered bool Whether to use a numbered list. False
RETURNS str The rendered list.

method MarkdownRenderer.link

Create a Markdown-formatted link.

md = MarkdownRenderer()
md.add(md.link("Google", "https://google.com"))
[Google](https://google.com)
Argument Type Description Default
text str The link text.
url str The link URL.
RETURNS str The rendered link.

method MarkdownRenderer.code_block

Create a Markdown-formatted code block.

md = MarkdownRenderer()
md.add(md.code_block("import spacy", "python"))
```python
import spacy
```
Argument Type Description Default
text str The code text.
lang str Optional code language. ""
RETURNS str The rendered code block.

method MarkdownRenderer.code, MarkdownRenderer.bold, MarkdownRenderer.italic

Create a Markdown-formatted text.

md = MarkdownRenderer()
md.add(md.code("import spacy"))
md.add(md.bold("Hello!"))
md.add(md.italic("Emphasis"))
`import spacy`

**Hello!**

_Emphasis_

Utilities

function color

from wasabi import color

formatted = color("This is a text", fg="white", bg="green", bold=True)
Argument Type Description Default
text str The text to be formatted. -
fg str / int Foreground color. String name or 0 - 256. None
bg str / int Background color. String name or 0 - 256. None
bold bool Format the text in bold. False
underline bool Format the text by underlining. False
RETURNS str The formatted string.

function wrap

from wasabi import wrap

wrapped = wrap("Hello world, this is a text.", indent=2)
Argument Type Description Default
text str The text to wrap. -
wrap_max int Maximum line width, including indentation. 80
indent int Number of spaces used for indentation. 4
RETURNS str The wrapped text with line breaks.

function diff_strings

from wasabi import diff_strings

diff = diff_strings("hello world!", "helloo world")
Argument Type Description Default
a str The first string to diff.
b str The second string to diff.
fg str / int Foreground color. String name or 0 - 256. "black"
bg tuple Background colors as (insert, delete) tuple of string name or 0 - 256. ("green", "red")
RETURNS str The formatted diff.

Environment variables

Wasabi also respects the following environment variables. The prefix can be customised on the Printer via the env_prefix argument. For example, setting env_prefix="SPACY" will expect the environment variable SPACY_LOG_FRIENDLY.

Name Description
ANSI_COLORS_DISABLED Disable colors.
WASABI_LOG_FRIENDLY Make output nicer for logs (no colors, no animations).
WASABI_NO_PRETTY Disable pretty printing, e.g. colors and icons.

๐Ÿ”” Run tests

Fork or clone the repo, make sure you have pytest installed and then run it on the package directory. The tests are located in /wasabi/tests.

pip install pytest
cd wasabi
python -m pytest wasabi

More Repositories

1

spaCy

๐Ÿ’ซ Industrial-strength Natural Language Processing (NLP) in Python
Python
28,700
star
2

thinc

๐Ÿ”ฎ A refreshing functional take on deep learning, compatible with your favorite libraries
Python
2,777
star
3

spacy-course

๐Ÿ‘ฉโ€๐Ÿซ Advanced NLP with spaCy: A free online course
Python
2,268
star
4

sense2vec

๐Ÿฆ† Contextually-keyed word vectors
Python
1,595
star
5

spacy-models

๐Ÿ’ซ Models for the spaCy Natural Language Processing (NLP) library
Python
1,516
star
6

spacy-transformers

๐Ÿ›ธ Use pretrained transformers like BERT, XLNet and GPT-2 in spaCy
Python
1,318
star
7

projects

๐Ÿช End-to-end NLP workflows from prototype to production
Python
1,249
star
8

spacy-llm

๐Ÿฆ™ Integrating LLMs into structured NLP pipelines
Python
950
star
9

curated-transformers

๐Ÿค– A PyTorch library of curated Transformer models and their composable components
Python
837
star
10

spacy-streamlit

๐Ÿ‘‘ spaCy building blocks and visualizers for Streamlit apps
Python
765
star
11

spacy-stanza

๐Ÿ’ฅ Use the latest Stanza (StanfordNLP) research models directly in spaCy
Python
715
star
12

prodigy-recipes

๐Ÿณ Recipes for the Prodigy, our fully scriptable annotation tool
Jupyter Notebook
464
star
13

cymem

๐Ÿ’ฅ Cython memory pool for RAII-style memory management
Cython
434
star
14

srsly

๐Ÿฆ‰ Modern high-performance serialization utilities for Python (JSON, MessagePack, Pickle)
Python
414
star
15

displacy

๐Ÿ’ฅ displaCy.js: An open-source NLP visualiser for the modern web
JavaScript
344
star
16

lightnet

๐ŸŒ“ Bringing pjreddie's DarkNet out of the shadows #yolo
C
319
star
17

prodigy-openai-recipes

โœจ Bootstrap annotation with zero- & few-shot learning via OpenAI GPT-3
Python
315
star
18

spacy-notebooks

๐Ÿ’ซ Jupyter notebooks for spaCy examples and tutorials
Jupyter Notebook
284
star
19

spacy-services

๐Ÿ’ซ REST microservices for various spaCy-related tasks
Python
239
star
20

cython-blis

๐Ÿ’ฅ Fast matrix-multiplication as a self-contained Python library โ€“ no system dependencies!
C
209
star
21

displacy-ent

๐Ÿ’ฅ displaCy-ent.js: An open-source named entity visualiser for the modern web
CSS
196
star
22

jupyterlab-prodigy

๐Ÿงฌ A JupyterLab extension for annotating data with Prodigy
TypeScript
187
star
23

tokenizations

Robust and Fast tokenizations alignment library for Rust and Python https://tamuhey.github.io/tokenizations/
Rust
179
star
24

spacymoji

๐Ÿ’™ Emoji handling and meta data for spaCy with custom extension attributes
Python
177
star
25

wheelwright

๐ŸŽก Automated build repo for Python wheels and source packages
Python
173
star
26

catalogue

Super lightweight function registries for your library
Python
170
star
27

confection

๐Ÿฌ Confection: the sweetest config system for Python
Python
165
star
28

spacy-dev-resources

๐Ÿ’ซ Scripts, tools and resources for developing spaCy
Python
125
star
29

radicli

๐Ÿ•Š๏ธ Radically lightweight command-line interfaces
Python
96
star
30

spacy-experimental

๐Ÿงช Cutting-edge experimental spaCy components and features
Python
93
star
31

spacy-lookups-data

๐Ÿ“‚ Additional lookup tables and data resources for spaCy
Python
93
star
32

talks

๐Ÿ’ฅ Browser-based slides or PDFs of our talks and presentations
JavaScript
90
star
33

thinc-apple-ops

๐Ÿ Make Thinc faster on macOS by calling into Apple's native Accelerate library
Cython
89
star
34

healthsea

Healthsea is a spaCy pipeline for analyzing user reviews of supplementary products for their effects on health.
Python
84
star
35

preshed

๐Ÿ’ฅ Cython hash tables that assume keys are pre-hashed
Cython
78
star
36

spacy-huggingface-pipelines

๐Ÿ’ฅ Use Hugging Face text and token classification pipelines directly in spaCy
Python
57
star
37

spacy-ray

โ˜„๏ธ Parallel and distributed training with spaCy and Ray
Python
53
star
38

ml-datasets

๐ŸŒŠ Machine learning dataset loaders for testing and example scripts
Python
45
star
39

assets

๐Ÿ’ฅ Explosion Assets
43
star
40

murmurhash

๐Ÿ’ฅ Cython bindings for MurmurHash2
C++
42
star
41

weasel

๐Ÿฆฆ weasel: A small and easy workflow system
Python
41
star
42

spacy-huggingface-hub

๐Ÿค— Push your spaCy pipelines to the Hugging Face Hub
Python
39
star
43

vscode-prodigy

๐Ÿงฌ A VS Code extension for annotating data with Prodigy
TypeScript
29
star
44

wikid

Generate a SQLite database from Wikipedia & Wikidata dumps.
Python
26
star
45

spacy-alignments

๐Ÿ’ซ A spaCy package for Yohei Tamura's Rust tokenizations library
Python
26
star
46

spacy-vscode

spaCy extension for Visual Studio Code
Python
23
star
47

spacy-benchmarks

๐Ÿ’ซ Runtime performance comparison of spaCy against other NLP libraries
Python
20
star
48

spacy-curated-transformers

spaCy entry points for Curated Transformers
Python
19
star
49

prodigy-hf

Train huggingface models on top of Prodigy annotations
Python
17
star
50

spacy-vectors-builder

๐ŸŒธ Train floret vectors
Python
15
star
51

os-signpost

Wrapper for the macOS signpost API
Cython
11
star
52

prodigy-pdf

A Prodigy plugin for PDF annotation
Python
11
star
53

spacy-loggers

๐Ÿ“Ÿ Logging utilities for spaCy
Python
11
star
54

prodigy-evaluate

๐Ÿ”Ž A Prodigy plugin for evaluating spaCy pipelines
Python
11
star
55

prodigy-segment

Select pixels in Prodigy via Facebook's Segment-Anything model.
Python
10
star
56

curated-tokenizers

Lightweight piece tokenization library
Cython
10
star
57

conll-2012

A slightly cleaned up version of the scripts & data for the CoNLL 2012 Coreference task.
Python
10
star
58

thinc_gpu_ops

๐Ÿ”ฎ GPU kernels for Thinc
C++
9
star
59

princetondh

Code for our presentation in Princeton DH 2023 April.
Jupyter Notebook
4
star
60

spacy-legacy

๐Ÿ•ธ๏ธ Legacy architectures and other registered spaCy v3.x functions for backwards-compatibility
Python
4
star
61

prodigy-ann

A Prodigy pluging for ANN techniques
Python
3
star
62

prodigy-whisper

Audio transcription with OpenAI's whisper model in the loop.
Python
3
star
63

ec2buildwheel

Python
2
star
64

aiGrunn-2023

Materials for the aiGrunn 2023 talk on spaCy Transformer pipelines
Python
1
star
65

spacy-io-binder

๐Ÿ“’ Repository used to build Binder images for the interactive spaCy code examples
Jupyter Notebook
1
star
66

prodigy-lunr

A Prodigy plugin for document search via LUNR
Python
1
star
67

.github

:octocat: GitHub settings
1
star
68

span-labeling-datasets

Loaders for various span labeling datasets
Python
1
star