{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Dependencies" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pip install pillow datasets pandas pypng uuid\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Preproccessing" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import uuid\n", "import shutil\n", "\n", "def rename_and_move_images(source_dir, target_dir):\n", " # Create the target directory if it doesn't exist\n", " os.makedirs(target_dir, exist_ok=True)\n", "\n", " # List of common image file extensions\n", " image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff')\n", "\n", " # Walk through the source directory and its subdirectories\n", " for root, dirs, files in os.walk(source_dir):\n", " for file in files:\n", " # Check if the file has an image extension\n", " if file.lower().endswith(image_extensions):\n", " # Generate a new filename with UUID\n", " new_filename = str(uuid.uuid4()) + os.path.splitext(file)[1]\n", " \n", " # Construct full file paths\n", " old_path = os.path.join(root, file)\n", " new_path = os.path.join(target_dir, new_filename)\n", " \n", " # Move and rename the file\n", " shutil.move(old_path, new_path)\n", " print(f\"Moved and renamed: {old_path} -> {new_path}\")\n", "\n", "# Usage\n", "source_directory = \"images\"\n", "target_directory = \"train\"\n", "\n", "rename_and_move_images(source_directory, target_directory)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Examine Metadata For Stable Diffusion PNGs\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from PIL import Image\n", "import os\n", "\n", "# Set the path to the train directory\n", "train_directory = \"train\"\n", "\n", "# Get any PNG image file from the train directory\n", "image_file = None\n", "for file_name in os.listdir(train_directory):\n", " if file_name.endswith('.png'):\n", " image_file = os.path.join(train_directory, file_name)\n", " break\n", "\n", "# Check if an image was found\n", "if image_file:\n", " # Open the image\n", " with Image.open(image_file) as img:\n", " print(f\"Filename: {image_file}\")\n", " \n", " # Extract and display image size (width, height)\n", " print(f\"Size: {img.size}\")\n", " \n", " # Extract and display image mode (RGB, RGBA, etc.)\n", " print(f\"Mode: {img.mode}\")\n", " \n", " # Extract and display image format\n", " print(f\"Format: {img.format}\")\n", " \n", " # Extract and display image info (metadata)\n", " print(\"Metadata:\")\n", " for key, value in img.info.items():\n", " print(f\" {key}: {value}\")\n", "else:\n", " print(\"No PNG image found in the train directory.\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Extract the Metadata" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import png\n", "import pandas as pd\n", "import re\n", "\n", "# Directory containing images\n", "image_dir = 'train'\n", "metadata_list = []\n", "\n", "# Mapping of possible keys to standardized field names\n", "field_mapping = {\n", " 'parameters': 'prompt',\n", " 'seed': 'seed',\n", " 'steps': 'steps',\n", " 'cfg scale': 'cfg',\n", " 'cfg_scale': 'cfg',\n", " 'cfg-scale': 'cfg',\n", " 'guidance': 'guidance',\n", " 'sampler': 'sampler_name',\n", " 'sampler_name': 'sampler_name',\n", " 'version': 'version',\n", " 'rng': 'rng',\n", " 'size': 'size'\n", "}\n", "\n", "def extract_metadata_from_png(image_path):\n", " \"\"\"\n", " Extracts metadata from all tEXt chunks in a PNG image.\n", " Args:\n", " image_path (str): Path to the PNG image.\n", " Returns:\n", " dict: A dictionary containing extracted metadata.\n", " \"\"\"\n", " metadata = {}\n", " try:\n", " with open(image_path, 'rb') as f:\n", " reader = png.Reader(file=f)\n", " for chunk_type, chunk_data in reader.chunks():\n", " if chunk_type == b'tEXt':\n", " # Decode the tEXt chunk\n", " chunk_text = chunk_data.decode('latin1')\n", " # Split into key and value using null byte as separator\n", " if '\\x00' in chunk_text:\n", " key, value = chunk_text.split('\\x00', 1)\n", " key = key.lower().strip()\n", " value = value.strip()\n", " # Map the key to standardized field name if it exists\n", " if key in field_mapping:\n", " standardized_key = field_mapping[key]\n", " metadata[standardized_key] = value\n", " except Exception as e:\n", " print(f\"Error reading PNG file {image_path}: {e}\")\n", " return metadata\n", "\n", "def parse_parameters(parameters):\n", " \"\"\"\n", " Parses the 'parameters' string to extract individual fields.\n", " \"\"\"\n", " # Extract prompt (everything before the first recognized field)\n", " prompt_end = min((parameters.find(field) for field in ['Steps:', 'CFG scale:', 'Guidance:', 'Seed:'] if field in parameters), default=-1)\n", " prompt = parameters[:prompt_end].strip() if prompt_end != -1 else parameters\n", "\n", " # Extract other fields\n", " fields = {\n", " 'steps': r'Steps: (\\d+)',\n", " 'cfg': r'CFG scale: ([\\d.]+)',\n", " 'guidance': r'Guidance: ([\\d.]+)',\n", " 'seed': r'Seed: (\\d+)',\n", " 'width': r'Size: (\\d+)x\\d+',\n", " 'height': r'Size: \\d+x(\\d+)',\n", " 'rng': r'RNG: (\\w+)',\n", " 'sampler_name': r'Sampler: (\\w+)',\n", " 'version': r'Version: (.+)$'\n", " }\n", "\n", " parsed = {'prompt': prompt}\n", " for key, pattern in fields.items():\n", " match = re.search(pattern, parameters)\n", " parsed[key] = match.group(1).strip() if match else 'N/A'\n", "\n", " return parsed\n", "\n", "# Loop through all PNG images in the directory\n", "for file_name in os.listdir(image_dir):\n", " if file_name.lower().endswith('.png'):\n", " image_path = os.path.join(image_dir, file_name)\n", " metadata = extract_metadata_from_png(image_path)\n", " \n", " # Parse the 'parameters' field\n", " if 'prompt' in metadata:\n", " parsed_metadata = parse_parameters(metadata['prompt'])\n", " else:\n", " parsed_metadata = {field: 'N/A' for field in field_mapping.values()}\n", " \n", " # Add file name to metadata\n", " parsed_metadata['file_name'] = file_name\n", " \n", " metadata_list.append(parsed_metadata)\n", "\n", "# Convert the metadata list to a DataFrame\n", "metadata_df = pd.DataFrame(metadata_list)\n", "\n", "# Define the desired column order\n", "desired_columns = ['file_name', 'seed', 'prompt', 'steps', 'cfg', 'sampler_name', 'guidance', 'version', 'width', 'height', 'rng']\n", "\n", "# Ensure all desired columns are present\n", "for col in desired_columns:\n", " if col not in metadata_df.columns:\n", " metadata_df[col] = 'N/A'\n", "\n", "# Reorder the DataFrame columns\n", "metadata_df = metadata_df[desired_columns]\n", "\n", "# Save the metadata to a CSV file\n", "metadata_csv_path = os.path.join(image_dir, 'metadata.csv')\n", "metadata_df.to_csv(metadata_csv_path, index=False)\n", "print(\"Metadata extraction complete. Metadata saved to:\", metadata_csv_path)\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.10" } }, "nbformat": 4, "nbformat_minor": 2 }