import gradio as gr import random import matplotlib.pyplot as plt import colorsys # Generate a random hex color def random_hex(): return "#" + "".join(f"{random.randint(0, 255):02x}" for _ in range(3)) # Convert hex to HSL def hex_to_hsl(hex_color): r, g, b = int(hex_color[1:3], 16) / 255.0, int(hex_color[3:5], 16) / 255.0, int(hex_color[5:7], 16) / 255.0 return colorsys.rgb_to_hls(r, g, b) # Convert HSL to hex def hsl_to_hex(h, l, s): r, g, b = colorsys.hls_to_rgb(h, l, s) return "#" + "".join(f"{int(c * 255):02x}" for c in (r, g, b)) # Generate a harmonious palette def generate_palette(locked_colors): locked_hsl = [hex_to_hsl(color) if color else None for color in locked_colors] base_hue = next((h for h, _, _ in locked_hsl if h is not None), random.random()) base_lum = next((l for _, l, _ in locked_hsl if l is not None), 0.5) base_sat = next((s for _, _, s in locked_hsl if s is not None), 0.7) new_palette = [] for i in range(5): if locked_colors[i]: new_palette.append(locked_colors[i]) else: new_hue = (base_hue + random.uniform(-0.1, 0.1)) % 1.0 new_lum = min(max(base_lum + random.uniform(-0.1, 0.1), 0.2), 0.8) new_sat = min(max(base_sat + random.uniform(-0.1, 0.1), 0.4), 1.0) new_palette.append(hsl_to_hex(new_hue, new_lum, new_sat)) return new_palette # Create color swatches def display_palette(colors): fig, ax = plt.subplots(figsize=(8, 2)) rgb_colors = [[int(h[i:i+2], 16) for i in (1, 3, 5)] for h in colors] ax.imshow([rgb_colors], aspect="auto") ax.set_xticks([]) ax.set_yticks([]) return fig, colors # Initialize locked colors initial_palette = generate_palette([None] * 5) # Gradio UI def update_palette(*locks): locks = [color if color and color.startswith("#") else None for color in locks] new_palette = generate_palette(locks) return display_palette(new_palette) + tuple(new_palette) with gr.Blocks(theme=gr.themes.Soft()) as iface: gr.Markdown("# 🎨 AI-Powered Color Palette Generator") gr.Markdown("Click on a color to lock it. Generate fresh palettes for unlocked colors!") with gr.Row(): lock_inputs = [gr.ColorPicker(label=f"Color {i+1}", value=initial_palette[i]) for i in range(5)] palette_output = gr.Plot(label="Generated Palette") generate_button = gr.Button("Regenerate Palette 🎨") generate_button.click(update_palette, inputs=lock_inputs, outputs=[palette_output] + lock_inputs) initial_fig, _ = display_palette(initial_palette) palette_output.value = initial_fig # Launch the app if __name__ == "__main__": iface.launch()