upscaler-gallery / scripts /generate-icat-comparison-projects.py
Silverbelt
add source file to the set, zoomed 400% + correct file type
63e8f49
raw
history blame contribute delete
No virus
8.39 kB
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
def get_jpeg_dimensions(file_path):
"""
Returns the (width, height) of a JPG image by reading the file's metadata.
"""
with open(file_path, 'rb') as f:
f.seek(0)
data = f.read(24)
# Check if file is JPEG
if data[0:2] == b'\xff\xd8': # JPEG files start with 0xFFD8
while True:
f.seek(2, 1) # Skip marker
marker = f.read(2)
if marker[0] == 0xFF and marker[1] == 0xC0: # Start of Frame marker
f.seek(3, 1) # Skip precision byte
height = int.from_bytes(f.read(2), 'big')
width = int.from_bytes(f.read(2), 'big')
return width, height
else:
size = int.from_bytes(f.read(2), 'big')
f.seek(size - 2, 1) # Skip to the next block
else:
raise ValueError("Not a JPEG file")
def get_image_dimensions(file_path):
extension = os.path.splitext(file_path)[-1].lower()
if extension == '.jpg' or extension == '.jpeg':
return get_jpeg_dimensions(file_path)
elif extension == '.png':
return get_png_dimensions(file_path)
else:
raise ValueError("Unsupported file format")
# 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_dirs = [os.path.join(script_dir, '..', 'source'), os.path.join(script_dir, '..', 'result')]
output_dir = os.path.join(script_dir, '..', 'output/icat_projects')
for dir in base_dirs:
if not os.path.exists(dir):
print(f"The path {dir} does not exist!")
sys.exit(1) # Exit the program with a non-zero status to indicate an error
print(f"Searching for images in {base_dirs}.")
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 dir in base_dirs:
for root, dirs, files in os.walk(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))
# Fill JSON structure with grouped files
for number, group in file_groups.items():
media_files = []
media_order = []
# 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": []
}
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_image_dimensions(file_path)
fileExt = file_name.split('.')[-1]
if "source" in file_path.lower():
zoomFactor = 400
else:
zoomFactor = 100
# Example media entry
media_entry = {
"id": hex_id,
"created": int(os.path.getctime(file_path) * 1000),
"codec": fileExt.upper(),
"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": fileExt,
"format": fileExt.upper(),
"x": 0,
"y": 0,
"z": zoomFactor,
"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}")