"""Self-contained visual controls for Gradio HTML: no network or model work.""" import html import json import math import re from relight_backend import PRESETS, DIRECTIONS AZIMUTHS = tuple(range(0, 360, 30)) ELEVATIONS = (0, 30, 60, 90) SWATCHES = ( ("White", "#FFFFFF"), ("Amber", "#FFBC73"), ("Blue", "#9EBBFF"), ("Pink", "#FF60C8"), ("Teal", "#57D9CA"), ("Red", "#FF6A5C"), ) def _object(value, allowed): if value is None: return {} if isinstance(value, str): if len(value) > 2048: raise ValueError("The visual control value is too large.") if not value.strip(): return {} try: value = json.loads(value) except (ValueError, TypeError) as error: raise ValueError("The visual control needs a valid JSON object.") from error if not isinstance(value, dict) or set(value) - allowed: raise ValueError("The visual control contains unsupported settings.") return dict(value) def read_relight_widget(value): data = _object(value, {"preset", "direction", "color"}) preset = data.get("preset", "Soft studio") if not isinstance(preset, str) or preset not in PRESETS: raise ValueError("Choose one of the illustrated lighting presets.") direction = data.get("direction", PRESETS[preset]["direction"]) if not isinstance(direction, str) or direction not in DIRECTIONS: raise ValueError("Choose one of the five light directions.") color = data.get("color", PRESETS[preset]["color"]) if not isinstance(color, str) or not re.fullmatch(r"#[0-9a-fA-F]{6}", color): raise ValueError("Choose a valid six-digit light colour.") return preset, direction, color.upper() def relight_widget_value(preset="Soft studio", direction="Left", color="#FFFFFF"): preset, direction, color = read_relight_widget(dict(preset=preset, direction=direction, color=color)) return json.dumps(dict(preset=preset, direction=direction, color=color), separators=(",", ":")) def _angle(value, allowed, label): if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value not in allowed: raise ValueError(f"Choose one of the illustrated {label} positions.") return int(value) def read_camera_widget(value): data = _object(value, {"azimuth", "elevation", "closeup"}) azimuth = _angle(data.get("azimuth", 90), AZIMUTHS, "camera") elevation = _angle(data.get("elevation", 0), ELEVATIONS, "height") closeup = data.get("closeup", False) if not isinstance(closeup, bool): raise ValueError("Close-up must be on or off.") return azimuth, elevation, closeup def camera_widget_value(azimuth=90, elevation=0, closeup=False): azimuth, elevation, closeup = read_camera_widget(dict(azimuth=azimuth, elevation=elevation, closeup=closeup)) return json.dumps(dict(azimuth=azimuth, elevation=elevation, closeup=closeup), separators=(",", ":")) _HEAD = '' def _preset_picture(name, color): """Original vector miniatures: the diagram is visible without remote assets.""" shape = _HEAD.replace('