Giter VIP home page Giter VIP logo

python-ascii_magic's Introduction

ASCII Magic

Python package that converts images into ASCII art for terminals and HTML. Thanks to Colorama it's compatible with the Windows terminal.

Code based on ProfOak's Ascii Py.

Changelog

v2.3 - Feb 2023

  • Craiyon support: from_craiyon()

v2.2 - Feb 2023

  • Stable Diffusion support: from_stable_diffusion()

v2.1 - Feb 2023

  • DALL-E support: from_dalle()

v2.0 - Feb 2023

  • Complete rewrite, full OOP, no longer compatible with 1.x
  • Added support for foreground color
  • to_html()

v1.6 - Sep 2021

  • OOP functionality
  • to_file()

v1.5 - Nov 2020

  • First public release

How to install

pip install ascii_magic

Quickstart

from ascii_magic import AsciiArt

my_art = AsciiArt.from_image('moon.jpg')
my_art.to_terminal()

Result:

ASCII Magic example

The class AsciiArt

This module's entire functionality is contained within the class AsciiArt, which has a collection class methods, such as AsciiArt.from_image(), that return AsciiArt objects with pictures from different sources: files, URLs, the clipboard, etc.

These objects have multiple methods, such as my_art.to_terminal(), that generate ASCII art pieces from the picture. These methods have parameters such as columns that allow you to change the appearance of the art piece.

For convenience, the module ascii_magic also exposes a collection of functions with the same name as the class methods mentioned above, which do exactly the same.

Example:

from ascii_magic import AsciiArt, from_image

# This:
my_art = AsciiArt.from_image('lion.jpg')
my_art.to_terminal()

# Does the same as this:
my_art = from_image('lion.jpg')
my_art.to_terminal()

This class is essentially a wrapper for a Pillow image. The property AsciiArt.image exposes the underlying Pillow object so you can manipulate it directly.

Example:

from ascii_magic import AsciiArt
from PIL import ImageEnhance

my_art = AsciiArt.from_image('lion.jpg')
my_art.image = ImageEnhance.Brightness(my_art.image).enhance(0.2)
my_art.to_terminal()

quick_test()

Loads a random Unsplash picture with the default parameters and prints it to the terminal, allowing you to verify in a single line of code that everything is running O.K.

AsciiArt.quick_test() -> None

Example:

from ascii_magic import AsciiArt

AsciiArt.quick_test()

from_image()

Creates an AsciiArt object from an image file.

from_image(path: str) -> AsciiArt

Parameters:

  • path (str): an image file compatible with Pillow, such as a jpeg or png

Example:

from ascii_magic import AsciiArt, Back

my_art = AsciiArt.from_image('lion.jpg')
my_art.to_terminal(columns=200, back=Back.BLUE)

Result:

ASCII Magic TERMINAL mode example

Example:

from ascii_magic import AsciiArt

my_art = AsciiArt.from_image('lion.jpg')
my_art.to_html_file('ascii_art.html', columns=200, width_ratio=2)

Result:

ASCII Magic HTML mode example

Example:

from ascii_magic import AsciiArt

my_art = AsciiArt.from_image('lion.jpg')
my_art.to_terminal(columns=200, monochrome=True)

Result:

ASCII Magic ASCII mode example

from_craiyon()

Creates an AsciiArt object with Craiyon, previously known as DALL-E Mini, a machine learning model that can generate realistic images from a description in natural language.

Keep in mind that this process can take one minute or more!

from_craiyon(prompt: str) -> AsciiArt

Parameters:

  • prompt (str): a description of an image in natural language

Example:

from ascii_magic import AsciiArt

my_art = AsciiArt.from_craiyon('A portrait of a cow with noble clothes')
my_art.to_html_file('cow_craiyon.html', columns=200)

Result:

ASCII Magic Craiyon example

from_dalle()

Creates an AsciiArt object with DALL-E, a machine learning model that can generate realistic images from a description in natural language. Requires a DALL-E API key. The API key can be configured in the module as described in the OpenAI documentation (openai.api_key = api_key) or through this function call.

from_dalle(
    prompt: str,
    api_key: Optional[str]
) -> AsciiArt

Parameters:

  • prompt (str): a description of an image in natural language
  • api_key (str, optional): a DALL-E API key

Example:

from ascii_magic import AsciiArt

api_key = 'SK-AFAKEDALLEAPIKEY'
my_art = AsciiArt.from_dalle('A portrait of a cow with noble clothes', api_key)
my_art.to_html_file('cow_dalle.html', columns=200)

