VIOLIN / scripts /generate_image_Variation_5.py
Perkzi's picture
Switch to Parquet format and ignore raw data folder
5e1ef3a
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>": color_format,
"<color_1>": normalize_hex(row.get("color_1", "")),
"<color_2>": normalize_hex(row.get("color_2", "")),
"<color_3>": normalize_hex(row.get("color_3", "")),
"<color_4>": normalize_hex(row.get("color_4", "")),
}
out = prompt
for k, v in mapping.items():
if k in out and v:
out = out.replace(k, v)
return out
def generate_images_and_prompts_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()
hex_color = normalize_hex(row.get("color_1", ""))
prompt_raw = row.get("prompt", "").strip()
split = (row.get("split") or "train").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)
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 image
img = Image.new("RGB", size, hex_color)
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})")
generate_images_and_prompts_with_split(
"metadata/Variation_5_Color_1.csv",
base_dir="data/Variation_5/Color_Level_1"
)
generate_images_and_prompts_with_split(
"metadata/Variation_5_Color_2.csv",
base_dir="data/Variation_5/Color_Level_2"
)
generate_images_and_prompts_with_split(
"metadata/Variation_5_Color_3.csv",
base_dir="data/Variation_5/Color_Level_3"
)