File size: 9,850 Bytes
6ed23ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""
Created Date: 09-26-2024
Updated Date: -
Author: Chaitanya Chadha
"""

import streamlit as st
from transformers import AutoImageProcessor, ResNetForImageClassification
import torch
from PIL import Image, ImageDraw, ImageFont
import math
import os
import io
from datetime import datetime

# Set page configuration at the very beginning
st.set_page_config(page_title="🎨 Colored ASCII Art Generator", layout="wide")

# Initialize model and processor once to improve performance
@st.cache_resource
def load_model_and_processor():
    processor = AutoImageProcessor.from_pretrained("microsoft/resnet-50")
    model = ResNetForImageClassification.from_pretrained("microsoft/resnet-50")
    return processor, model

processor, model = load_model_and_processor()

def Classify_Image(image):
    """
    Classifies the image using a pre-trained ResNet-50 model.
    Returns the predicted label.
    """
    inputs = processor(image, return_tensors="pt")
    with torch.no_grad():
        logits = model(**inputs).logits
    # model predicts one of the 1000 ImageNet classes
    predicted_label = logits.argmax(-1).item()
    return model.config.id2label[predicted_label]

def resize_image(image, new_width=100):
    width, height = image.size
    aspect_ratio = height / width
    # Adjusting height based on the aspect ratio and a scaling factor
    new_height = int(aspect_ratio * new_width * 0.55)
    resized_image = image.resize((new_width, new_height))
    return resized_image

def grayify(image):
    return image.convert("L")

def calculate_image_entropy(image):
    # Calculates the entropy of the grayscale image to determine its complexity.
    # Higher entropy indicates a more complex image with more details.
    histogram = image.histogram()
    histogram_length = sum(histogram)

    samples_probability = [float(h) / histogram_length for h in histogram if h != 0]
    entropy = -sum([p * math.log(p, 2) for p in samples_probability])

    return entropy

def select_character_set(entropy, art_gen_choice, classification):
    ASCII_CHARS_SETS = {
        "standard": [
            '@', '%', '#', '*', '+', '=', '-', ':', '.', ' '
        ],
        "detailed": [
            '$', '@', 'B', '%', '8', '&', 'W', 'M', '#', '*', 'o', 'a', 'h', 'k', 'b',
            'd', 'p', 'q', 'w', 'm', 'Z', 'O', '0', 'Q', 'L', 'C', 'J', 'U', 'Y',
            'X', 'z', 'c', 'v', 'u', 'n', 'x', 'r', 'j', 'f', 't', '/', '\\', '|',
            '(', ')', '1', '{', '}', '[', ']', '?', '-', '_', '+', '~', '<', '>',
            'i', '!', 'l', 'I', ';', ':', ',', '"', '^', '', "'", '.', ' '
        ],
        "simple": [
            '#', '*', '+', '=', '-', ':', '.', ' '
        ],
        "custom": [
            "!", "~", "@", "#", "$", "%", "Β¨", "&", "*", "(", ")", "_", "+", "-",
            "=", "{", "}", "[", "]", "|", "\\", "/", ":", ";", "'", "\"", ",", "<",
            ".", ">", "?", " " ] + list(set(list(str(classification))))
    }

    if art_gen_choice.lower() == "custom":
        selected_set = "custom"
        return ASCII_CHARS_SETS[selected_set]
    else:
        # Define entropy thresholds (these values can be adjusted based on experimentation)
        if entropy < 4.0:
            selected_set = "simple"
        elif 4.0 <= entropy < 5.5:
            selected_set = "standard"
        else:
            selected_set = "detailed"

        return ASCII_CHARS_SETS[selected_set]

def determine_optimal_width(image, max_width=120):
    # Determines the optimal width for the ASCII art based on the image's original dimensions.
    original_width, original_height = image.size
    if original_width > max_width:
        return max_width
    else:
        return original_width

def render_ascii_to_image(ascii_chars, img_width, img_height, font_path="fonts/DejaVuSansMono.ttf", font_size=10):
    # Renders the ASCII characters onto an image with their corresponding colors.
    if not os.path.isfile(font_path):
        st.error(f"Font file not found at {font_path}. Please provide a valid font path.")
        return None

    # Create a new image with white background
    try:
        font = ImageFont.truetype(font_path, font_size)
    except Exception as e:
        st.error(f"Error loading font: {e}")
        return None

    # Get character dimensions
    # Using getbbox which is compatible with Pillow >= 8.0
    left, top, right, bottom = font.getbbox('A')
    char_width = right - left
    char_height = bottom - top
    image_width = char_width * img_width
    image_height = char_height * img_height
    new_image = Image.new("RGB", (image_width, image_height), "white")
    draw = ImageDraw.Draw(new_image)

    for i, (char, color) in enumerate(ascii_chars):
        x = (i % img_width) * char_width
        y = (i // img_width) * char_height
        draw.text((x, y), char, fill=color, font=font)

    return new_image

def pixels_to_colored_ascii(grayscale_image, color_image, chars):
    # Maps each pixel to an ASCII character from the selected character set.
    # Returns a list of tuples: (character, (R, G, B))
    grayscale_pixels = grayscale_image.getdata()
    color_pixels = color_image.getdata()
    ascii_chars = []

    for grayscale_pixel, color_pixel in zip(grayscale_pixels, color_pixels):
        # Scale grayscale pixel value to the range of the character set
        index = grayscale_pixel * (len(chars) - 1) // 255
        ascii_char = chars[index]

        # Extract RGB values; ignore alpha if present
        if len(color_pixel) == 4:
            r, g, b, _ = color_pixel
        else:
            r, g, b = color_pixel

        ascii_chars.append((ascii_char, (r, g, b)))

    return ascii_chars

def generate_ascii_art(image, font_path="fonts/DejaVuSansMono.ttf", font_size=12):
    # image: PIL Image object

    # Classify the image
    image_class = Classify_Image(image)
    st.write(f"**Image Classification:** {image_class}")

    # Convert to grayscale and calculate entropy
    grayscale_image = grayify(image)
    entropy = calculate_image_entropy(grayscale_image)
    st.write(f"**Image Entropy:** {entropy:.2f}")

    # Select character set
    art_gen_choice = st.session_state.get('art_gen_choice', 'custom')
    selected_chars = select_character_set(entropy, art_gen_choice, image_class)
    st.write(f"**Selected Character Set:** '{art_gen_choice}' with {len(selected_chars)} characters.")

    # Determine optimal width
    optimal_width = determine_optimal_width(image)
    st.write(f"**Selected Width:** {optimal_width}")

    # Resize images
    resized_image = resize_image(image, optimal_width)
    grayscale_resized_image = grayify(resized_image)
    color_resized_image = resized_image.convert("RGB")  # Ensure image is in RGB mode

    # Convert pixels to ASCII
    ascii_chars = pixels_to_colored_ascii(grayscale_resized_image, color_resized_image, selected_chars)

    # Create ASCII string
    ascii_str = ''.join([char for char, color in ascii_chars])
    ascii_lines = [ascii_str[index: index + optimal_width] for index in range(0, len(ascii_str), optimal_width)]
    ascii_art = "\n".join(ascii_lines)

    return ascii_art, ascii_chars, resized_image.size

def main():
    # Title and Description are already set after set_page_config
    st.title("🎨 Colored ASCII Art Generator")

    st.markdown("""
    Upload an image, and this app will convert it into colored ASCII art. 
    You can view the classification, entropy, and download or copy the ASCII art.
    """)

    # Sidebar for options
    st.sidebar.header("Options")
    art_gen_choice = st.sidebar.selectbox(
        "Character Set Choice",
        options=["custom", "standard", "detailed", "simple"],
        help="Select the character set to use for ASCII art generation."
    )
    st.session_state['art_gen_choice'] = art_gen_choice

    # File uploader
    uploaded_file = st.file_uploader("Upload an Image", type=["png", "jpg", "jpeg", "bmp", "gif"])

    if uploaded_file is not None:
        try:
            # Read the image
            image = Image.open(uploaded_file).convert("RGB")
            st.image(image, caption='Uploaded Image', use_column_width=True)

            # Generate ASCII Art
            with st.spinner("Generating ASCII Art..."):
                ascii_art, ascii_chars, resized_size = generate_ascii_art(image)

            # Display ASCII Art as Image
            ascii_image = render_ascii_to_image(
                ascii_chars,
                img_width=resized_size[0],
                img_height=resized_size[1],
                font_path="fonts/DejaVuSansMono.ttf",
                font_size=12
            )

            if ascii_image:
                st.image(ascii_image, caption='Colored ASCII Art', use_column_width=True)

                # Provide Download Button for ASCII Image
                img_byte_arr = io.BytesIO()
                ascii_image.save(img_byte_arr, format='PNG')
                img_byte_arr = img_byte_arr.getvalue()

                st.download_button(
                    label="πŸ“₯ Download ASCII Art Image",
                    data=img_byte_arr,
                    file_name=f"ascii_art_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png",
                    mime="image/png"
                )

            # Display ASCII Art as Text with Copy Option
            st.text_area("ASCII Art", ascii_art, height=300)

            # Provide a download button for the ASCII text
            st.download_button(
                label="πŸ“„ Download ASCII Art Text",
                data=ascii_art,
                file_name=f"ascii_art_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
                mime="text/plain"
            )

        except Exception as e:
            st.error(f"An error occurred: {e}")
    else:
        st.info("Please upload an image to get started.")

if __name__ == "__main__":
    main()