from __future__ import annotations import colorsys import functools import hashlib import io import json import math import re from dataclasses import dataclass from pathlib import Path from typing import Any, Iterable import numpy as np from PIL import Image CUSTOM_EPOCH_MS = 1_704_067_200_000 # 2024-01-01T00:00:00Z BUILD_BASE_MS = 1_784_764_800_000 # 2026-07-23T00:00:00Z WORKER_IDS = { "record": 1, "raw": 2, "lut": 3, "family": 4, "raw_shard": 5, "normalized_shard": 6, "canonical_parquet": 7, "alias_parquet": 8, "raw_index_parquet": 9, "asset": 10, "report": 11, } DIRECTIVES = { "TITLE", "LUT_1D_SIZE", "LUT_3D_SIZE", "DOMAIN_MIN", "DOMAIN_MAX", "LUT_1D_INPUT_RANGE", "LUT_3D_INPUT_RANGE", } TECHNICAL_TERMS = { "rec709": ("rec709",), "rec.709": ("rec709",), "s-log3": ("s-log3",), "slog3": ("s-log3",), "s-log2": ("s-log2",), "slog2": ("s-log2",), "s-log": ("s-log",), "v-log": ("v-log",), "vlog": ("v-log",), "c-log": ("c-log",), "clog": ("c-log",), "log-c": ("log-c",), "logc": ("log-c",), "redlogfilm": ("redlogfilm",), "bmdfilm": ("bmdfilm",), "cineon": ("cineon",), "alexa": ("alexa",), "aces": ("aces",), "dci-p3": ("dci-p3",), "dcip3": ("dci-p3",), "s-gamut": ("s-gamut",), "sgamut": ("s-gamut",), } CAMERA_TERMS = { "sony": "sony", "canon": "canon", "panasonic": "panasonic", "blackmagic": "blackmagic", "bmd": "blackmagic", "arri": "arri", "alexa": "arri", "red camera": "red", "redlog": "red", "dji": "dji", "gopro": "gopro", "fuji": "fujifilm", "fujifilm": "fujifilm", "nikon": "nikon", } STYLE_TERMS = { "cinematic": "cinematic", "cinema": "cinematic", "movie": "cinematic", "film": "film", "vintage": "vintage", "retro": "retro", "wedding": "wedding", "portrait": "portrait", "travel": "travel", "landscape": "landscape", "drone": "drone", "hdr": "hdr", "teal": "teal", "orange": "orange", "warm": "warm", "cold": "cool", "cool": "cool", "noir": "noir", "monochrome": "monochrome", "black and white": "monochrome", "b&w": "monochrome", "cyberpunk": "cyberpunk", "kodak": "film-emulation", "fuji": "film-emulation", "food": "food", "nature": "nature", "city": "urban", "urban": "urban", "commercial": "commercial", "dramatic": "dramatic", "nostalgia": "nostalgic", "日系": "japanese-style", "婚礼": "wedding", "婚纱": "wedding", "人像": "portrait", "旅行": "travel", "风光": "landscape", "风景": "landscape", "电影": "cinematic", "胶片": "film", "复古": "vintage", "美食": "food", "冷色": "cool", "暖": "warm", "清新": "fresh", "儿童": "children", } @dataclass class ParsedLUT: lut_3d: np.ndarray | None lut_1d: np.ndarray | None lut_3d_size: int | None lut_1d_size: int | None inferred_3d_size: bool domain_min: np.ndarray domain_max: np.ndarray domain_declared: bool one_d_input_range: tuple[float, float] | None title_present: bool encoding: str replacement_characters: bool unknown_line_count: int data_row_count: int expected_data_row_count: int comments_text: str def snowflake_id(kind: str, ordinal: int) -> str: """Return a deterministic, classic 64-bit Snowflake ID as a decimal string.""" if kind not in WORKER_IDS: raise KeyError(f"Unknown Snowflake kind: {kind}") if ordinal < 0: raise ValueError("Snowflake ordinal must be non-negative") timestamp_ms = BUILD_BASE_MS + ordinal // 4096 sequence = ordinal % 4096 value = ( ((timestamp_ms - CUSTOM_EPOCH_MS) << 22) | (WORKER_IDS[kind] << 12) | sequence ) if value >= 2**63: raise OverflowError("Snowflake ID exceeded signed 64-bit range") return str(value) def decode_lut(raw: bytes) -> tuple[str, str, bool]: for encoding in ("utf-8-sig", "gb18030", "cp1252"): try: return raw.decode(encoding), encoding, False except UnicodeDecodeError: continue text = raw.decode("utf-8", "replace") return text, "utf-8-replace", "\ufffd" in text def _parse_vector(value: str, expected: int = 3) -> np.ndarray | None: try: array = np.fromstring(value.replace(",", " "), sep=" ", dtype=np.float64) except ValueError: return None if array.size < expected: return None return array[:expected].astype(np.float32) def _safe_fromstring(value: str, dtype: Any = np.float64) -> np.ndarray: try: return np.fromstring(value, sep=" ", dtype=dtype) except ValueError: return np.empty(0, dtype=dtype) def _integer_cube_root(value: int) -> int | None: if value <= 0: return None guess = round(value ** (1.0 / 3.0)) for candidate in range(max(1, guess - 2), guess + 3): if candidate**3 == value: return candidate return None def parse_cube(raw: bytes) -> ParsedLUT: text, encoding, replacements = decode_lut(raw) directives: dict[str, str] = {} comments: list[str] = [] unknown_lines = 0 lines = text.splitlines() data_start: int | None = None for line_index, raw_line in enumerate(lines): stripped = raw_line.strip().lstrip("\ufeff") if not stripped: continue if stripped.startswith("#"): comments.append(stripped[1:].strip()) continue content = stripped.split("#", 1)[0].strip() if not content: continue parts = content.split(None, 1) key = parts[0].upper() if key in DIRECTIVES: if key not in directives: directives[key] = parts[1].strip() if len(parts) > 1 else "" continue values = _safe_fromstring(content.replace(",", " "), dtype=np.float64) if values.size >= 3 and all(math.isfinite(float(item)) for item in values[:3]): data_start = line_index break else: unknown_lines += 1 lut_3d_size = None lut_1d_size = None if directives.get("LUT_3D_SIZE", "").strip().isdigit(): lut_3d_size = int(directives["LUT_3D_SIZE"].strip()) if directives.get("LUT_1D_SIZE", "").strip().isdigit(): lut_1d_size = int(directives["LUT_1D_SIZE"].strip()) declared_expected = (lut_1d_size or 0) + ((lut_3d_size or 0) ** 3) values = np.empty((0, 3), dtype=np.float32) if data_start is not None: if declared_expected: candidate_lines = lines[data_start : data_start + declared_expected] else: candidate_lines = lines[data_start:] numeric_block = "\n".join(candidate_lines).replace(",", " ") flat = _safe_fromstring(numeric_block, dtype=np.float32) if flat.size % 3 == 0: values = flat.reshape(-1, 3) target_rows = declared_expected or None if ( (target_rows is not None and len(values) != target_rows) or (target_rows is None and len(values) == 0) ): fallback_rows: list[tuple[float, float, float]] = [] for raw_line in lines[data_start:]: content = raw_line.split("#", 1)[0].strip() row = _safe_fromstring( content.replace(",", " "), dtype=np.float64 ) if row.size >= 3 and all( math.isfinite(float(item)) for item in row[:3] ): fallback_rows.append( (float(row[0]), float(row[1]), float(row[2])) ) if target_rows is not None and len(fallback_rows) == target_rows: break elif content and not content.startswith("#"): unknown_lines += 1 values = np.asarray(fallback_rows, dtype=np.float32) inferred_3d = False if lut_3d_size is None and lut_1d_size is None: inferred = _integer_cube_root(len(values)) if inferred is not None: lut_3d_size = inferred inferred_3d = True expected = (lut_1d_size or 0) + ((lut_3d_size or 0) ** 3) if expected != len(values): raise ValueError( f"Data row mismatch: parsed={len(values)}, expected={expected}, " f"lut_1d_size={lut_1d_size}, lut_3d_size={lut_3d_size}" ) offset = 0 lut_1d = None lut_3d = None if lut_1d_size: lut_1d = values[:lut_1d_size].copy() offset = lut_1d_size if lut_3d_size: lut_3d = values[offset:].reshape( lut_3d_size, lut_3d_size, lut_3d_size, 3 ) domain_min = _parse_vector(directives.get("DOMAIN_MIN", "")) domain_max = _parse_vector(directives.get("DOMAIN_MAX", "")) domain_declared = domain_min is not None and domain_max is not None if domain_min is None: domain_min = np.zeros(3, dtype=np.float32) if domain_max is None: domain_max = np.ones(3, dtype=np.float32) one_d_input_range = None range_values = _parse_vector( directives.get("LUT_1D_INPUT_RANGE", ""), expected=2 ) if range_values is not None: one_d_input_range = (float(range_values[0]), float(range_values[1])) return ParsedLUT( lut_3d=lut_3d, lut_1d=lut_1d, lut_3d_size=lut_3d_size, lut_1d_size=lut_1d_size, inferred_3d_size=inferred_3d, domain_min=domain_min, domain_max=domain_max, domain_declared=domain_declared, one_d_input_range=one_d_input_range, title_present="TITLE" in directives, encoding=encoding, replacement_characters=replacements or "\ufffd" in text, unknown_line_count=unknown_lines, data_row_count=len(values), expected_data_row_count=expected, comments_text="\n".join(comments[:64]), ) def interpolate_axis(array: np.ndarray, axis: int, size: int) -> np.ndarray: if array.shape[axis] == size: return array.astype(np.float32, copy=False) positions = np.linspace(0, array.shape[axis] - 1, size, dtype=np.float32) low = np.floor(positions).astype(np.int32) high = np.minimum(low + 1, array.shape[axis] - 1) weight_shape = [1] * array.ndim weight_shape[axis] = size weight = (positions - low).reshape(weight_shape) left = np.take(array, low, axis=axis) right = np.take(array, high, axis=axis) return left * (1.0 - weight) + right * weight def normalize_3d(lut: np.ndarray | None, size: int = 33) -> np.ndarray | None: if lut is None: return None result = lut.astype(np.float32, copy=False) for axis in range(3): result = interpolate_axis(result, axis, size) return result.astype(np.float16) def normalize_1d(lut: np.ndarray | None, size: int = 4096) -> np.ndarray | None: if lut is None: return None result = interpolate_axis(lut.astype(np.float32, copy=False), 0, size) return result.astype(np.float16) def semantic_sha256( lut_3d: np.ndarray | None, lut_1d: np.ndarray | None, domain_min: np.ndarray, domain_max: np.ndarray, one_d_input_range: tuple[float, float] | None, ) -> str: digest = hashlib.sha256() if lut_3d is None: digest.update(b"3d:none\0") else: digest.update(b"3d:33:f16\0") digest.update(np.ascontiguousarray(lut_3d).tobytes()) if lut_1d is None: digest.update(b"1d:none\0") else: digest.update(b"1d:4096:f16\0") digest.update(np.ascontiguousarray(lut_1d).tobytes()) digest.update(np.asarray(domain_min, dtype=" np.ndarray: unit = np.linspace(0.0, 1.0, size, dtype=np.float32) blue, green, red = np.meshgrid(unit, unit, unit, indexing="ij") rgb = np.stack([red, green, blue], axis=-1) return domain_min + rgb * (domain_max - domain_min) def calculate_metrics( lut_3d: np.ndarray | None, lut_1d: np.ndarray | None, domain_min: np.ndarray, domain_max: np.ndarray, ) -> dict[str, float | None]: arrays = [item.astype(np.float32) for item in (lut_3d, lut_1d) if item is not None] merged = np.concatenate([item.reshape(-1, 3) for item in arrays], axis=0) metrics: dict[str, float | None] = { "value_min": float(np.min(merged)), "value_max": float(np.max(merged)), "out_of_unit_fraction": float( np.mean((merged < 0.0) | (merged > 1.0)) ), "clipped_fraction": float( np.mean((merged <= 0.0) | (merged >= 1.0)) ), "identity_rmse": None, "mean_abs_change": None, "neutral_rmse": None, "luma_shift": None, "saturation_mean": None, "monotonicity_violation_fraction": None, } if lut_3d is not None: table = lut_3d.astype(np.float32) identity = identity_grid(table.shape[0], domain_min, domain_max) delta = table - identity diagonal = table[ np.arange(table.shape[0]), np.arange(table.shape[0]), np.arange(table.shape[0]), ] neutral = identity[ np.arange(identity.shape[0]), np.arange(identity.shape[0]), np.arange(identity.shape[0]), ] luma_weights = np.asarray([0.2126, 0.7152, 0.0722], dtype=np.float32) monotonic = np.concatenate( [ np.diff(table[..., 0], axis=2).reshape(-1), np.diff(table[..., 1], axis=1).reshape(-1), np.diff(table[..., 2], axis=0).reshape(-1), ] ) metrics.update( { "identity_rmse": float(np.sqrt(np.mean(delta**2))), "mean_abs_change": float(np.mean(np.abs(delta))), "neutral_rmse": float( np.sqrt(np.mean((diagonal - neutral) ** 2)) ), "luma_shift": float( np.mean(table @ luma_weights) - np.mean(identity @ luma_weights) ), "saturation_mean": float( np.mean(np.max(table, axis=-1) - np.min(table, axis=-1)) ), "monotonicity_violation_fraction": float( np.mean(monotonic < -1e-5) ), } ) return metrics def _stable_unique(values: Iterable[str]) -> list[str]: return sorted(set(values)) def classify_lut( original_name: str, comments_text: str, has_3d: bool, has_1d: bool, ) -> dict[str, Any]: searchable = f"{original_name}\n{comments_text}".casefold() technical_tags: list[str] = [] camera_tags: list[str] = [] style_tags: list[str] = [] for needle, tags in TECHNICAL_TERMS.items(): if needle in searchable: technical_tags.extend(tags) for needle, tag in CAMERA_TERMS.items(): if needle in searchable: camera_tags.append(tag) for needle, tag in STYLE_TERMS.items(): if needle in searchable: style_tags.append(tag) technical_signals = ( technical_tags or "source input" in searchable or "input shaper" in searchable or "output:" in searchable or "to-rec709" in searchable or "to rec709" in searchable ) if has_3d and has_1d: function_type = "hybrid_transform" elif technical_signals: function_type = "technical_or_hybrid" elif style_tags: function_type = "creative_look" else: function_type = "unknown" if has_3d and has_1d: lut_type = "1d+3d" elif has_3d: lut_type = "3d" elif has_1d: lut_type = "1d" else: lut_type = "invalid" return { "lut_type": lut_type, "function_type": function_type, "technical_tags": _stable_unique(technical_tags), "camera_tags": _stable_unique(camera_tags), "style_tags": _stable_unique(style_tags), } def family_key(original_name: str) -> str: stem = original_name while stem.casefold().endswith(".cube"): stem = stem[:-5] stem = stem.casefold() stem = re.sub(r"\s*\((?:copy|\d+)\)\s*$", "", stem) stem = re.sub(r"\s*\[\d+\]\s*", " ", stem) stem = re.sub(r"(?:[-_ #]|\s)+\d+\s*$", "", stem) stem = re.sub(r"\s*[-_ ]?copy\s*$", "", stem) stem = re.sub(r"\s+", " ", stem).strip(" -_") if not stem: return "__unnamed__" return stem @functools.lru_cache(maxsize=1) def build_reference_image(width: int = 256, height: int = 144) -> np.ndarray: image = np.zeros((height, width, 3), dtype=np.float32) hue_height = int(height * 0.62) neutral_height = int(height * 0.18) channel_height = height - hue_height - neutral_height for y in range(hue_height): saturation = y / max(1, hue_height - 1) value = 0.95 - 0.35 * (y / max(1, hue_height - 1)) for x in range(width): hue = x / max(1, width - 1) image[y, x] = colorsys.hsv_to_rgb(hue, saturation, value) ramp = np.linspace(0.0, 1.0, width, dtype=np.float32) neutral_start = hue_height image[neutral_start : neutral_start + neutral_height] = ramp[None, :, None] channel_start = neutral_start + neutral_height third = max(1, channel_height // 3) image[channel_start : channel_start + third, :, 0] = ramp image[channel_start + third : channel_start + 2 * third, :, 1] = ramp image[channel_start + 2 * third :, :, 2] = ramp return image def apply_1d(image: np.ndarray, lut: np.ndarray) -> np.ndarray: positions = np.clip(image, 0.0, 1.0) * (lut.shape[0] - 1) low = np.floor(positions).astype(np.int32) high = np.minimum(low + 1, lut.shape[0] - 1) weight = positions - low result = np.empty_like(image, dtype=np.float32) for channel in range(3): result[..., channel] = ( lut[low[..., channel], channel] * (1.0 - weight[..., channel]) + lut[high[..., channel], channel] * weight[..., channel] ) return result def apply_3d( image: np.ndarray, lut: np.ndarray, domain_min: np.ndarray, domain_max: np.ndarray, ) -> np.ndarray: scale = np.where(domain_max != domain_min, domain_max - domain_min, 1.0) unit = np.clip((image - domain_min) / scale, 0.0, 1.0) coordinates = unit * (lut.shape[0] - 1) low = np.floor(coordinates).astype(np.int32) high = np.minimum(low + 1, lut.shape[0] - 1) weight = coordinates - low r0, g0, b0 = low[..., 0], low[..., 1], low[..., 2] r1, g1, b1 = high[..., 0], high[..., 1], high[..., 2] wr, wg, wb = weight[..., 0:1], weight[..., 1:2], weight[..., 2:3] c000 = lut[b0, g0, r0] c100 = lut[b0, g0, r1] c010 = lut[b0, g1, r0] c110 = lut[b0, g1, r1] c001 = lut[b1, g0, r0] c101 = lut[b1, g0, r1] c011 = lut[b1, g1, r0] c111 = lut[b1, g1, r1] c00 = c000 * (1.0 - wr) + c100 * wr c10 = c010 * (1.0 - wr) + c110 * wr c01 = c001 * (1.0 - wr) + c101 * wr c11 = c011 * (1.0 - wr) + c111 * wr c0 = c00 * (1.0 - wg) + c10 * wg c1 = c01 * (1.0 - wg) + c11 * wg return c0 * (1.0 - wb) + c1 * wb def render_preview( lut_3d: np.ndarray | None, lut_1d: np.ndarray | None, domain_min: np.ndarray, domain_max: np.ndarray, quality: int = 84, ) -> bytes: source = build_reference_image() transformed = source if lut_1d is not None: transformed = apply_1d(transformed, lut_1d.astype(np.float32)) if lut_3d is not None: transformed = apply_3d( transformed, lut_3d.astype(np.float32), domain_min.astype(np.float32), domain_max.astype(np.float32), ) source_u8 = np.round(np.clip(source, 0.0, 1.0) * 255).astype(np.uint8) transformed_u8 = np.round(np.clip(transformed, 0.0, 1.0) * 255).astype( np.uint8 ) separator = np.full((source.shape[0], 4, 3), 235, dtype=np.uint8) joined = np.concatenate([source_u8, separator, transformed_u8], axis=1) buffer = io.BytesIO() Image.fromarray(joined, mode="RGB").save( buffer, format="WEBP", quality=quality, method=4 ) return buffer.getvalue() def normalized_npz_bytes( lut_id: str, lut_3d: np.ndarray | None, lut_1d: np.ndarray | None, domain_min: np.ndarray, domain_max: np.ndarray, one_d_input_range: tuple[float, float] | None, ) -> bytes: payload: dict[str, np.ndarray] = { "lut_id": np.asarray(lut_id), "domain_min": np.asarray(domain_min, dtype=np.float32), "domain_max": np.asarray(domain_max, dtype=np.float32), } if lut_3d is not None: payload["lut_3d"] = np.asarray(lut_3d, dtype=np.float16) if lut_1d is not None: payload["lut_1d"] = np.asarray(lut_1d, dtype=np.float16) if one_d_input_range is not None: payload["lut_1d_input_range"] = np.asarray( one_d_input_range, dtype=np.float32 ) buffer = io.BytesIO() np.savez_compressed(buffer, **payload) return buffer.getvalue() def safe_json_dumps(value: Any) -> str: return json.dumps( value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False, ) def atomic_write(path: Path, data: bytes) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".partial") temporary.write_bytes(data) temporary.replace(path)