Result:

ASCII Magic DALL-E example

from_stable_diffusion()

Creates an AsciiArt object with Stable Diffusion, a machine learning model that can generate realistic images from a description in natural language. Requires a Stable Diffusion API key.

from_stable_diffusion(
    prompt: str,
    api_key: str,
    steps: int = 30,
    engine: Optional[str],
) -> AsciiArt

Parameters:

  • prompt (str): a description of an image in natural language
  • api_key (str, optional): a Stable Diffusion API key
  • steps (int, optional): amount of inference steps performed (see Stable Diffusion documentation)
  • engine (str, optional): set the engine to use for generation (see Stable Diffusion documentation)

Example:

from ascii_magic import AsciiArt

api_key = 'SK-AFAKESTABLEDIFFUSIONAPIKEY'
my_art = AsciiArt.from_stable_diffusion('A portrait of a cow with noble clothes', api_key)
my_art.to_html_file('cow_stable_diffusion.html', columns=200)

Result:

ASCII Magic Stable Diffusion example

from_url()

Creates an AsciiArt object from an image URL. Raises an urllib.error.URLError if something goes wrong while requesting the image, but you can also catch it as an OSError if you don't want to import urllib into your project.

from_url(url: str) -> AsciiArt

Parameters:

  • url (str): an URL which will be loaded via urllib (supports redirects)

Example:

from ascii_magic import AsciiArt

try:
    my_art = AsciiArt.from_url('https://source.unsplash.com/800x600?nature')
except OSError as e:
    print(f'Could not load the image, server said: {e.code} {e.msg}')
my_art.to_terminal()

from_clipboard()

Creates an AsciiArt object from the contents of the clipboard. Raises an OSError if the clipboard doesn't contain an image. Requires PyGObject under Linux.

from_clipboard() -> AsciiArt

Example:

from ascii_magic import AsciiArt

try:
    my_art = AsciiArt.from_clipboard()
except OSError:
    print('The clipboard does not contain an image')
my_art.to_terminal()

from_pillow_image()

Creates an AsciiArt object from an image object created with Pillow. This allows you to handle the image loading yourself.

from_pillow_image(img: PIL.Image) -> AsciiArt

Parameters:

  • img (obj): an image object created with Pillow

Example:

from ascii_magic import AsciiArt
from PIL import Image

img = Image.open('lion.jpg')
my_art = AsciiArt.from_pillow_image(img)
my_art.to_terminal()

The AsciiArt object

An AsciiArt object created as explained above has a collection of methods, such as to_ascii(), that allows you to create and display ASCII art pieces. All of them return a string, and some have additional functionality, as described below.

to_ascii()

Returns a string containing ASCII art and, by default, control characters that allows most terminals (also known as shells) to display color.

The module ascii_magic exposes two enums to handle color: Front and Back which allow you to select terminal-compatible colors.

AsciiArt.to_ascii(
    columns: int = 120,
    width_ratio: float = 2.2,
    monochrome: bool = False,
    char: Optional[str],
    front: Optional[Front],
    back: Optional[Back]
) -> str

Parameters:

  • columns (int, optional): the number of characters per row, more columns = wider art
  • width_ratio (float, optional): ASCII characters are not squares, so this adjusts the width to height ratio during generation
  • monochrome (bool, optional): if set to True, disables the usage of control characters that display color
  • char (str, optional): instead of using many different ASCII glyphs, you can use a single one, such as '#'
  • front (enum, optional): overrides the foreground color with one of:
    • Front.BLACK
    • Front.RED
    • Front.GREEN
    • Front.YELLOW
    • Front.BLUE
    • Front.MAGENTA
    • Front.CYAN
    • Front.WHITE
  • back (enum, optional): sets the background color to one of:
    • Back.BLACK
    • Back.RED
    • Back.GREEN
    • Back.YELLOW
    • Back.BLUE
    • Back.MAGENTA
    • Back.CYAN
    • Back.WHITE

Example:

from ascii_magic import AsciiArt, Back

my_art = AsciiArt.from_image('lion.jpg')
my_output = my_art.to_ascii(columns=200, back=Back.BLUE)
print(my_output)

Result:

ASCII Magic TERMINAL mode example

to_terminal()

Identical to AsciiArt.to_ascii(), but it also does a print() of the result, saving you one line of code ;)

to_file()

Identical to AsciiArt.to_ascii(), but it also saves the result to a text file.

AsciiArt.to_file(
    path: str,
    # ... same parameters as AsciiArt.to_ascii()
) -> str

