upscaler-gallery / scripts /generate-icat-comparison-projects.py
Silverbelt
script to generate icat projects to compare the images
b3e34bd
raw
history blame
6.73 kB
from PIL import Image
import os
import re
import sys
import json
import uuid
import struct
from collections import defaultdict
def get_png_dimensions(file_path):
"""
Returns the (width, height) of a PNG image by reading the file's metadata.
"""
with open(file_path, 'rb') as f:
# PNG files start with an 8-byte signature
signature = f.read(8)
# Check if the file is a valid PNG by checking the signature
if signature != b'\x89PNG\r\n\x1a\n':
raise ValueError("Not a valid PNG file")
# The IHDR chunk starts after the 8-byte signature and 4-byte length field
f.read(4) # Skip the length of the IHDR chunk
# Ensure we're reading the IHDR chunk
ihdr_chunk = f.read(4)
if ihdr_chunk != b'IHDR':
raise ValueError("Invalid PNG IHDR chunk")
# Read width and height from the IHDR chunk (8 bytes total)
width, height = struct.unpack('>II', f.read(8))
return width, height
# Get the directory of the current script
script_dir = os.path.dirname(os.path.abspath(__file__))
# Construct the full path to the target directory
base_dir = os.path.join(script_dir, '..', 'result', 'flux-dev')
output_dir = os.path.join(script_dir, '..', 'output/icat_projects')
if not os.path.exists(base_dir):
print(f"The path {base_dir} does not exist!")
sys.exit(1) # Exit the program with a non-zero status to indicate an error
else:
print(f"Searching for images in {base_dir}.")
os.makedirs(output_dir, exist_ok=True)
# Regular expression to match the five-digit number in the file names
pattern = re.compile(r'\d{5}')
# Dictionary to store file groups
file_groups = defaultdict(list)
# Walk through all subdirectories and files
for root, dirs, files in os.walk(base_dir):
for file in files:
# Search for the five-digit number in the file name
match = pattern.search(file)
if match:
# Get the five-digit number
number = match.group()
# Add the file (with its full path) to the corresponding group
file_groups[number].append(os.path.join(root, file))
# JSON structure template
json_structure = {
"uiVisibility": {
"antiAliasSelect": True,
"fullscreenButton": True,
"gridSelect": True,
"helpButton": True,
"layersButton": True,
"layoutTabs": True,
"loopButton": True,
"mediaInfo": True,
"pixelDataButton": False,
"progressBar": True,
"setSelect": False,
"speedSelect": True,
"startEndTime": True,
"timeDisplay": True,
"titleBar": True,
"videoControls": True,
"zoomSelect": True,
"contentSidebar": True,
"timeline": True,
"controlBar": True,
"addFilterBtn": True,
"addLogoBtn": True,
"inOutSlider": True,
"timelineInOutSlider": False,
"appSettingsBtn": True
},
"sets": []
}
# Fill JSON structure with grouped files
for number, group in file_groups.items():
media_files = []
media_order = []
for file_path in group:
file_name = os.path.basename(file_path)
base_name = file_name.rsplit('.', 1)[0]
hex_id = uuid.uuid4().hex # Generate a unique hex ID for each file
cleaned_path = os.path.abspath(file_path).replace('\\', '%5C').replace(':', '%3A')
width, height = get_png_dimensions(file_path)
# Example media entry
media_entry = {
"id": hex_id,
"created": int(os.path.getctime(file_path) * 1000),
"codec": "PNG",
"bitrate": 0,
"width": width,
"height": height,
"type": "image",
"fps": 0,
"duration": 0,
"size": os.path.getsize(file_path),
"modified": int(os.path.getmtime(file_path) * 1000),
"hasAudio": False,
"timestamps": [],
"path": os.path.abspath(file_path).replace("/", "\\"),
"name": file_name,
"base": base_name,
"originalBase": base_name,
"extension": file_name.split('.')[-1],
"format": "PNG",
"x": 0,
"y": 0,
"z": 100,
"startTime": 0,
"thumbnails": [],
"labelVisibility": {
"codec": False,
"bitrate": False,
"dimensions": False,
"format": False,
"fps": False,
"duration": False,
"startTime": False
},
"muted": True,
"visible": True,
"shaderId": "",
"shaderInputs": [],
"shaderSettings": {},
"shaderSource": "",
"showShader": True,
"src": f"icat://localhost/?src={cleaned_path}",
"mediaOverlay": "",
"frameImages": [],
"showFrameImages": True,
"infoTexts": [],
"showInfoText": False
}
media_files.append(media_entry)
media_order.append(hex_id)
# Add the set entry to JSON structure
set_id = str(uuid.uuid4().hex)
json_structure["activeSet"] = set_id
json_structure["sets"].append({
"id": set_id,
"created": 1724539610545,
"label": f"Einstellen {len(json_structure['sets']) + 1}",
"antiAlias": False,
"endTime": 1e+29,
"grid": 0,
"layout": "split",
"overlayOrder": [],
"looping": True,
"boomerang": False,
"mediaOrder": media_order,
"x": 2170.7728827197748,
"y": 0,
"z": 30.340576171875,
"speed": 1,
"splitposition": 0.5,
"startTime": 0,
"time": 0,
"viewport": {
"top": 93.17708587646484,
"left": 0,
"paneWidth": 2560,
"paneHeight": 932.0625,
"height": 932.0625,
"width": 2560,
"minZoom": 30.340576171875,
"fitScale": 0.30340576171875,
"fitWidth": 4096,
"fitHeight": 3072,
"fitPaneWidth": 4096,
"fitPaneHeight": 3072,
"contentWidth": 4096,
"contentHeight": 3072
},
"gamma": 1,
"exposure": 1,
"media": media_files,
"overlays": []
})
json_filename = os.path.join(output_dir, f"image_comparison_{number}.json")
with open(json_filename, 'w') as json_file:
json.dump(json_structure, json_file, indent=4)
print(f"JSON-Datei für Gruppe {number} wurde geschrieben: {json_filename}")