aurebesh / bin /generate.py
SauravMaheshkar's picture
docs: update
866064d unverified
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "datasets",
# "pillow",
# ]
# ///
import json
import os
import re
from datasets import load_dataset
from PIL import Image, ImageDraw, ImageFont
FONT_PATH = "assets/Aurebesh"
FONT_SIZE = 50
IMAGE_SIZE = (784, 784)
OUTPUT_DIR = "images"
font = ImageFont.truetype(FONT_PATH, FONT_SIZE)
##### Get all words from Paul Graham Essays #####
paul_graham_ds = load_dataset("sgoel9/paul_graham_essays", split="train")
all_words = []
for entry in paul_graham_ds:
text = str(entry["text"]) # pyright: ignore
words = re.findall(r"\b\w+\b", text.lower())
all_words.extend(words)
def generate_aurebesh_image(text, output_dir):
# TODO: Generate images with various background colours
img = Image.new("RGB", IMAGE_SIZE, color=(255, 255, 255))
d = ImageDraw.Draw(img)
# TODO: Experiment with various orientations
bbox = d.textbbox((0, 0), text, font=font)
# atm, text is rendered in the center
text_width, text_height = bbox[2] - bbox[0], bbox[3] - bbox[1]
position = ((IMAGE_SIZE[0] - text_width) // 2, (IMAGE_SIZE[1] - text_height) // 2)
# Add the text to the image
d.text(position, text, font=font, fill=(0, 0, 0))
# Save the image
if not os.path.exists(output_dir):
os.makedirs(output_dir)
img.save(os.path.join(output_dir, f"{text}.png"))
captions = []
for word in all_words:
clean_word = re.sub(r"\W+", "", word)
generate_aurebesh_image(clean_word, OUTPUT_DIR)
captions.append({"file_name": f"{clean_word}.png", "text": word})
with open(os.path.join(OUTPUT_DIR, "metadata.jsonl"), "w") as f:
for item in captions:
f.write(json.dumps(item) + "\n")
dataset = load_dataset("imagefolder", data_dir=OUTPUT_DIR, split="all")
dataset.push_to_hub("SauravMaheshkar/aurebesh") # pyright: ignore