New

SingleStore April Challenge: Haiku ASCII

Notebook


SingleStore Notebooks

SingleStore April Challenge: Haiku ASCII

📣 SingleStore's Creative Challenge for #NationalPoetryMonth: Win RayBan Smart sunglasses 😎 and a $500 AWS gift card! 💸


This notebook can be run on the SingleStore Free Shared Tier Workspace.

To create a Shared Tier Workspace, please visit: https://www.singlestore.com/cloud-trial


🎉 All throughout April, SingleStore is hosting a challenge inviting participants to craft a unique Haiku or create captivating ASCII art using SingleStore Notebooks. The most creative masterpiece wins a set of Meta RayBan Smart sunglasses and a $500 AWS gift card!

➡️ Steps to Participate

✅ Activate your Free Shared Tier with SingleStore here: https://www.singlestore.com/cloud-trial

✅ Create your artistic masterpiece in a SingleStore Notebook, drawing inspiration from this example Notebook and your unique vision.

✅ Share a Github link to your notebook by April 30, 2024: https://docs.google.com/forms/d/e/1FAIpQLSdXcvzSxtTtHYxRG40Pc5HVknxu6EbngDrsX6ukzkEbRu26ww/viewform

✅ Make sure to tag @SingleStore and use #SingleStorePoetry when sharing your work on LinkedIn/X


For questions about this contest or SingleStore Notebooks, use our dedicated Discord channel: https://discord.gg/re56Fwyd

Feel free to make changes to this starter code to generate a Haiku and ASCII art. The below code consists of two main parts:

  1. Generating a Haiku: The generate_haiku function creates a simple haiku using pre-defined lists of phrases that correspond to the traditional 5-7-5 syllable structure of haikus. This function randomly selects one phrase from each list to construct the haiku.

  2. Visualizing the Haiku: The visualize_haiku function uses matplotlib to create a visualization of the generated haiku. It sets up a figure with a custom background color, hides the axes for a cleaner look, and displays the haiku text in the center with a styled bounding box around it.

In [1]:

1!pip install matplotlib --quiet

Generating a Haiku with Seasonal Transitions

In [2]:

1import numpy as np2import matplotlib.pyplot as plt3from matplotlib.colors import LinearSegmentedColormap4import matplotlib.image as mpimg  # Import for loading the logo image5import requests  # Import requests to download the logo6from PIL import Image  # Import PIL to handle the image7from io import BytesIO  # Import BytesIO to handle the image as a byte stream8
9# Seasonal Transition Haiku Generator10def generate_seasonal_transition_haiku():11    seasons = ["Winter", "Spring", "Summer", "Fall"]12    transitions = {13        ("Winter", "Spring"): [14            "Data thaws with grace,",  # 5 syllables15            "Queries swiftly bloom, unfurl,",  # 7 syllables16            "Insight crisp and clear."  # 5 syllables17        ],18        ("Spring", "Summer"): [19            "Insights grow in light,",  # 5 syllables20            "Data scales the bright, warm sun,",  # 7 syllables21            "Wisdom on full show."  # 5 syllables22        ],23        ("Summer", "Fall"): [24            "Leaves of data turn,",  # 5 syllables25            "Decisions ripe and well-earned,",  # 7 syllables26            "Change whispers anew."  # 5 syllables27        ],28        ("Fall", "Winter"): [29            "Data's frost sets in,",  # 5 syllables30            "Vector cycles glean insights,",  # 7 syllables31            "Silence holds the keys."  # 5 syllables32        ],33    }34
35    # Randomly select a transition36    start_season = np.random.choice(seasons)37    end_season = seasons[(seasons.index(start_season) + 1) % len(seasons)]38
39    haiku_lines = transitions[(start_season, end_season)]40
41    return haiku_lines, start_season, end_season42
43# Visualization with Gradient44def visualize_seasonal_transition(haiku, start_season, end_season):45    fig, ax = plt.subplots(figsize=(10, 6))46    ax.axis('off')47
48    # Seasonal Colors49    colors = {50        "Winter": "#ffffff",51        "Spring": "#4caf50",52        "Summer": "#ffa726",53        "Fall": "#fb8c00"54    }55
56    # Create Gradient57    cmap = LinearSegmentedColormap.from_list("season_transition", [colors[start_season], colors[end_season]])58    gradient = np.linspace(0, 1, 256)59    gradient = np.vstack((gradient, gradient))60
61    ax.imshow(gradient, aspect='auto', cmap=cmap, extent=[0, 10, 0, 10])62
63    # Display Haiku64    ax.text(5, 5, "\n".join(haiku), ha='center', va='center', fontsize=14, color="black")65
66    # Download the logo67    logo_url = "https://raw.githubusercontent.com/singlestore-labs/spaces-notebooks/master/common/images/singlestore-logo-vertical.png"68    response = requests.get(logo_url)69    logo_img = Image.open(BytesIO(response.content))70
71    # Convert the Image object to a NumPy array and display it72    logo = np.array(logo_img)73    ax_logo = fig.add_axes([0.75, -0.05, 0.15, 0.15])  # Adjust these values to position and scale the logo74    ax_logo.imshow(logo)75    ax_logo.axis('off')  # Hide the axis of the logo subplot76
77    plt.show()78
79# Generate and Visualize80haiku, start_season, end_season = generate_seasonal_transition_haiku()81visualize_seasonal_transition(haiku, start_season, end_season)

