# Ansy
[![GitHub Repository](https://img.shields.io/badge/-GitHub-%230D0D0D?logo=github&labelColor=gray)](https://github.com/anas-shakeel/ansy)
[![Latest PyPi version](https://img.shields.io/pypi/v/ansy.svg)](https://pypi.python.org/pypi/ansy)
[![supported Python versions](https://img.shields.io/pypi/pyversions/ansy)](https://pypi.python.org/pypi/ansy)
[![Project licence](https://img.shields.io/pypi/l/ansy?color=blue)](LICENSE)
[![Black](https://img.shields.io/badge/code%20style-black-000000.svg)](black)
[![Automated testing results](https://img.shields.io/github/actions/workflow/status/anas-shakeel/ansy/.github/workflows/python-package.yml?branch=main)](https://github.com/anas-shakeel/ansy/actions/workflows/python-package.yml?query=branch%3Amain)
[![PyPI downloads](https://img.shields.io/pypi/dm/ansy.svg)](https://pypistats.org/packages/ansy)
`ansy` (pronounced __ANSI__), inspired by (& successor to) `termcolor` module that is used to style and format output in the terminal.
It is was a part of another module i'v recently released called [Pinsy](https://pypi.org/project/pinsy), but i thought why not release it as it's own standalone module. So, Here it is.
### ▎ Features
- Colorize a string using 3 color modes (`4-bit`, `8-bit`, `24-bit`)
- Colorize selective parts of a string
- Colorize a string using random colors.
- Apply Gradients to strings.
- Format a string using attributes such as `bold`, `italic`, `underline`, and __7__ more
- Strip away ANSI Codes from a string
- Access to widely used colors
- No external dependencies
- Easy to use API
- All of this under `90kb` *(and much of it is occupied by `docstrings`, `type annotations` and `hex colors`)*
### ▎ Setup & Installation
``` shell
pip install ansy
```
You may also need to install `colorama` (*__windows__ users only*).
### ▎ From `termcolor` to `ansy`
If your code uses `termcolor` and you want to shift to `ansy`, you can safely replace the `colored` function of `termcolor` with the `colored` function of `ansy`.
```py
from ansy import colored
colored('This is ansy.', 'light_red', 'dark_grey', ['bold', 'underline'])
# Argument names for color & on_color have been changed to fgcolor & bgcolor
colored(text='this is ansy with kw-args', fgcolor='light_red', bgcolor='dark_grey', attrs=['bold'])
```
## ▎ USAGE
Using `ansy` is very easy.
### Coloring a string:
Use the `colored` function, if you want to colorize a string.
```py
from ansy import colored
# Bold Red text on a White background
red_white = colored('This is a string', 'red', 'white', attrs=['bold'])
print(red_white)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 1.png" />
</p>
Leaving an argument empty uses the default `None` value which disables that formatting.
```py
# Red text with default background and no attributes
red = ansy.colored('This is a string', 'red')
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 2.png" />
</p>
This method also takes an extra `color_mode` argument, which specifies the color mode you want to use.
```py
# Underlined Text with 215 (brown_sandy) FG and 183 (grey_9) BG.
formatted = colored('This is a string', 215, 240, ['underline'], color_mode=8)
print(formatted)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 3.png" />
</p>
`color_mode` can only be one of below:
- `4` to use 4 bit colors
- `8` to use 8 bit colors
- `24` to use 24 bit colors
Notice i've also changed the colors to some codes. These codes belong to the `8-bit` color system and they range from `0` to `255`.
You can also use color names instead of codes.
```py
# Underlined Text with brown_sandy FG and grey_9 BG.
formatted = colored('This is a string', 'brown_sandy', 'grey_9', ['underline'], 8)
```
You can get these colors using `get_all_colors` function, which yields a tuple containing color name and code on each iteration.
```py
# Iterates through and prints all colors from 8-bit colorsystem
for name, code in ansy.get_all_colors():
print(name, code)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 4 get_all_colors.png" />
</p>
Or you can just call `print_all_colors()`, which prints these color names, their code and the color they represent.
```py
ansy.print_all_colors()
# Outputs similar to below, but colored
# ▓▓▓▓▓▓ 0: black
# ▓▓▓▓▓▓ 1: red
# ▓▓▓▓▓▓ 2: green
# --snip--
# ▓▓▓▓▓▓ 255: grey_24
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 5 print_all_colors.png" />
</p>
Modern terminals also support RGB colors which offer a much much more wider range of colors *(approx. 16.7 million colors)*. Now you have the ability to use any color you like *(provided if the terminal supports)*
```py
# Red Italic Text on a White background
fg = (255,100,100)
bg = (215,215,215)
colored('This is a string', fg, bg, ['italic'], 24)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 6.png" />
</p>
`24-bit` color system accepts **RGB** tuple as well as **Hex** color codes.
```py
# Red Italic Text on a White background
fg = '#FF6464'
bg = '#D7D7D7'
colored('This is a string', fg, bg, ['italic'], 24)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 6.png" />
</p>
You can also use `printc()` function with same arguments as of `colored()` to just print the result of `colored()` instead of returning the formatted string.
```py
from ansy import printc
printc('Print this string after formatting.', fgcolor='plum', attrs=['italic'], color_mode=8)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 7.png" />
</p>
Similar to `c_print()` function of `termcolor`, only slightly easier to type.
### Coloring selective parts of a string:
`colored()` formats the whole string. And so if you wanted to apply formatting to a selective part of a string you would normally have to do it like this:
```py
# Formatting the name part and leaving the rest as is
formatted_world = colored('World', fgcolor='purple', attrs=['bold'], color_mode=8)
print(f"Hello, {formatted_world}!")
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_selective 1.png" />
</p>
What if you wanted to set a different color for `"Hello"` too?
```py
formatted_hello = colored('Hello', fgcolor='orange', color_mode=8)
formatted_world = colored('World', fgcolor='purple', attrs=['bold'], color_mode=8)
print(f"{formatted_hello}, {formatted_world}")
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_selective 2.png" />
</p>
You could imagine where this is going, right?
The solution to this problem is `colored_ansy()` function. It adds the styling defined in `style` dictionary to wherever an `ansy string` is found in the whole string.
**What is an Ansy String?**
An ansy string is simply a syntax that allows you to apply a specific styling or formatting to any part of the text they want.
> An `Ansy String` starts with a `@` followed by the name of the style (defined by the `style` dict), and the text in backets `[text]` to which they want to apply the formatting.
>
> ```py
> ansy_string = "This is an @my_style[ansy string]"
> ```
**What is Style Dict?**
`Style dict` is a dictionary which defines the style(s) to apply to these ansy strings. Each style in the `style` dictionary is itself a dictionary.
Purpose of this structure is so that you could define all your styles in one dictionary and then use it everywhere, instead of creating a dictioanry for each style and create a mess in your code.
**Structure of Style Dict:**
```py
style = {
"my_style": {
"colormode": 8,
"fgcolor": "light_red",
"bgcolor": 255,
"attrs": ['bold', 'italic']
}
}
```
Every key in this `style` dictionary is the name of the style that you're gonna use in the `ansy strings`.
Each style must have 4 `key:value` pairs.
- `color_mode`: the color mode to use (`4`, `8`, `24`)
- `fgcolor`: the foreground color of the style
- `bgcolor`: the background color of the style
- `attrs`: the attributes to apply
One thing to note here, `color_mode` decides which color mode to use and you should provide a color supported by that mode. for example, if using `4` bit color mode, provide a color that is a valid 4-bit color. If using `8` bit, provide a color from `256` color system. For color mode `24`, provide an `RGBTuple` or a `Hex` color code.
Back to our problem.
```py
from ansy import colored_ansy
# Define styles
style = {
"orange": {
"color_mode": 8,
"fgcolor": 'orange',
"bgcolor": None,
"attrs": None
},
"purple": {
"color_mode": 8,
"fgcolor": 'purple',
"bgcolor": None,
"attrs": ['bold']
}}
formatted = colored_ansy("@orange[Hello] @purple[World]", style)
print(formatted)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_selective 2.png" />
</p>
You must be thinking, wow! what a solution. we now have to write even more lines of code, right?
Well yeah! but only if you do it manually. there is a function in called `create_style()` which makes it easier to define styles.
```py
from ansy import colored_ansy, create_style
# Create styles
style = {
"orange": create_style(8, fgcolor='orange'),
"purple": create_style(8, fgcolor='purple', attrs=['bold'])
}
formatted = colored_ansy("@orange[Hello] @purple[World]", style)
print(formatted)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_selective 2.png" />
</p>
Still more code, but it's just a one time thing! now you can use `orange` and `purple` style to format as many parts as you want.
This below example hides some parts of text using `concealed` attribute.
```py
# Reusing Styles
style['hide'] = create_style(attrs=['concealed'])
formatted = ansy.colored_ansy('Hide this @hide[..], & this @hide[++], but not this @hide[**]', style)
print(formatted) # Output: Hide this , & this , but not this **
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_selective 3.png" />
</p>
Note that `concealed` attribute does not remove/delete the text, it only hides it visually.
### Applying Gradients:
Horizontal Gradients can be applied to the foreground of a string using two **24-bit** Colors using the `colored_gradient()` function.
```py
# Gradient (left-to-right) using Red and Blue colors
from ansy import colored_gradient
formatted = colored_gradient('This is ansy.', (255,100,100), (100,50,200))
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_gradient 1.png" />
</p>
This method takes in `5` argument:
- `text`: the text to apply the gradient to
- `start_color`: starting foreground rgb color
- `end_color`: ending foreground rgb color
- `quality`: quality of the gradient
> can be set to `high`, `medium` or `low`
- `reverse` reverse the gradient to be (right to left) instead.
Currently, this method only supports horizontal gradients, not vertical ones. but you can fake vertical gradients by introducing newline characters `\n` in your string.
```py
text = "This is text is \ngoing to be used \nto create or fake \na vertical gradient."
print(colored_gradient(text, '#00ffff','#b00b1e'))
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_gradient 2.png" />
</p>
It still is horizontal gradient but it would appear as if it's a vertical gradient. *(well, technically diagonal)*
### Random Colors:
Coloring strings in your application using random colors may not be the best thing to do. but it's there if you need.
```py
from ansy import colored_random
formatted = colored_random('Random Random, Evil Phantom!')
print(formatted)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_random 1.png" />
</p>
By default, this method choose a random color from `4-bit` colorsystem. but you can change the `color_mode` to `8` or `24` to use those colors.
```py
colored_random('text', color_mode=24)
```
This method takes `6` arguments:
- `text`: the text string
- `target`: how to apply random colors
- `chars`: apply a random color to each character of text
- `words`: apply a random color to each word of text
- `all`: apply a random color to whole text **(default)**
- `color_mode`: the color mode to use
- `custom_palette`: choose colors randomly only from this list of colors
- `attrs`: the attributes to apply
- `random_attrs`: randomize the attributes too
You can also choose a `target` to apply random colors to.
```py
print(colored_random('Apply random colors to each word', target='words'))
print(colored_random('Apply random colors to each character', target='chars'))
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_random 2.png" />
</p>
You can pass a list of colors that you like, to `custom_palette` and this method then, will only choose colors from that list.
```py
palette = ["#69D2E7","#A7DBD8","#E0E4CC","#F38630","#FA6900"]
colored_random('Not so random palette.', custom_palette=palette, target="words", color_mode=24)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_random 3.png" />
</p>
You can add colors from any color system into the `palette` list, but then make sure to set that color mode too.
### De-ansifying a string containing ANSI Codes:
If you want to remove all `ANSI Escape Codes` from a string, you can use the `de_ansi` function.
```py
from ansy import colored, de_ansi
ansi_string = colored('This string contains ANSI', 'light_blue', 'dark_grey', ['italic'])
clean_string = de_ansi(ansi_string)
print([ansi_string]) # Output: ['\x1b[3m\x1b[100m\x1b[94mThis string contains ANSI\x1b[0m']
print([clean_string]) # Output: ['This string contains ANSI']
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/deansi 1.png" />
</p>
Notice how i am printing the strings, this is a neat little trick to check if a string contains `ANSI Codes` .
By simply printing a string containing `ANSI`, you won't be able to see the **ANSI Escape Code** because, well, they are escaped. `print([ansi_string])` just prints the contents of a list and the `ANSI Codes` do not **"ESCAPE"** this way.
Also you can write out the strings in a text file. that method works too.
### Widely Used Colors:
Ansy includes `24-bit` colors to be used in your applications. These colors include:
- `19` **Google's Material Colors** (with `14` different shades in each)
- `140` **Web/HTML Colors**
- `200` **Color Palettes** (with `5` colors in each)
You can get these colors using the `colors` module within the `ansy` package.
```py
from ansy import colors
```
This module contains `4` functions:
- `get_material_color()`: Takes in a `color` string and returns all shades of that color from **Material Colors**.
- `get_palettes()`: Returns a generator iterator, which yields a list of colors on each iteration.
- `get_random_palette()`: Returns a random palette from **Color Palettes**.
- `get_web_colors()`: Returns a generator iterator, which yields dictionaries of colors from **Web/HTML Colors**.
All **Material Colors** are tabulated in the **Useful to know** section with their names and shades.
```py
from ansy import colors
# Material colors
materials = colors.get_material_color("red")
print(materials)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/material_colors.png" />
</p>
Output is pretty-printed using [Pinsy](https://github.com/anas-shakeel/pinsy) package.
Get **Web Colors** like this:
```py
for color in colors.get_web_colors():
print(color)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/web_colors.png" />
</p>
And **Palettes** like this:
```py
for palette in colors.get_palettes():
print(palette)
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/palettes.png" />
</p>
And Get a random palette from these **Palettes** likes this:
```py
print(colors.get_random_palette())
```
<p align="center">
<img src="https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/palette random.png" />
</p>
## ▎ ANSY API
`colored(text, fgcolor=None, bgcolor=None, attrs=None, color_mode=4, no_color=None, force_color=None)`
Colorize text using `4`, `8`, or `24` bit colors. If `fgcolor`, `bgcolor`, and `attrs` all are `None`, the `text` itself is returned without any ansi codes added.
> ### Parameters:
>
> - `text`: the text to colorize
>
> - `fgcolor`: the foreground color
>
> - `bgcolor`: the background color
>
> - `attrs`: the attributes to apply
>
> - `color_mode`: the colormode to use (defualt is `4`)
>
> ### Returns:
>
> Formatted string.
>
> ### Exceptions:
>
> Raises `ColorModeError` if:
>
> - `color_mode` is invalid
>
> Raises `InvalidColorError` if:
>
> - `fgcolor` is invalid
>
> - `bgcolor` is invalid
>
> Raises `AttributeError` if:
>
> - `attrs` contain an invalid attribute
`colored_ansy(text, style, no_color=None, force_color=None)`
Adds the styling defined in `style` to wherever an `ansy string` is found in the `text`.
> ### Parameters:
>
> - `text`: the text containing the `ansy strings`
>
> - `style`: a dictionary containing the style(s).
>
> ### Returns:
>
> Formatted string.
>
> ### Exceptions:
>
> Raises `StyleError` if:
>
> - style name used in `ansy string` not found in `style` dict
>
> Raises `ColorModeError` if:
>
> - `color_mode` provided in style, is invalid
`colored_gradient(text, start_color=None, end_color=None, quality='medium', reverse=False)`
Apply horizontal gradient on `text`. This method uses `24-bit` color system.
> ### Parameters:
>
> - `text`: the text to apply the gradient to
> - `start_color`: starting foreground color (`RGBTuple` or `Hex code`)
> - `end_color`: ending foreground color (`RGBTuple` or `Hex code`)
> - `quality`: quality of the gradient (`high`, `medium`, or `low`)
> - `reverse`: reverses the gradient to be (right to left) instead.
>
> ### Returns:
>
> Formatted string.
>
> ### Exceptions:
>
> Raises `InvalidColorError` if:
>
> - `start_color` is an invalid `24-bit` color
>
> - `end_color` is an invalid `24-bit` color
>
> Raises `AssertionError` if:
>
> - `quality` is not set to `high`, `medium`, or `low`
`colored_random(text, target='all', color_mode=4, custom_palette=None, attrs=None, random_attrs=False)`
Apply a random color to `text`. colors are chosen from a colorsystem specified by `color_mode`.
> ### Parameters:
>
> - `text`: the text string
> - `target`: apply random colors to `chars`, `words` or `all` string.
> - `color_mode`: the colormode to use
> - `custom_palette`: choose colors only from this iterable of user-defined colors
> - `attrs`: the attributes to apply (attributes are **NOT** randomized by default)
> - `random_attrs`: randomize the attributes too.
>
> ### Returns:
>
> Formatted string.
>
> ### Exceptions:
>
> Raises `ValueError` if:
>
> - `target` is not set to `chars`, `words`, `all`
>
> Raises `ColorModeError` if:
>
> - `color_mode` is invalid
>
> Raises `InvalidColorError` if:
>
> - `custom_palette` contains an invalid color
>
> Raises `AttributeError` if:
>
> - `attrs` contains an invalid attribute
`colorname_to_code(color)`
Returns the `code` for the `color` name from `8-bit` color system. Returns `None` if `color` is not a valid color name.
> ### Parameters:
>
> - `color_name`: name of a color (from`8-bit` color system)
>
> ### Returns:
>
> Color `code` or `None`
`code_to_colorname(code)`
Returns the color name for the `code`. Returns `None` if `code` is not a valid color.
> ### Parameters:
>
> - `code`: code of a color (from `8-bit` color system **i.e. [0-255]**)
>
> ### Returns:
>
> Color `name` or `None`
`contains_ansi(text)`
Returns `True` if `text` contains Ansi codes, else `False`.
> ### Parameters:
>
> - `text`: the text string to check
>
> ### Returns:
>
> bool
`create_style(color_mode=4, fgcolor=None, bgcolor=None, attrs=None)`
Creates a style `dict` to use in `colored_ansy()` as style.
> ### Parameters:
>
> - `color_mode`: the color mode (`4-bit`, `8-bit`, `24-bit`)
>
> - `4` means use 4-bit colors (`16` Standard colors)
>
> - `8` means use 8-bit colors (`256` colors)
>
> - `24` means use 24-bit colors (approx. `16.7 million` colors)
>
> - `fgcolor` the foreground color
>
> - `bgcolor` the foreground color
>
> - `attrs` the attributes list
>
> ### Returns:
>
> Style `dict`
>
> ### Exceptions:
>
> Raises `InvalidColorError` if:
>
> - `fgcolor` is not a valid color
>
> - `bgcolor` is not a valid color
>
> Raises `ColorModeError` if:
>
> - `color_mode` is invalid
>
> Raises `AttributeError` if:
>
> - `attrs` includes an invalid attribute string
`create_random_palette(color_mode, n)`
Returns a list of `n` colors from `color_mode`-bit color system.
> ### Parameters:
>
> - `color_mode`: the colormode to use
> - `n`: number of colors to include in palette
>
> ### Returns:
>
> `list` of colors
>
> ### Exceptions:
>
> Raises `TypeError` if:
>
> - `n`: is not an integer
`de_ansi(text)`
Removes all `ANSI Codes` from given string.
> ### Parameters:
>
> - `text` the text to remove ANSI codes from.
>
> ### Returns:
>
> De-ansified string.
>
> ### Exceptions:
>
> Raises `TypeError` if:
>
> - `text` is not a `str`
`get_all_colors(sort_by_name=False)`
Yields a `tuple` of `color_name` and it's `code`. (sorted by `code`)
> ### Parameters:
>
> - `sort_by_name`: Sorts colors by name (default is `False` which sorts by code)
>
> ### Returns:
>
> Generator obect.
`get_random_color(color_mode=4)`
Returns a random color from a colorsystem specified by `color_mode`.
> ### Parameters:
>
> - `color_mode`: the color system to use to choose random color from
>
> ### Returns:
>
> Color name `str`, or rgb `tuple`
>
> ### Exceptions:
>
> Raises `ColorModeError` if:
>
> - `color_mode` is invalid.
`hex_to_rgb(hexcode)`
Converts `hexcode` into an `RGBTuple`. It is case-insensitive and also recognizes shorter hex codes e.g `#FFF`, `#9ca` etc.
> ### Parameters:
>
> - `hexcode`: a hex color code string
>
> ### Returns:
>
> RGB tuple.
`is_valid_attr(attr)`
Returns `True` if `attr` is a valid Attribute, else `False`.
> ### Parameters:
>
> - `attr`: the attribute string
>
> ### Returns:
>
> Boolean
`is_valid_color(color, color_mode)`
Validates the color based on `color_mode`. Returns `True` if color is valid, `False` otherwise.
> ### Parameters:
>
> - `color`: a color from `4`, `8` or `24`-bit color system
> - `color_mode`: the color mode of `color` (can be one of `4`, `8`, `24`)
>
> ### Returns:
>
> Boolean
`is_valid_hex(hexcode)`
Returns `True` if `hexcode` is valid, else `False`.
> ### Parameters:
>
> - `hexcode`: the hex color code to validate
>
> ### Returns:
>
> Boolean
`is_valid_rgb(rgb)`
Returns `True` if `rgb` is valid RGB tuple, else `False`.
> ### Parameters:
>
> - `rgb`: the rgb tuple to validate
>
> ### Returns:
>
> Boolean
`make_ansi(fgcolor=None, bgcolor=None, attrs=None, color_mode=4)`
Make an `Ansi Escape Sequence` from the args given. Returns the sequence without `Ansi Reset Code`. This method is similar to `colored()`, but rather than adding sequence to the text, it returns the sequence itself. Matter of fact, `colored()` also uses this method under the hood.
> ### Parameters:
>
> - `fgcolor`: the foreground color (any color that belongs to `color_mode` color system)
> - `bgcolor`: the background color (any color that belongs to `color_mode` color system)
> - `attrs`: the attributes list
> - `color_mode`: the color mode to use
>
> ### Returns:
>
> Ansi escape sequence `str`
>
> ### Exceptions:
>
> Raises `InvalidColorError` if:
>
> - `fgcolor` is invalid or not from `color_mode` color system
> - `bgcolor` is invalid or not from `color_mode` color system
>
> Raises `ColorModeError` if:
>
> - `color_mode` is invalid
`make_gradient(start_color, end_color, steps=10, reverse=False)`
Make a gradient between two RGB colors `start_color` and `end_color` by linearly interpolating between these for a given number of `steps`. Returns the `list` of rgb tuples.
> ### Parameters:
>
> - `start_color`: starting rgb color
>
> - `end_color`: ending rgb color
>
> - `steps`: steps to interpolate across (minimum `2`)
>
> - `reverse`: flip the gradient horizontally
>
> ### Returns:
>
> `list` of rgb colors
>
> ### Exceptions:
>
> Raises `InvalidColorError` if:
>
> - `start_color` is not a valid RGBTuple
> - `end_color` is not a valid RGBTuple
`print_all_colors()`
Print all 256 colors from `8-bit` color system with their name and code. (sorted by `codes` in asc. order)
> ### Returns:
>
> Generator object.
`printc(text, fgcolor=None, bgcolor=None, attrs=None, color_mode=4, sep=" ", end="\n", file=None, flush=False, no_color=None, force_color=None)`
Prints whatever returns from `colored()`.
> ### Parameters:
>
> - `text`: the text to colorize
>
> - `fgcolor`: the foreground color
>
> - `bgcolor`: the background color
>
> - `attrs`: the attributes to apply
>
> - `color_mode`: the colormode to use (defualt is `4`)
>
> - `sep`: sep arg of print function.
>
> - `end`: end arg of print function.
>
> - `file`: file arg of print function.
>
> - `flush`: flush arg of print function.
>
> ### Exceptions:
>
> All exceptions raised by `colored()`
`rgb_to_hex(rgb, with_symbol=True)`
Converts `rgb` tuple into Hex color code.
> ### Parameters:
>
> - `rgb`: RGB tuple to convert to hex
> - `with_symbol`: Whether to include the `#` symbol in output
>
> ### Returns:
>
> Hex color code `str`
`search_colors(query)`
Returns a generator object which on each iteration, yields a tuple `(name, code)` of `8-bit` color that contain `query` in it's name. Returns `None` if query is empty.
> ### Parameters:
>
> - `query`: the string to look for...
>
> ### Returns:
>
> Generator Object.
## ▎ Exceptions in ansy:
`ColorModeError`
Raised when encountered an inappropriate color mode that is unrecognized by `ansy`
`HexError`
Raised when encountered an invalid Hex color code.
`InvalidColorError`
Raised when encountered an inappropriate color that is unrecognized by `ansy`
`RGBError`
Raised when encountered an invalid RGB tuple.
`StyleError`
Raised when encountered an invalid style for `Ansy strings`
## ▎ COLORS API
`get_material_color(color)`
Returns a `dict` of a material `color` (all of its shades). Returns `None` if `color` not found.
> ### Parameters:
>
> - `color`: name of a color from **Material Colors**
>
> ### Returns:
>
> `dict` containing the shades of `color`
`get_palettes()`
Returns a generator object which on iteration, yields a color palette `list`.
> ### Returns:
>
> Generator object.
`get_random_palette()`
Returns a random color palette `list`.
> ### Returns:
>
> `list` of colors
`get_web_colors()`
Returns a generator object which on iteration, yields a color `dict` from **Web/HTML Colors**.
> ### Returns:
>
> Generator object.
## ▎ Useful to know
### Standard Colors (4-Bit)
`black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`,
`light_grey`, `dark_grey`, `light_red`, `light_green`, `light_yellow`,
`light_blue`, `light_magenta`, `light_cyan`
### 256 Colors (8-Bit)
Call `ansy.print_all_colors()` to see all colors and their codes.
### Attributes
There are several attributes in `ansy` but not all are widely supported. some may not work as expected or not work at all.
| Attribute | What it does |
|:------------------ | -------------------------------------------------------------------------- |
| `bold` | bolds the text or increases intensity |
| `dark` | Darkens the text |
| `italic` | Italicizes the text (Not widely supported) |
| `blink` | Sets the blinking to less than 150 times per minute (Not widely supported) |
| `reverse` | Swaps foreground and background colors of text |
| `concealed` | Hides the text visually, but does not remove (Not widely supported) |
| `underline` | Underlines the text |
| `double-underline` | Double-Underlines the text (Disables bold mode on several terminals) |
| `overline` | Overlines the text i.e line above the text (Not widely supported) |
| `strike` | Strikes the text, as if marked for deletion (Not widely supported) |
### Material Colors:
These below are the names of Material Colors.
`red`, `pink`, `purple`, `deeppurple`, `indigo`, `blue`, `lightblue`, `cyan`, `teal`, `green`, `lightgreen`, `lime`, `yellow`, `amber`, `orange`, `deeporange`, `brown`, `grey`, `bluegrey`.
These below are the shades of each Material color.
`50`, `100`, `200`, `300`, `400`, `500`, `600`, `700`, `800`, `900`, `a100`, `a200`, `a400`, `a700`.
### ▎ Attributions
- `_can_do_colour()` (_which checks environment variables for tty/dumb terminals_) is borrowed from `termcolor`. see full license text in `THIRD_PARTY_LICENSES` file.
- `8-bit` colors have been assigned X-Term names using **256-colors-cheatsheet** from [**ditig.com**](https://www.ditig.com/publications/256-colors-cheat-sheet) *(Updated and cleaned)*
- `colors` module uses **1400+** colors that are taken from the [Corpora](https://github.com/dariusk/corpora) by Darius Kazemi.
Thank you all, for saving me from the frustration i had to go through if........
### ▎ Compatibility and Testing
This package has been well-tested across multiple platforms, including **Windows**, **macOS**, and **Linux** _(ubuntu)_, ensuring broad compatibility.
It is tested on Python versions `3.8` upto `3.13`. it may or may not work on other versions.
---
I think i'm starting to ♥ `markdown` even more than `python`.
### Author: ❝ Anas shakeel ❞
Raw data
{
"_id": null,
"home_page": "https://github.com/Anas-Shakeel/ansy",
"name": "ansy",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "python, ANSI, ANSI color, color, cli, command-line, terminal, text formatting, color output, ansy, terminal, text styling",
"author": "Anas Shakeel",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/e8/03/d360077472b7c4fe15e1956728eb5dc6a19c7400c55f42bf9d0f6cffc716/ansy-1.1.2.tar.gz",
"platform": null,
"description": "# Ansy\r\n\r\n[![GitHub Repository](https://img.shields.io/badge/-GitHub-%230D0D0D?logo=github&labelColor=gray)](https://github.com/anas-shakeel/ansy) \r\n[![Latest PyPi version](https://img.shields.io/pypi/v/ansy.svg)](https://pypi.python.org/pypi/ansy)\r\n[![supported Python versions](https://img.shields.io/pypi/pyversions/ansy)](https://pypi.python.org/pypi/ansy)\r\n[![Project licence](https://img.shields.io/pypi/l/ansy?color=blue)](LICENSE) \r\n[![Black](https://img.shields.io/badge/code%20style-black-000000.svg)](black) \r\n[![Automated testing results](https://img.shields.io/github/actions/workflow/status/anas-shakeel/ansy/.github/workflows/python-package.yml?branch=main)](https://github.com/anas-shakeel/ansy/actions/workflows/python-package.yml?query=branch%3Amain)\r\n[![PyPI downloads](https://img.shields.io/pypi/dm/ansy.svg)](https://pypistats.org/packages/ansy)\r\n\r\n\r\n`ansy` (pronounced __ANSI__), inspired by (& successor to) `termcolor` module that is used to style and format output in the terminal.\r\n\r\nIt is was a part of another module i'v recently released called [Pinsy](https://pypi.org/project/pinsy), but i thought why not release it as it's own standalone module. So, Here it is.\r\n\r\n\r\n### \u258e Features\r\n\r\n- Colorize a string using 3 color modes (`4-bit`, `8-bit`, `24-bit`)\r\n\r\n- Colorize selective parts of a string\r\n\r\n- Colorize a string using random colors.\r\n\r\n- Apply Gradients to strings.\r\n\r\n- Format a string using attributes such as `bold`, `italic`, `underline`, and __7__ more\r\n\r\n- Strip away ANSI Codes from a string\r\n\r\n- Access to widely used colors\r\n\r\n- No external dependencies\r\n\r\n- Easy to use API\r\n\r\n- All of this under `90kb` *(and much of it is occupied by `docstrings`, `type annotations` and `hex colors`)*\r\n\r\n### \u258e Setup & Installation\r\n``` shell\r\npip install ansy\r\n```\r\nYou may also need to install `colorama` (*__windows__ users only*).\r\n\r\n### \u258e From `termcolor` to `ansy`\r\n\r\nIf your code uses `termcolor` and you want to shift to `ansy`, you can safely replace the `colored` function of `termcolor` with the `colored` function of `ansy`.\r\n\r\n```py\r\nfrom ansy import colored\r\n\r\ncolored('This is ansy.', 'light_red', 'dark_grey', ['bold', 'underline'])\r\n\r\n# Argument names for color & on_color have been changed to fgcolor & bgcolor\r\ncolored(text='this is ansy with kw-args', fgcolor='light_red', bgcolor='dark_grey', attrs=['bold'])\r\n```\r\n\r\n## \u258e USAGE\r\n\r\nUsing `ansy` is very easy.\r\n\r\n### Coloring a string:\r\n\r\nUse the `colored` function, if you want to colorize a string.\r\n\r\n```py\r\nfrom ansy import colored\r\n\r\n# Bold Red text on a White background\r\nred_white = colored('This is a string', 'red', 'white', attrs=['bold'])\r\nprint(red_white)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 1.png\" />\r\n</p>\r\n\r\nLeaving an argument empty uses the default `None` value which disables that formatting.\r\n\r\n```py\r\n# Red text with default background and no attributes\r\nred = ansy.colored('This is a string', 'red')\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 2.png\" />\r\n</p>\r\n\r\nThis method also takes an extra `color_mode` argument, which specifies the color mode you want to use.\r\n\r\n```py\r\n# Underlined Text with 215 (brown_sandy) FG and 183 (grey_9) BG.\r\nformatted = colored('This is a string', 215, 240, ['underline'], color_mode=8)\r\nprint(formatted)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 3.png\" />\r\n</p>\r\n\r\n`color_mode` can only be one of below:\r\n\r\n- `4` to use 4 bit colors\r\n\r\n- `8` to use 8 bit colors\r\n\r\n- `24` to use 24 bit colors\r\n\r\nNotice i've also changed the colors to some codes. These codes belong to the `8-bit` color system and they range from `0` to `255`.\r\n\r\nYou can also use color names instead of codes.\r\n\r\n```py\r\n# Underlined Text with brown_sandy FG and grey_9 BG.\r\nformatted = colored('This is a string', 'brown_sandy', 'grey_9', ['underline'], 8)\r\n```\r\n\r\nYou can get these colors using `get_all_colors` function, which yields a tuple containing color name and code on each iteration.\r\n\r\n```py\r\n# Iterates through and prints all colors from 8-bit colorsystem\r\nfor name, code in ansy.get_all_colors():\r\n print(name, code)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 4 get_all_colors.png\" />\r\n</p>\r\n\r\nOr you can just call `print_all_colors()`, which prints these color names, their code and the color they represent.\r\n\r\n```py\r\nansy.print_all_colors()\r\n# Outputs similar to below, but colored\r\n# \u2593\u2593\u2593\u2593\u2593\u2593 0: black\r\n# \u2593\u2593\u2593\u2593\u2593\u2593 1: red\r\n# \u2593\u2593\u2593\u2593\u2593\u2593 2: green\r\n# --snip--\r\n# \u2593\u2593\u2593\u2593\u2593\u2593 255: grey_24\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 5 print_all_colors.png\" />\r\n</p>\r\n\r\nModern terminals also support RGB colors which offer a much much more wider range of colors *(approx. 16.7 million colors)*. Now you have the ability to use any color you like *(provided if the terminal supports)*\r\n\r\n```py\r\n# Red Italic Text on a White background\r\nfg = (255,100,100)\r\nbg = (215,215,215)\r\ncolored('This is a string', fg, bg, ['italic'], 24)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 6.png\" />\r\n</p>\r\n\r\n`24-bit` color system accepts **RGB** tuple as well as **Hex** color codes.\r\n\r\n```py\r\n# Red Italic Text on a White background\r\nfg = '#FF6464'\r\nbg = '#D7D7D7'\r\ncolored('This is a string', fg, bg, ['italic'], 24)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 6.png\" />\r\n</p>\r\n\r\nYou can also use `printc()` function with same arguments as of `colored()` to just print the result of `colored()` instead of returning the formatted string.\r\n\r\n```py\r\nfrom ansy import printc\r\nprintc('Print this string after formatting.', fgcolor='plum', attrs=['italic'], color_mode=8)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_str 7.png\" />\r\n</p>\r\n\r\nSimilar to `c_print()` function of `termcolor`, only slightly easier to type.\r\n\r\n### Coloring selective parts of a string:\r\n\r\n`colored()` formats the whole string. And so if you wanted to apply formatting to a selective part of a string you would normally have to do it like this:\r\n\r\n```py\r\n# Formatting the name part and leaving the rest as is\r\nformatted_world = colored('World', fgcolor='purple', attrs=['bold'], color_mode=8)\r\nprint(f\"Hello, {formatted_world}!\")\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_selective 1.png\" />\r\n</p>\r\n\r\nWhat if you wanted to set a different color for `\"Hello\"` too?\r\n\r\n```py\r\nformatted_hello = colored('Hello', fgcolor='orange', color_mode=8)\r\nformatted_world = colored('World', fgcolor='purple', attrs=['bold'], color_mode=8)\r\nprint(f\"{formatted_hello}, {formatted_world}\")\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_selective 2.png\" />\r\n</p>\r\n\r\nYou could imagine where this is going, right?\r\n\r\nThe solution to this problem is `colored_ansy()` function. It adds the styling defined in `style` dictionary to wherever an `ansy string` is found in the whole string.\r\n\r\n**What is an Ansy String?**\r\n\r\nAn ansy string is simply a syntax that allows you to apply a specific styling or formatting to any part of the text they want.\r\n\r\n> An `Ansy String` starts with a `@` followed by the name of the style (defined by the `style` dict), and the text in backets `[text]` to which they want to apply the formatting.\r\n> \r\n> ```py\r\n> ansy_string = \"This is an @my_style[ansy string]\"\r\n> ```\r\n\r\n**What is Style Dict?**\r\n\r\n`Style dict` is a dictionary which defines the style(s) to apply to these ansy strings. Each style in the `style` dictionary is itself a dictionary.\r\n\r\nPurpose of this structure is so that you could define all your styles in one dictionary and then use it everywhere, instead of creating a dictioanry for each style and create a mess in your code.\r\n\r\n**Structure of Style Dict:**\r\n\r\n```py\r\nstyle = {\r\n \"my_style\": {\r\n \"colormode\": 8,\r\n \"fgcolor\": \"light_red\",\r\n \"bgcolor\": 255,\r\n \"attrs\": ['bold', 'italic']\r\n }\r\n}\r\n```\r\n\r\nEvery key in this `style` dictionary is the name of the style that you're gonna use in the `ansy strings`.\r\n\r\nEach style must have 4 `key:value` pairs.\r\n\r\n- `color_mode`: the color mode to use (`4`, `8`, `24`)\r\n\r\n- `fgcolor`: the foreground color of the style\r\n\r\n- `bgcolor`: the background color of the style\r\n\r\n- `attrs`: the attributes to apply\r\n\r\nOne thing to note here, `color_mode` decides which color mode to use and you should provide a color supported by that mode. for example, if using `4` bit color mode, provide a color that is a valid 4-bit color. If using `8` bit, provide a color from `256` color system. For color mode `24`, provide an `RGBTuple` or a `Hex` color code.\r\n\r\nBack to our problem.\r\n\r\n```py\r\nfrom ansy import colored_ansy\r\n# Define styles\r\nstyle = {\r\n \"orange\": {\r\n \"color_mode\": 8,\r\n \"fgcolor\": 'orange',\r\n \"bgcolor\": None,\r\n \"attrs\": None\r\n },\r\n \"purple\": {\r\n \"color_mode\": 8,\r\n \"fgcolor\": 'purple',\r\n \"bgcolor\": None,\r\n \"attrs\": ['bold']\r\n}}\r\n\r\nformatted = colored_ansy(\"@orange[Hello] @purple[World]\", style)\r\nprint(formatted)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_selective 2.png\" />\r\n</p>\r\n\r\nYou must be thinking, wow! what a solution. we now have to write even more lines of code, right?\r\n\r\nWell yeah! but only if you do it manually. there is a function in called `create_style()` which makes it easier to define styles.\r\n\r\n```py\r\nfrom ansy import colored_ansy, create_style\r\n\r\n# Create styles\r\nstyle = {\r\n \"orange\": create_style(8, fgcolor='orange'),\r\n \"purple\": create_style(8, fgcolor='purple', attrs=['bold'])\r\n}\r\n\r\nformatted = colored_ansy(\"@orange[Hello] @purple[World]\", style)\r\nprint(formatted)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_selective 2.png\" />\r\n</p>\r\n\r\nStill more code, but it's just a one time thing! now you can use `orange` and `purple` style to format as many parts as you want.\r\n\r\nThis below example hides some parts of text using `concealed` attribute.\r\n\r\n```py\r\n# Reusing Styles\r\nstyle['hide'] = create_style(attrs=['concealed'])\r\n\r\nformatted = ansy.colored_ansy('Hide this @hide[..], & this @hide[++], but not this @hide[**]', style)\r\nprint(formatted) # Output: Hide this , & this , but not this **\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_selective 3.png\" />\r\n</p>\r\n\r\nNote that `concealed` attribute does not remove/delete the text, it only hides it visually.\r\n\r\n### Applying Gradients:\r\n\r\nHorizontal Gradients can be applied to the foreground of a string using two **24-bit** Colors using the `colored_gradient()` function.\r\n\r\n```py\r\n# Gradient (left-to-right) using Red and Blue colors\r\nfrom ansy import colored_gradient\r\n\r\nformatted = colored_gradient('This is ansy.', (255,100,100), (100,50,200))\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_gradient 1.png\" />\r\n</p>\r\n\r\nThis method takes in `5` argument:\r\n\r\n- `text`: the text to apply the gradient to\r\n\r\n- `start_color`: starting foreground rgb color\r\n\r\n- `end_color`: ending foreground rgb color\r\n\r\n- `quality`: quality of the gradient\r\n \r\n > can be set to `high`, `medium` or `low`\r\n\r\n- `reverse` reverse the gradient to be (right to left) instead.\r\n\r\nCurrently, this method only supports horizontal gradients, not vertical ones. but you can fake vertical gradients by introducing newline characters `\\n` in your string.\r\n\r\n```py\r\ntext = \"This is text is \\ngoing to be used \\nto create or fake \\na vertical gradient.\"\r\nprint(colored_gradient(text, '#00ffff','#b00b1e'))\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_gradient 2.png\" />\r\n</p>\r\n\r\nIt still is horizontal gradient but it would appear as if it's a vertical gradient. *(well, technically diagonal)*\r\n\r\n### Random Colors:\r\n\r\nColoring strings in your application using random colors may not be the best thing to do. but it's there if you need.\r\n\r\n```py\r\nfrom ansy import colored_random\r\n\r\nformatted = colored_random('Random Random, Evil Phantom!')\r\nprint(formatted)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_random 1.png\" />\r\n</p>\r\n\r\nBy default, this method choose a random color from `4-bit` colorsystem. but you can change the `color_mode` to `8` or `24` to use those colors.\r\n\r\n```py\r\ncolored_random('text', color_mode=24)\r\n```\r\n\r\nThis method takes `6` arguments:\r\n\r\n- `text`: the text string\r\n\r\n- `target`: how to apply random colors\r\n \r\n - `chars`: apply a random color to each character of text\r\n \r\n - `words`: apply a random color to each word of text\r\n \r\n - `all`: apply a random color to whole text **(default)**\r\n\r\n- `color_mode`: the color mode to use\r\n\r\n- `custom_palette`: choose colors randomly only from this list of colors\r\n\r\n- `attrs`: the attributes to apply\r\n\r\n- `random_attrs`: randomize the attributes too\r\n\r\nYou can also choose a `target` to apply random colors to.\r\n\r\n```py\r\nprint(colored_random('Apply random colors to each word', target='words'))\r\nprint(colored_random('Apply random colors to each character', target='chars'))\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_random 2.png\" />\r\n</p>\r\n\r\nYou can pass a list of colors that you like, to `custom_palette` and this method then, will only choose colors from that list.\r\n\r\n```py\r\npalette = [\"#69D2E7\",\"#A7DBD8\",\"#E0E4CC\",\"#F38630\",\"#FA6900\"]\r\ncolored_random('Not so random palette.', custom_palette=palette, target=\"words\", color_mode=24)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/colored_random 3.png\" />\r\n</p>\r\n\r\nYou can add colors from any color system into the `palette` list, but then make sure to set that color mode too.\r\n\r\n### De-ansifying a string containing ANSI Codes:\r\n\r\nIf you want to remove all `ANSI Escape Codes` from a string, you can use the `de_ansi` function.\r\n\r\n```py\r\nfrom ansy import colored, de_ansi\r\n\r\nansi_string = colored('This string contains ANSI', 'light_blue', 'dark_grey', ['italic'])\r\nclean_string = de_ansi(ansi_string)\r\n\r\nprint([ansi_string]) # Output: ['\\x1b[3m\\x1b[100m\\x1b[94mThis string contains ANSI\\x1b[0m']\r\nprint([clean_string]) # Output: ['This string contains ANSI']\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/deansi 1.png\" />\r\n</p>\r\n\r\nNotice how i am printing the strings, this is a neat little trick to check if a string contains `ANSI Codes` .\r\n\r\nBy simply printing a string containing `ANSI`, you won't be able to see the **ANSI Escape Code** because, well, they are escaped. `print([ansi_string])` just prints the contents of a list and the `ANSI Codes` do not **\"ESCAPE\"** this way.\r\n\r\nAlso you can write out the strings in a text file. that method works too.\r\n\r\n### Widely Used Colors:\r\n\r\nAnsy includes `24-bit` colors to be used in your applications. These colors include:\r\n\r\n- `19` **Google's Material Colors** (with `14` different shades in each)\r\n\r\n- `140` **Web/HTML Colors**\r\n\r\n- `200` **Color Palettes** (with `5` colors in each)\r\n\r\nYou can get these colors using the `colors` module within the `ansy` package.\r\n\r\n```py\r\nfrom ansy import colors\r\n```\r\n\r\nThis module contains `4` functions:\r\n\r\n- `get_material_color()`: Takes in a `color` string and returns all shades of that color from **Material Colors**.\r\n\r\n- `get_palettes()`: Returns a generator iterator, which yields a list of colors on each iteration.\r\n\r\n- `get_random_palette()`: Returns a random palette from **Color Palettes**.\r\n\r\n- `get_web_colors()`: Returns a generator iterator, which yields dictionaries of colors from **Web/HTML Colors**.\r\n\r\nAll **Material Colors** are tabulated in the **Useful to know** section with their names and shades.\r\n\r\n```py\r\nfrom ansy import colors\r\n\r\n# Material colors\r\nmaterials = colors.get_material_color(\"red\")\r\nprint(materials)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/material_colors.png\" />\r\n</p>\r\n\r\nOutput is pretty-printed using [Pinsy](https://github.com/anas-shakeel/pinsy) package.\r\n\r\nGet **Web Colors** like this:\r\n\r\n```py\r\nfor color in colors.get_web_colors():\r\n print(color)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/web_colors.png\" />\r\n</p>\r\n\r\nAnd **Palettes** like this:\r\n\r\n```py\r\nfor palette in colors.get_palettes():\r\n print(palette)\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/palettes.png\" />\r\n</p>\r\n\r\nAnd Get a random palette from these **Palettes** likes this:\r\n\r\n```py\r\nprint(colors.get_random_palette())\r\n```\r\n<p align=\"center\">\r\n <img src=\"https://raw.githubusercontent.com/Anas-Shakeel/ansy/main/assets/palette random.png\" />\r\n</p>\r\n\r\n## \u258e ANSY API\r\n\r\n`colored(text, fgcolor=None, bgcolor=None, attrs=None, color_mode=4, no_color=None, force_color=None)`\r\n\r\nColorize text using `4`, `8`, or `24` bit colors. If `fgcolor`, `bgcolor`, and `attrs` all are `None`, the `text` itself is returned without any ansi codes added.\r\n\r\n> ### Parameters:\r\n> \r\n> - `text`: the text to colorize\r\n> \r\n> - `fgcolor`: the foreground color\r\n> \r\n> - `bgcolor`: the background color\r\n> \r\n> - `attrs`: the attributes to apply\r\n> \r\n> - `color_mode`: the colormode to use (defualt is `4`)\r\n> \r\n> ### Returns:\r\n> \r\n> Formatted string.\r\n> \r\n> ### Exceptions:\r\n> \r\n> Raises `ColorModeError` if:\r\n> \r\n> - `color_mode` is invalid\r\n> \r\n> Raises `InvalidColorError` if:\r\n> \r\n> - `fgcolor` is invalid\r\n> \r\n> - `bgcolor` is invalid\r\n> \r\n> Raises `AttributeError` if:\r\n> \r\n> - `attrs` contain an invalid attribute\r\n\r\n`colored_ansy(text, style, no_color=None, force_color=None)`\r\n\r\nAdds the styling defined in `style` to wherever an `ansy string` is found in the `text`.\r\n\r\n> ### Parameters:\r\n> \r\n> - `text`: the text containing the `ansy strings`\r\n> \r\n> - `style`: a dictionary containing the style(s).\r\n> \r\n> ### Returns:\r\n> \r\n> Formatted string.\r\n> \r\n> ### Exceptions:\r\n> \r\n> Raises `StyleError` if:\r\n> \r\n> - style name used in `ansy string` not found in `style` dict\r\n> \r\n> Raises `ColorModeError` if:\r\n> \r\n> - `color_mode` provided in style, is invalid\r\n\r\n`colored_gradient(text, start_color=None, end_color=None, quality='medium', reverse=False)`\r\n\r\nApply horizontal gradient on `text`. This method uses `24-bit` color system.\r\n\r\n> ### Parameters:\r\n> \r\n> - `text`: the text to apply the gradient to\r\n> - `start_color`: starting foreground color (`RGBTuple` or `Hex code`)\r\n> - `end_color`: ending foreground color (`RGBTuple` or `Hex code`)\r\n> - `quality`: quality of the gradient (`high`, `medium`, or `low`)\r\n> - `reverse`: reverses the gradient to be (right to left) instead.\r\n> \r\n> ### Returns:\r\n> \r\n> Formatted string.\r\n> \r\n> ### Exceptions:\r\n> \r\n> Raises `InvalidColorError` if:\r\n> \r\n> - `start_color` is an invalid `24-bit` color\r\n> \r\n> - `end_color` is an invalid `24-bit` color\r\n> \r\n> Raises `AssertionError` if:\r\n> \r\n> - `quality` is not set to `high`, `medium`, or `low`\r\n\r\n`colored_random(text, target='all', color_mode=4, custom_palette=None, attrs=None, random_attrs=False)`\r\n\r\nApply a random color to `text`. colors are chosen from a colorsystem specified by `color_mode`.\r\n\r\n> ### Parameters:\r\n> \r\n> - `text`: the text string\r\n> - `target`: apply random colors to `chars`, `words` or `all` string.\r\n> - `color_mode`: the colormode to use\r\n> - `custom_palette`: choose colors only from this iterable of user-defined colors\r\n> - `attrs`: the attributes to apply (attributes are **NOT** randomized by default)\r\n> - `random_attrs`: randomize the attributes too.\r\n> \r\n> ### Returns:\r\n> \r\n> Formatted string.\r\n> \r\n> ### Exceptions:\r\n> \r\n> Raises `ValueError` if:\r\n> \r\n> - `target` is not set to `chars`, `words`, `all`\r\n> \r\n> Raises `ColorModeError` if:\r\n> \r\n> - `color_mode` is invalid\r\n> \r\n> Raises `InvalidColorError` if:\r\n> \r\n> - `custom_palette` contains an invalid color\r\n> \r\n> Raises `AttributeError` if:\r\n> \r\n> - `attrs` contains an invalid attribute\r\n\r\n`colorname_to_code(color)`\r\n\r\nReturns the `code` for the `color` name from `8-bit` color system. Returns `None` if `color` is not a valid color name.\r\n\r\n> ### Parameters:\r\n> \r\n> - `color_name`: name of a color (from`8-bit` color system)\r\n> \r\n> ### Returns:\r\n> \r\n> Color `code` or `None`\r\n\r\n`code_to_colorname(code)`\r\n\r\nReturns the color name for the `code`. Returns `None` if `code` is not a valid color.\r\n\r\n> ### Parameters:\r\n> \r\n> - `code`: code of a color (from `8-bit` color system **i.e. [0-255]**)\r\n> \r\n> ### Returns:\r\n> \r\n> Color `name` or `None`\r\n\r\n`contains_ansi(text)`\r\n\r\nReturns `True` if `text` contains Ansi codes, else `False`.\r\n\r\n> ### Parameters:\r\n> \r\n> - `text`: the text string to check\r\n> \r\n> ### Returns:\r\n> \r\n> bool\r\n\r\n`create_style(color_mode=4, fgcolor=None, bgcolor=None, attrs=None)`\r\n\r\nCreates a style `dict` to use in `colored_ansy()` as style.\r\n\r\n> ### Parameters:\r\n> \r\n> - `color_mode`: the color mode (`4-bit`, `8-bit`, `24-bit`)\r\n> \r\n> - `4` means use 4-bit colors (`16` Standard colors)\r\n> \r\n> - `8` means use 8-bit colors (`256` colors)\r\n> \r\n> - `24` means use 24-bit colors (approx. `16.7 million` colors)\r\n> \r\n> - `fgcolor` the foreground color\r\n> \r\n> - `bgcolor` the foreground color\r\n> \r\n> - `attrs` the attributes list\r\n> \r\n> ### Returns:\r\n> \r\n> Style `dict`\r\n> \r\n> ### Exceptions:\r\n> \r\n> Raises `InvalidColorError` if:\r\n> \r\n> - `fgcolor` is not a valid color\r\n> \r\n> - `bgcolor` is not a valid color\r\n> \r\n> Raises `ColorModeError` if:\r\n> \r\n> - `color_mode` is invalid\r\n> \r\n> Raises `AttributeError` if:\r\n> \r\n> - `attrs` includes an invalid attribute string\r\n\r\n`create_random_palette(color_mode, n)`\r\n\r\nReturns a list of `n` colors from `color_mode`-bit color system.\r\n\r\n> ### Parameters:\r\n> \r\n> - `color_mode`: the colormode to use\r\n> - `n`: number of colors to include in palette\r\n> \r\n> ### Returns:\r\n> \r\n> `list` of colors\r\n> \r\n> ### Exceptions:\r\n> \r\n> Raises `TypeError` if:\r\n> \r\n> - `n`: is not an integer\r\n\r\n`de_ansi(text)`\r\n\r\nRemoves all `ANSI Codes` from given string.\r\n\r\n> ### Parameters:\r\n> \r\n> - `text` the text to remove ANSI codes from.\r\n> \r\n> ### Returns:\r\n> \r\n> De-ansified string.\r\n> \r\n> ### Exceptions:\r\n> \r\n> Raises `TypeError` if:\r\n> \r\n> - `text` is not a `str`\r\n\r\n`get_all_colors(sort_by_name=False)`\r\n\r\nYields a `tuple` of `color_name` and it's `code`. (sorted by `code`)\r\n\r\n> ### Parameters:\r\n> \r\n> - `sort_by_name`: Sorts colors by name (default is `False` which sorts by code)\r\n> \r\n> ### Returns:\r\n> \r\n> Generator obect.\r\n\r\n`get_random_color(color_mode=4)`\r\n\r\nReturns a random color from a colorsystem specified by `color_mode`.\r\n\r\n> ### Parameters:\r\n> \r\n> - `color_mode`: the color system to use to choose random color from\r\n> \r\n> ### Returns:\r\n> \r\n> Color name `str`, or rgb `tuple`\r\n> \r\n> ### Exceptions:\r\n> \r\n> Raises `ColorModeError` if:\r\n> \r\n> - `color_mode` is invalid.\r\n\r\n`hex_to_rgb(hexcode)`\r\n\r\nConverts `hexcode` into an `RGBTuple`. It is case-insensitive and also recognizes shorter hex codes e.g `#FFF`, `#9ca` etc.\r\n\r\n> ### Parameters:\r\n> \r\n> - `hexcode`: a hex color code string\r\n> \r\n> ### Returns:\r\n> \r\n> RGB tuple.\r\n\r\n`is_valid_attr(attr)`\r\n\r\nReturns `True` if `attr` is a valid Attribute, else `False`.\r\n\r\n> ### Parameters:\r\n> \r\n> - `attr`: the attribute string\r\n> \r\n> ### Returns:\r\n> \r\n> Boolean\r\n\r\n`is_valid_color(color, color_mode)`\r\n\r\nValidates the color based on `color_mode`. Returns `True` if color is valid, `False` otherwise.\r\n\r\n> ### Parameters:\r\n> \r\n> - `color`: a color from `4`, `8` or `24`-bit color system\r\n> - `color_mode`: the color mode of `color` (can be one of `4`, `8`, `24`)\r\n> \r\n> ### Returns:\r\n> \r\n> Boolean\r\n\r\n`is_valid_hex(hexcode)`\r\n\r\nReturns `True` if `hexcode` is valid, else `False`.\r\n\r\n> ### Parameters:\r\n> \r\n> - `hexcode`: the hex color code to validate\r\n> \r\n> ### Returns:\r\n> \r\n> Boolean\r\n\r\n`is_valid_rgb(rgb)`\r\n\r\nReturns `True` if `rgb` is valid RGB tuple, else `False`.\r\n\r\n> ### Parameters:\r\n> \r\n> - `rgb`: the rgb tuple to validate\r\n> \r\n> ### Returns:\r\n> \r\n> Boolean\r\n\r\n`make_ansi(fgcolor=None, bgcolor=None, attrs=None, color_mode=4)`\r\n\r\nMake an `Ansi Escape Sequence` from the args given. Returns the sequence without `Ansi Reset Code`. This method is similar to `colored()`, but rather than adding sequence to the text, it returns the sequence itself. Matter of fact, `colored()` also uses this method under the hood.\r\n\r\n> ### Parameters:\r\n> \r\n> - `fgcolor`: the foreground color (any color that belongs to `color_mode` color system)\r\n> - `bgcolor`: the background color (any color that belongs to `color_mode` color system)\r\n> - `attrs`: the attributes list\r\n> - `color_mode`: the color mode to use\r\n> \r\n> ### Returns:\r\n> \r\n> Ansi escape sequence `str`\r\n> \r\n> ### Exceptions:\r\n> \r\n> Raises `InvalidColorError` if:\r\n> \r\n> - `fgcolor` is invalid or not from `color_mode` color system\r\n> - `bgcolor` is invalid or not from `color_mode` color system\r\n> \r\n> Raises `ColorModeError` if:\r\n> \r\n> - `color_mode` is invalid\r\n\r\n`make_gradient(start_color, end_color, steps=10, reverse=False)`\r\n\r\nMake a gradient between two RGB colors `start_color` and `end_color` by linearly interpolating between these for a given number of `steps`. Returns the `list` of rgb tuples.\r\n\r\n> ### Parameters:\r\n> \r\n> - `start_color`: starting rgb color\r\n> \r\n> - `end_color`: ending rgb color\r\n> \r\n> - `steps`: steps to interpolate across (minimum `2`)\r\n> \r\n> - `reverse`: flip the gradient horizontally\r\n> \r\n> ### Returns:\r\n> \r\n> `list` of rgb colors\r\n> \r\n> ### Exceptions:\r\n> \r\n> Raises `InvalidColorError` if:\r\n> \r\n> - `start_color` is not a valid RGBTuple\r\n> - `end_color` is not a valid RGBTuple\r\n\r\n`print_all_colors()`\r\n\r\nPrint all 256 colors from `8-bit` color system with their name and code. (sorted by `codes` in asc. order)\r\n\r\n> ### Returns:\r\n> \r\n> Generator object.\r\n\r\n`printc(text, fgcolor=None, bgcolor=None, attrs=None, color_mode=4, sep=\" \", end=\"\\n\", file=None, flush=False, no_color=None, force_color=None)`\r\n\r\nPrints whatever returns from `colored()`.\r\n\r\n> ### Parameters:\r\n> \r\n> - `text`: the text to colorize\r\n> \r\n> - `fgcolor`: the foreground color\r\n> \r\n> - `bgcolor`: the background color\r\n> \r\n> - `attrs`: the attributes to apply\r\n> \r\n> - `color_mode`: the colormode to use (defualt is `4`)\r\n> \r\n> - `sep`: sep arg of print function.\r\n> \r\n> - `end`: end arg of print function.\r\n> \r\n> - `file`: file arg of print function.\r\n> \r\n> - `flush`: flush arg of print function.\r\n> \r\n> ### Exceptions:\r\n> \r\n> All exceptions raised by `colored()`\r\n\r\n`rgb_to_hex(rgb, with_symbol=True)`\r\n\r\nConverts `rgb` tuple into Hex color code.\r\n\r\n> ### Parameters:\r\n> \r\n> - `rgb`: RGB tuple to convert to hex\r\n> - `with_symbol`: Whether to include the `#` symbol in output\r\n> \r\n> ### Returns:\r\n> \r\n> Hex color code `str`\r\n\r\n`search_colors(query)`\r\n\r\nReturns a generator object which on each iteration, yields a tuple `(name, code)` of `8-bit` color that contain `query` in it's name. Returns `None` if query is empty.\r\n\r\n> ### Parameters:\r\n> \r\n> - `query`: the string to look for...\r\n> \r\n> ### Returns:\r\n> \r\n> Generator Object.\r\n\r\n## \u258e Exceptions in ansy:\r\n\r\n`ColorModeError`\r\n\r\nRaised when encountered an inappropriate color mode that is unrecognized by `ansy`\r\n\r\n`HexError`\r\n\r\nRaised when encountered an invalid Hex color code.\r\n\r\n`InvalidColorError`\r\n\r\nRaised when encountered an inappropriate color that is unrecognized by `ansy`\r\n\r\n`RGBError`\r\n\r\nRaised when encountered an invalid RGB tuple.\r\n\r\n`StyleError`\r\n\r\nRaised when encountered an invalid style for `Ansy strings`\r\n\r\n## \u258e COLORS API\r\n\r\n`get_material_color(color)`\r\n\r\nReturns a `dict` of a material `color` (all of its shades). Returns `None` if `color` not found.\r\n\r\n> ### Parameters:\r\n> \r\n> - `color`: name of a color from **Material Colors**\r\n> \r\n> ### Returns:\r\n> \r\n> `dict` containing the shades of `color`\r\n\r\n`get_palettes()`\r\n\r\nReturns a generator object which on iteration, yields a color palette `list`.\r\n\r\n> ### Returns:\r\n> \r\n> Generator object.\r\n\r\n`get_random_palette()`\r\n\r\nReturns a random color palette `list`.\r\n\r\n> ### Returns:\r\n> \r\n> `list` of colors\r\n\r\n`get_web_colors()`\r\n\r\nReturns a generator object which on iteration, yields a color `dict` from **Web/HTML Colors**.\r\n\r\n> ### Returns:\r\n> \r\n> Generator object.\r\n\r\n## \u258e Useful to know\r\n\r\n### Standard Colors (4-Bit)\r\n\r\n`black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`,\r\n\r\n`light_grey`, `dark_grey`, `light_red`, `light_green`, `light_yellow`,\r\n\r\n`light_blue`, `light_magenta`, `light_cyan`\r\n\r\n### 256 Colors (8-Bit)\r\n\r\nCall `ansy.print_all_colors()` to see all colors and their codes.\r\n\r\n### Attributes\r\n\r\nThere are several attributes in `ansy` but not all are widely supported. some may not work as expected or not work at all.\r\n\r\n| Attribute | What it does |\r\n|:------------------ | -------------------------------------------------------------------------- |\r\n| `bold` | bolds the text or increases intensity |\r\n| `dark` | Darkens the text |\r\n| `italic` | Italicizes the text (Not widely supported) |\r\n| `blink` | Sets the blinking to less than 150 times per minute (Not widely supported) |\r\n| `reverse` | Swaps foreground and background colors of text |\r\n| `concealed` | Hides the text visually, but does not remove (Not widely supported) |\r\n| `underline` | Underlines the text |\r\n| `double-underline` | Double-Underlines the text (Disables bold mode on several terminals) |\r\n| `overline` | Overlines the text i.e line above the text (Not widely supported) |\r\n| `strike` | Strikes the text, as if marked for deletion (Not widely supported) |\r\n\r\n### Material Colors:\r\n\r\nThese below are the names of Material Colors.\r\n\r\n`red`, `pink`, `purple`, `deeppurple`, `indigo`, `blue`, `lightblue`, `cyan`, `teal`, `green`, `lightgreen`, `lime`, `yellow`, `amber`, `orange`, `deeporange`, `brown`, `grey`, `bluegrey`.\r\n\r\nThese below are the shades of each Material color.\r\n\r\n`50`, `100`, `200`, `300`, `400`, `500`, `600`, `700`, `800`, `900`, `a100`, `a200`, `a400`, `a700`.\r\n\r\n### \u258e Attributions\r\n\r\n- `_can_do_colour()` (_which checks environment variables for tty/dumb terminals_) is borrowed from `termcolor`. see full license text in `THIRD_PARTY_LICENSES` file.\r\n\r\n- `8-bit` colors have been assigned X-Term names using **256-colors-cheatsheet** from [**ditig.com**](https://www.ditig.com/publications/256-colors-cheat-sheet) *(Updated and cleaned)*\r\n\r\n- `colors` module uses **1400+** colors that are taken from the [Corpora](https://github.com/dariusk/corpora) by Darius Kazemi.\r\n\r\nThank you all, for saving me from the frustration i had to go through if........\r\n\r\n### \u258e Compatibility and Testing\r\n\r\nThis package has been well-tested across multiple platforms, including **Windows**, **macOS**, and **Linux** _(ubuntu)_, ensuring broad compatibility.\r\n\r\nIt is tested on Python versions `3.8` upto `3.13`. it may or may not work on other versions.\r\n\r\n---\r\n\r\nI think i'm starting to \u2665 `markdown` even more than `python`.\r\n\r\n### Author: \u275d Anas shakeel \u275e\r\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A Python package to colorize and format output in the terminal.",
"version": "1.1.2",
"project_urls": {
"Homepage": "https://github.com/Anas-Shakeel/ansy"
},
"split_keywords": [
"python",
" ansi",
" ansi color",
" color",
" cli",
" command-line",
" terminal",
" text formatting",
" color output",
" ansy",
" terminal",
" text styling"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "7df32edca7599798d4892f530acd57be83f682099dc1ff6b5298104db53f8ce8",
"md5": "06d8814e6f5c2719568721b914c7a26b",
"sha256": "057de681921c4fefbc3d757f694b196f62aff42d1398981b53aaedfdc2cde1f9"
},
"downloads": -1,
"filename": "ansy-1.1.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "06d8814e6f5c2719568721b914c7a26b",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 35191,
"upload_time": "2024-11-23T20:48:28",
"upload_time_iso_8601": "2024-11-23T20:48:28.914373Z",
"url": "https://files.pythonhosted.org/packages/7d/f3/2edca7599798d4892f530acd57be83f682099dc1ff6b5298104db53f8ce8/ansy-1.1.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "e803d360077472b7c4fe15e1956728eb5dc6a19c7400c55f42bf9d0f6cffc716",
"md5": "82d936705685ea1a2419857701b75ce7",
"sha256": "8fefc41bd6c7c66aea9a833cf0fca35168fa17a6ab0f113cea8920a17abcd2b7"
},
"downloads": -1,
"filename": "ansy-1.1.2.tar.gz",
"has_sig": false,
"md5_digest": "82d936705685ea1a2419857701b75ce7",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 51895,
"upload_time": "2024-11-23T20:48:30",
"upload_time_iso_8601": "2024-11-23T20:48:30.939739Z",
"url": "https://files.pythonhosted.org/packages/e8/03/d360077472b7c4fe15e1956728eb5dc6a19c7400c55f42bf9d0f6cffc716/ansy-1.1.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-23 20:48:30",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "Anas-Shakeel",
"github_project": "ansy",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "ansy"
}