ascii / app.py
sudo-soldier's picture
Update app.py
01fd3af verified
import gradio as gr
from PIL import Image
import numpy as np
import tempfile
def convert_to_ascii(image, char_set, bg_toggle, color_toggle):
width = 100
img = image.convert('RGB')
aspect_ratio = img.height / img.width
height = int(width * aspect_ratio)
img = img.resize((width, height))
pixels = np.array(img)
if char_set == "Symbols":
chars = "@%#*+=-:. "
elif char_set == "Inverted":
chars = " .:-=+*#%@"
elif char_set == "Numbers":
chars = "0123456789"
ascii_art = ""
html_ascii_art = ""
for i in range(height):
for j in range(width):
r, g, b = pixels[i, j]
brightness = (r + g + b) / 3
char_index = int((brightness / 255) * (len(chars) - 1))
char = chars[len(chars) - 1 - char_index]
if bg_toggle and r == g == b == 255:
ascii_art += " "
html_ascii_art += " "
else:
if color_toggle:
html_ascii_art += f'<span style="color: rgb({r},{g},{b})">{char}</span>'
ascii_art += char
else:
ascii_art += char
html_ascii_art += char
ascii_art += "\n"
html_ascii_art += "<br>"
if color_toggle:
temp = tempfile.NamedTemporaryFile(delete=False, suffix=".html")
temp.write(html_ascii_art.encode('utf-8'))
else:
temp = tempfile.NamedTemporaryFile(delete=False, suffix=".txt")
temp.write(ascii_art.encode('utf-8'))
temp.close()
return html_ascii_art, temp.name
def create_interface():
image_input = gr.Image(type="pil", label="Upload Image")
char_set_input = gr.Radio(choices=["Symbols", "Inverted", "Numbers"], label="Character Set")
bg_toggle_input = gr.Checkbox(label="Enable Background Transparency", value=False)
color_toggle_input = gr.Checkbox(label="Enable Color", value=True)
output_html = gr.HTML(label="ASCII Art Output")
download_output = gr.File(label="Download ASCII Art")
interface = gr.Interface(
fn=convert_to_ascii,
inputs=[image_input, char_set_input, bg_toggle_input, color_toggle_input],
outputs=[output_html, download_output],
live=True,
title="Image to ASCII Converter",
description="""Convert your images into ASCII art instantly.
The website [JesseJesse.xyz](https://ascii.JesseJesse.xyz)
Download the [Android](https://ascii.JesseJesse.xyz/ascii.apk) App
"""
)
return interface
if __name__ == "__main__":
interface = create_interface()
interface.launch()