File size: 9,275 Bytes
09de860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
{
 "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
}