ASCII Art Generation

Note that you might have to add the URL to firewall when asked to do so, to be able to access your input image in the below code

In [3]:

1!pip install Pillow requests --quiet

In [4]:

1import requests2from PIL import Image3from io import BytesIO4
5# Define the ASCII characters that will be used to replace the pixels.6ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]7
8def resize_image(image, new_width=100):9    width, height = image.size10    ratio = height / width / 1.65  # Correct for aspect ratio11    new_height = int(new_width * ratio)12    resized_image = image.resize((new_width, new_height))13    return resized_image14
15def grayify(image):16    grayscale_image = image.convert("L")17    return grayscale_image18
19def pixels_to_ascii(image):20    pixels = image.getdata()21    ascii_str = ''22    for pixel in pixels:23        ascii_str += ASCII_CHARS[pixel // 25]  # Map the pixel value to ASCII_CHARS24    return ascii_str25
26def process_image_from_url(image_url, new_width=100):27    # Fetch the image from the URL28    response = requests.get(image_url)29    if response.status_code == 200:30        # Open the image from the bytes in response content31        image = Image.open(BytesIO(response.content))32
33        # Process the image34        image = resize_image(image, new_width)35        image = grayify(image)36        ascii_str = pixels_to_ascii(image)37
38        # Format the ASCII string so that each line has `new_width` characters.39        img_width = image.width40        ascii_str_len = len(ascii_str)41        ascii_img = ""42        for i in range(0, ascii_str_len, img_width):43            ascii_img += ascii_str[i:i+img_width] + "\n"44
45        # Print the ASCII art46        print(ascii_img)47    else:48        print("Failed to retrieve the image from the URL")49
50# Example usage with a public image URL51image_url = 'https://raw.githubusercontent.com/singlestore-labs/spaces-notebooks/master/common/images/singlestore-banner.png'  # Replace with your image's URL52process_image_from_url(image_url, 100)


➡️ Next Steps:

✅ Share a Github link to your notebook by April 30, 2024: https://docs.google.com/forms/d/e/1FAIpQLSdXcvzSxtTtHYxRG40Pc5HVknxu6EbngDrsX6ukzkEbRu26ww/viewform

✅ Make sure to tag @SingleStore and use #SingleStorePoetry when sharing your work on LinkedIn/X

Details


About this Template

SingleStore is hosting a challenge inviting participants to craft a unique Haiku or create captivating ASCII art using SingleStore Notebooks. The most creative masterpiece wins a set of Meta RayBan Smart sunglasses and a $500 AWS gift card!"

This Notebook can be run in Standard and Enterprise deployments.

Tags

challengehaikuascii

License

This Notebook has been released under the Apache 2.0 open source license.

See Notebook in action

Launch this notebook in SingleStore and start executing queries instantly.