Parameters:

  • path (str): the output file path

Example:

from ascii_magic import AsciiArt

my_art = AsciiArt.from_image('lion.jpg')
my_art.to_file('lion.txt', monochrome=True)

to_html()

Returns a string with ASCII art created as HTML markup. Accepts the same parameters as AsciiArt.to_ascii(), except for back and front colors. By default the HTML ASCII art is generated with a 24-bit palette (16 million colors).

AsciiArt.to_html(
    full_color: bool = True,
    # ... same parameters as AsciiArt.to_ascii(), except back and front colors
) -> str

Parameters:

  • full_color (bool, optional): if set to False, limits color palette to 8 colors

Example:

from ascii_magic import AsciiArt

my_art = AsciiArt.from_image('lion.jpg')
my_html_markup = my_art.to_html(columns=200)

to_html_file()

Identical to AsciiArt.to_html(), but it also saves the markup to a barebones HTML file inside a <pre> tag with a bunch of default CSS styles that you can easily open in your browser.

AsciiArt.to_html_file(
    path: str,
    styles: str = '...',  # See description below
    additional_styles: str = '',
    auto_open: bool = False
    # ... same parameters as AsciiArt.to_html()
) -> str

Parameters:

  • path (str): the output file path
  • styles (str, optional): a string with a bunch of CSS styles for the <pre> element, by default:
    • display: inline-block;
    • border-width: 4px 6px;
    • border-color: black;
    • border-style: solid;
    • background-color: black;
    • font-size: 8px;
  • additional_styles (str, optional): use this to add your own CSS styles without removing the default ones
  • auto_open (bool, optional): if True, the file will be opened with webbrowser.open()

Example:

from ascii_magic import AsciiArt

my_art = AsciiArt.from_image('lion.jpg')
my_art.to_html_file('lion.html', columns=200, additional_styles='font-family: MonoLisa;')

Result:

ASCII Magic HTML mode example

Licence

Copyright (c) 2020 Leandro Barone.

Usage is provided under the MIT License. See LICENSE for the full details.

python-ascii_magic's People

Contributors

leandrobarone avatar leandrobaroneagrodreams avatar satyadahal avatar themrcodes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

python-ascii_magic's Issues

Brightness Correction

Since there is black/transparent area, the brightness, saturation and etc will look different (e.g. darker) from the original image. Any idea on the correction?

Linux support

Traceback (most recent call last):
File "convert.py", line 1, in
import ascii_magic
File "/home/gustavo/.local/lib/python3.8/site-packages/ascii_magic/init.py", line 2, in
from PIL import Image, ImageGrab
File "/usr/lib/python3/dist-packages/PIL/ImageGrab.py", line 26, in
raise ImportError("ImageGrab is macOS and Windows only")
ImportError: ImageGrab is macOS and Windows only

Ascii HTML Mode

When trying to use ascii_magic.Modes.HTML, this is generated instead.

Code:
import ascii_magic
output = ascii_magic.from_image_file("dogedemo.png", mode=ascii_magic.Modes.HTML)
ascii_magic.to_terminal(output)

Result:
image

Tag the source

It would be very helpful if you could tag releases as well. This would enable distributions who want to run your tests to fetch the package from GitHub instead of PyPI, where the tests are excluded.

Thanks

use set of chars instead of single char

The current behaviour of the optional char argument is to wrap the passed string in a list.

I don't why, but this actually limits the usefulness.

Simply removing the list, allows users to pass a string with the set of chars they wish to use.

Simply change
chars = [char] if char else CHARS_BY_DENSITY

To
chars = char if char else CHARS_BY_DENSITY

Strings are already iterable in python. This is also the current behaviour if char is None (CHARS_BY_DENSITY is just a string with all characters to be used).

Empty strings ('') evaluate to False, while strings with contents evaluate to True:

>>> test1 = ''
>>> test2 = '1'
>>> if test1: print(test1)
...
>>> if test2: print(test2)
...
1
>>>

craiyon api no more working

hi,
I think the api adress you were using for craiyon is no more working:
When i tried to use your example I had a "JSONDecodeError: Expecting value: line 1 column 1 (char 0)" visibly because the request you use had no answer.
I take a look and the "https://api.craiyon.com/draw" you used is no more existing.
I tried to replace in your code by the old version of Craiyon (https://backend.craiyon.com/generate) and by the new one (https://api.craiyon.com/v3) without success.
But that does not change that i appreciate a lot your library :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.