Skip to content

Commit

Permalink
Merge pull request #2 from thomassamoth/develop
Browse files Browse the repository at this point in the history
ansiconverter v2.0.0
  • Loading branch information
thomassamoth authored Sep 9, 2023
2 parents bc92bd9 + cfcfdf7 commit 0144ec2
Show file tree
Hide file tree
Showing 6 changed files with 280 additions and 172 deletions.
154 changes: 107 additions & 47 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,108 +1,168 @@
# 🌀 ANSI Converter

![PyPI](https://img.shields.io/pypi/v/ansiconverter) ![PyPI - License](https://img.shields.io/pypi/l/ansiconverter) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ansiconverter) ![PyPI - Status](https://img.shields.io/pypi/status/ansiconverter)
![PyPI](https://img.shields.io/pypi/v/ansiconverter) ![PyPI - License](https://img.shields.io/pypi/l/ansiconverter) ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ansiconverter) ![PyPI - Status](https://img.shields.io/pypi/status/ansiconverter) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat)](https://makeapullrequest.com) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

Convert any colour to the ANSI format to write in colours in your terminal.
Convert any colour to the [ANSI format](https://en.wikipedia.org/wiki/ANSI_escape_code) to write in colours in your terminal.

## ⌨ Installation
## ⌨️ Installation

Run this command to install `ansiconverter`:

```python
```bash
python -m pip install -U ansiconverter
```

To install for **development**:

```bash
git clone https://github.com/thomassamoth/ansiconverter.git

cd ansiconverter

pip install -e .[dev]
```
### Tests

To ensure the installation of this package has been successful, you can run the [tests](https://github.com/thomassamoth/ansiconverter/tree/main/test).

1. Make sure you have installed the `pytest` module. Otherwise, run:

```bash
pip install pytest
```

2. After you downloaded the code and installed the package, run the tests by executing:

```bash
python -m pytest test/
```

##  💻 Usage

### Converter module

#### Convert any *RGB* colour to *ANSI*
> ⚠️ **Warning**
> Some colour combinations between background and foreground are incompatible. The result can be slightly different from what is expected.
<details>
<summary><strong>Convert from <i>RGB</i> colour to <i>ANSI</i></strong></summary>

```python
# How to print a green text on a white background
from ansiconverter.converter import RGBtoANSI
from ansiconverter import RGBtoANSI
print(RGBtoANSI(text='Green text on a white background',foregound=[0, 255, 0], background=[255, 255, 255]))

```
**Result:**

<img src ="https://user-images.githubusercontent.com/25958977/190724022-a8b6e7cf-60e7-4493-9d9b-14b28be7268a.png" width=700 >

#### Convert any *hexadecimal* colour to *ANSI*
**Result**:
<img src ="https://github.com/thomassamoth/ansiconverter/assets/25958977/76d6d253-4176-4891-adae-8df05e56d62f" height=50 >
</details>

> **Warning**
Some colour combinations are incompatible, and the result will be [slightly different](#convert-any-rgb-colour-to-ansi) from what is expected.
<details>
<summary>
<strong>Convert from <i>hexadecimal</i> to <i>ANSI</i></strong>
</summary>

```python
# How to print a yellow text on a navy blue background, with hexadecimal values.
from ansiconverter.converter import HEXtoANSI

from ansiconverter import HEXtoANSI
print(HEXtoANSI('Some yellow text on blue background','#fdf31f', '000080'))

```
**Result**:

<img src="https://user-images.githubusercontent.com/25958977/190716452-69a8f8df-6f2d-4a79-94c2-f601dc4b4466.png" width=700)>
**Result**:
<img src="https://github.com/thomassamoth/ansiconverter/assets/25958977/40954308-5be6-4e69-b8a8-c08a63224a03" height=50)>
</details>

### Styles module &#127912;
> &#8505;&#65039; **Note**
> Another little tool has been added to convert RGB to hexadecimal and vice versa. It can't be used to write in color in the terminal but could be useful for other applications.
Write your text in different styles:
<details>
<summary>
<strong>Convert from <i>hexadecimal</i> to <i>RGB</i></strong>
</summary>

* bold
* italic
* faint
* underlined
* bold & underlined
* strikethrough
* reversed
```python
from ansiconverter import HEXtoRGB
print(HEXtoRGB("#0b38c1"))
```

**Result** :
```python
[11, 59, 193]
```
</details>


from ansiconverter.styles import styles
<details>
<summary>
<strong>Convert from <i>RGB</i> to <i>hexadecimal</i></strong>
</summary>

print(styles.bold("Some text in bold"))
```python
from ansiconverter import RGBtoHEX
print(RGBtoHEX([11, 59, 193]))
```

### &#9879; Combination of colours and styles
**Result** :
```python
"#0b3bc1"
```
</details>
<hr/>

It is possible to combine text styles with colours by doing so:
### &#127912; Styles module

```python
from ansiconverter.converter import *
from ansiconverter.styles import styles
Several text styles are available as well. You can even [combine them with colours](#combination-of-colours-and-styles)

print(styles.bold(HEXtoANSI('A yellow text in bold','#f6cf6c')))
| Style | Method |
|------------------------------|----------------------|
| bold | `bold` |
| italic | `italic` |
| fainted | `faint` |
| underlined | `underline` |
| bold & underlined | `bold_and_underline` |
| strikethroughed | `strikethrough` |
| reversed _(colours inverted)_ | `reverse` |

```

**Result:**
```python
from ansiconverter import bold

<img src="https://user-images.githubusercontent.com/25958977/190715961-3a3da6e1-bf9f-4011-8644-29c3efa4f263.png" width=700>
print(bold("Some text in bold"))
```
Replace `.bold` in the example with any method above to get the desired style.

You can replace `styles.bold()` by any function mentionned [above](#styles-module) i.e. `styles.italic()`. You can even **combine** different styles!
<hr/>

## &#10133; Additional features
### Combination of colours and styles

You can also use ***RGB to HEX*** converter or ***HEX to RGB*** by themselves like this:
&#9879;&#65039; It is possible to combine text styles with colours by doing so:

``` python
>>> from ansiconverter import converter
```python
from ansiconverter import HEXtoANSI, bold
print(bold(HEXtoANSI('A yellow text in bold','#f6cf6c')))
```

>>> print(converter.HEXtoRGB("#0b38c1"))
[11, 59, 193])
**Result:**
<img src="https://github.com/thomassamoth/ansiconverter/assets/25958977/4936657f-a536-497e-b8da-4df1d8f53813" height=50>

>>> print(converter.RGBtoHEX([11, 59, 193]))
"#0b3bc1"
**N.B**: the order between the style and the text format isn't important and you can switch them.

```python
print(bold(HEXtoANSI('A yellow text in bold','#f6cf6c')))
```
#

> **Note**
This repository is based on [Mark Smith](https://github.com/judy2k)'s talk available [here](https://youtu.be/GIF3LaRqgXo) and its [linked repository](https://github.com/judy2k/publishing_python_packages_talk)
will work the same as

```python
print(HEXtoANSI(bold('A yellow text in bold'),'#f6cf6c'))
```

## Note

This structure of this repository is based on a talk by [Mark Smith](https://github.com/judy2k), which is available [here](https://youtu.be/GIF3LaRqgXo), and its [linked repository](https://github.com/judy2k/publishing_python_packages_talk)

## License
This repository is licensed under the MIT license. See the [LICENSE](LICENSE.md) file for more information.
24 changes: 22 additions & 2 deletions ansiconverter/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,22 @@
from . import converter
from . import styles
from .converter import Converter
from .styles import Styles

# Export the Styles class and styling functions
bold = Styles().bold
faint = Styles().faint
italic = Styles().italic
underline = Styles().underline
bold_and_underline = Styles().bold_and_underline
strikethrough = Styles().strikethrough
reverse = Styles().reverse

# Export the Converter methods
RGBtoANSI = Converter().RGBtoANSI
RGBtoHEX = Converter().RGBtoHEX
HEXtoANSI = Converter().HEXtoANSI
HEXtoRGB = Converter().HEXtoRGB

# Are imported whrn writing from ansiconverter import *
__all__ = ['Styles', 'bold', 'faint', 'italic', 'underline', 'bold_and_underline', 'strikethrough', 'reverse',]

__all__.extend(['RGBtoANSI', 'RGBtoHEX', 'HEXtoANSI', 'HEXtoRGB'])
148 changes: 74 additions & 74 deletions ansiconverter/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,82 +4,82 @@
"""


RESET = "\x1b[0m"


def RGBtoANSI(text: str, foregound=[255, 255, 255], background=[],):
"""Write a text in RGB colour.
Args:
text (str): the text you want to write.
foregound (list, optional): RGB foregound's colour. Defaults to [255, 255, 255].
background (list, optional): RGB background's colour. Defaults to [].
Raises:
ValueError: the foregound colour can't be an empty list.
Returns:
string: the ANSI code for the foreground and the background.
"""
if foregound != []:
if background == []:
return f"\033[38;2;{foregound[0]};{foregound[1]};{foregound[2]}m{str(text)}{RESET}"
class Converter:
"""ANSI conversions and an additional function to convert RGB to HEX."""

RESET = "\x1b[0m"

@staticmethod
def RGBtoANSI(
text: str,
foregound=[255, 255, 255],
background=[],
):
"""Write a text in RGB color.
Args:
text (str): the text you want to write.
foregound (list, optional): RGB foregound's color. Defaults to [255, 255, 255].
background (list, optional): RGB background's color. Defaults to [].
Raises:
ValueError: the foregound color can't be an empty list.
Returns:
string: the ANSI code for the foreground and the background.
"""
if foregound != []:
if background == []:
return f"\033[38;2;{foregound[0]};{foregound[1]};{foregound[2]}m{str(text)}{Converter.RESET}"
else:
return f"\033[38;2;{foregound[0]};{foregound[1]};{foregound[2]}m\033[48;2;{background[0]};{background[1]};{background[2]}m{str(text)}{Converter.RESET}"
else:
return f"\033[38;2;{foregound[0]};{foregound[1]};{foregound[2]}m\033[48;2;{background[0]};{background[1]};{background[2]}m{str(text)}{RESET}"
else:
raise ValueError(
"The foregound can't be an empty list!\nNo paramaters will write the text in write"
)


def HEXtoRGB(fg="#000000"):
"""Convert a hexadecimal colour to its RGB triplet.
Args:
fg (str, optional): Hexadecimal colour value. Defaults to "#000000".
Raises:
ValueError: The colour is not a correct hexadecimal value.
Returns:
list: triplet of RGB values.
"""
foreground = ""
while True:
foreground = fg.lstrip("#").lower()
if len(foreground) == 6:
return list(int(foreground[i: i + 2], base=16) for i in (0, 2, 4))
raise ValueError(
"The foregound can't be an empty list!\nNo paramaters will write the text in write"
)

@staticmethod
def HEXtoRGB(fg="#000000"):
"""Convert a hexadecimal color to its RGB triplet.
Args:
fg (str, optional): Hexadecimal color value. Defaults to "#000000".
Raises:
ValueError: The color is not a correct hexadecimal value.
Returns:
list: triplet of RGB values.
"""
foreground = ""
while True:
foreground = fg.lstrip("#").lower()
if len(foreground) == 6:
return list(int(foreground[i : i + 2], base=16) for i in (0, 2, 4))

else:
raise ValueError("Enter a valid hexadecimal value")
return 1

@staticmethod
def HEXtoANSI(text, foreground="#ffffff", background=""):
from ansiconverter import HEXtoRGB, RGBtoANSI

foregroundRGB = HEXtoRGB(foreground)
if foreground != "":
if background != "":
backgroundRGB = HEXtoRGB(background)
return RGBtoANSI(text, foregroundRGB, backgroundRGB)
else:
return RGBtoANSI(text, foregroundRGB)

else:
raise ValueError("Enter a valid hexadecimal value")
return 1

raise ValueError("Please enter at least one foreground color.")

def HEXtoANSI(text, foreground="#ffffff", background=""):
from ansiconverter.converter import HEXtoRGB

foregroundRGB = HEXtoRGB(foreground)
if foreground != "":
if background != "":
backgroundRGB = HEXtoRGB(background)
return RGBtoANSI(text, foregroundRGB, backgroundRGB)
@staticmethod
# Utility to convert to other color format
def RGBtoHEX(rgb=[255, 255, 255]):
if rgb != []:
return f"#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}"
else:
return RGBtoANSI(text, foregroundRGB)

else:
raise ValueError("Please enter at least one foreground colour.")


def RGBtoHEX(rgb=[255, 255, 255]):
"""Convert any RGB colour to hexadecimal.
Args:
rgb (list, optional): the colour you want to convert. Defaults to [255, 255, 255].
Returns:
string: colour's hexadecimal value
"""
if rgb != []:
return f"#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}"
else:
raise (ValueError(f"The colour can't be an empty list. Please retry."))
raise ValueError(f"The color can't be an empty list. Please retry.")
Loading

0 comments on commit 0144ec2

Please sign in to comment.