import csv import os from PIL import Image def normalize_hex(hex_color: str) -> str: """Make sure the hex color starts with #""" if not hex_color: return "#000000" hex_color = hex_color.strip() return hex_color if hex_color.startswith("#") else f"#{hex_color}" def replace_placeholders(prompt: str, row: dict) -> str: """Replace the placeholder in prompt""" color_format = row.get("color_format", "").strip() or "Hex code" mapping = { "": color_format, "": normalize_hex(row.get("color_1", "")), "": normalize_hex(row.get("color_2", "")), } out = prompt for k, v in mapping.items(): if k in out and v: out = out.replace(k, v) return out def generate_two_color_images_with_split(csv_file, base_dir, size=(256, 256)): with open(csv_file, "r", encoding="utf-8") as f: reader = csv.DictReader(f) rows = list(reader) for row in rows: id_val = row["id"].strip() hex1 = normalize_hex(row.get("color_1", "")) hex2 = normalize_hex(row.get("color_2", "")) prompt_raw = row.get("prompt", "").strip() split = (row.get("split") or "train").strip() direction = row.get("direction", "").strip() # Replace the placeholder in prompt prompt_filled = replace_placeholders(prompt_raw, row) # out_dir = os.path.join(base_dir, split) out_dir = base_dir os.makedirs(out_dir, exist_ok=True) # file path img_path = os.path.join(out_dir, f"id_{id_val}.png") txt_path = os.path.join(out_dir, f"id_{id_val}.txt") # Create a blank drawing img = Image.new("RGB", size) # direction if direction=="h": # horizontal Top and bottom split top = Image.new("RGB", (size[0], size[1] // 2), hex1) bottom = Image.new("RGB", (size[0], size[1] // 2), hex2) img.paste(top, (0, 0)) img.paste(bottom, (0, size[1] // 2)) elif direction=="v": # vertical Left and right split left = Image.new("RGB", (size[0] // 2, size[1]), hex1) right = Image.new("RGB", (size[0] // 2, size[1]), hex2) img.paste(left, (0, 0)) img.paste(right, (size[0] // 2, 0)) else: img = Image.new("RGB", size, hex1) img.save(img_path) # write prompt with open(txt_path, "w", encoding="utf-8") as f: f.write(prompt_filled) print(f"Generate: {img_path}, {txt_path} (split={split}, colors={hex1},{hex2})") generate_two_color_images_with_split( "metadata/Variation_2_Color_1.csv", base_dir="data/Variation_2/Color_Level_1" ) generate_two_color_images_with_split( "metadata/Variation_2_Color_2.csv", base_dir="data/Variation_2/Color_Level_2" ) generate_two_color_images_with_split( "metadata/Variation_2_Color_3.csv", base_dir="data/Variation_2/Color_Level_3" )