Spaces:
Running on Zero
Running on Zero
Download app.py from jejunepixels/automatic-drawing: direct link, hf CLI and curl.
- Browser
- Download file 21.4 kB
-
https://huggingface.co/spaces/jejunepixels/automatic-drawing/resolve/main/app.py
- Command line
-
hf download hf://spaces/jejunepixels/automatic-drawing/app.py
-
curl -L -o app.py https://huggingface.co/spaces/jejunepixels/automatic-drawing/resolve/main/app.py
21.4 kB
| """Prompt-free diffusion canvas for a private Hugging Face Space.""" | |
| import spaces | |
| import os | |
| import secrets | |
| import tempfile | |
| import time | |
| import threading | |
| from pathlib import Path | |
| from PIL import ImageChops, ImageStat | |
| import gradio as gr | |
| from gpu_note import gpu_note | |
| from brand_theme import brand_theme | |
| import torch | |
| from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline | |
| from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline | |
| from diffusers.utils.torch_utils import randn_tensor | |
| class CaptureStart: | |
| """Observe the exact prepared latents without drawing extra random numbers.""" | |
| def prepare_latents(self, *args, **kwargs): | |
| latents = super().prepare_latents(*args, **kwargs) | |
| observer = getattr(self, "latent_observer", None) | |
| if observer is not None: | |
| observer(latents) | |
| return latents | |
| class DrawingPipeline(CaptureStart, StableDiffusionPipeline): | |
| pass | |
| class DrawingFeedbackPipeline(CaptureStart, StableDiffusionImg2ImgPipeline): | |
| pass | |
| class DrawingXLPipeline(CaptureStart, StableDiffusionXLPipeline): | |
| pass | |
| class DrawingXLFeedbackPipeline(CaptureStart, StableDiffusionXLImg2ImgPipeline): | |
| pass | |
| MODELS = { | |
| "stabilityai/sd-turbo": (DrawingPipeline, DrawingFeedbackPipeline), | |
| "stabilityai/sdxl-turbo": (DrawingXLPipeline, DrawingXLFeedbackPipeline), | |
| } | |
| PIPELINES = {} | |
| for repo, (text_cls, image_cls) in MODELS.items(): | |
| print(f"Preloading {repo}", flush=True) | |
| text_pipe = text_cls.from_pretrained( | |
| repo, torch_dtype=torch.float16, variant="fp16", use_safetensors=True) | |
| text_pipe.to("cuda" if os.environ.get("SPACES_ZERO_GPU") or torch.cuda.is_available() else "cpu") | |
| PIPELINES[repo] = (text_pipe, image_cls(**text_pipe.components)) | |
| def decode_preview(pipeline, latents): | |
| with torch.inference_mode(): | |
| original_dtype = pipeline.vae.dtype | |
| upcast = original_dtype == torch.float16 and getattr(pipeline.vae.config, "force_upcast", False) | |
| if upcast: | |
| pipeline.vae.to(dtype=torch.float32) | |
| try: | |
| pixels = pipeline.vae.decode( | |
| latents.detach().to(pipeline.vae.dtype) / pipeline.vae.config.scaling_factor, | |
| return_dict=False)[0] | |
| finally: | |
| if upcast: | |
| pipeline.vae.to(dtype=original_dtype) | |
| return pipeline.image_processor.postprocess(pixels, output_type="pil")[0] | |
| def prepare_noise(model, seed): | |
| pipeline = PIPELINES[model][0] | |
| device = pipeline._execution_device | |
| pipeline.scheduler.set_timesteps(4, device=device) | |
| generator = torch.Generator("cpu").manual_seed(seed) | |
| raw = randn_tensor((1, pipeline.unet.config.in_channels, 64, 64), | |
| generator=generator, device=device, dtype=pipeline.unet.dtype) | |
| preview = decode_preview(pipeline, raw * pipeline.scheduler.init_noise_sigma) | |
| return dict(seed=seed, start_latents=raw.cpu(), initial_rng_state=generator.get_state()), preview | |
| def evolve(state, drift, model): | |
| if model not in PIPELINES: | |
| raise gr.Error("Choose a supported model.") | |
| pipe, feedback = PIPELINES[model] | |
| state = dict(state or {}) | |
| seed = state.get("seed", secrets.randbelow(2**31)) | |
| image = state.get("image") | |
| frame = state.get("frame", -1) | |
| history = list(state.get("history", [])) | |
| for _ in range(1): | |
| frame += 1 | |
| started = time.perf_counter() | |
| kwargs = dict(prompt="", guidance_scale=0.0, num_inference_steps=4, | |
| generator=torch.Generator("cpu").manual_seed(seed + frame)) | |
| if image is None and "start_latents" in state: | |
| kwargs["latents"] = state["start_latents"].to(pipe._execution_device) | |
| kwargs["generator"].set_state(state["initial_rng_state"]) | |
| effective_drift = float(drift) | |
| active = pipe if image is None else feedback | |
| stages = [] if image is None else [(image.copy(), "Before noise")] | |
| def capture_start(latents): | |
| label = "Starting noise (decoded latent)" if image is None else "After noise added (decoded latent)" | |
| stages.append((decode_preview(active, latents), label)) | |
| def capture_step(pipeline, step, timestep, callback_kwargs): | |
| stages.append((decode_preview(pipeline, callback_kwargs["latents"]), | |
| f"Denoising step {step + 1} · t={int(timestep)}")) | |
| return callback_kwargs | |
| active.latent_observer = capture_start | |
| try: | |
| with torch.inference_mode(): | |
| kwargs.update(callback_on_step_end=capture_step, | |
| callback_on_step_end_tensor_inputs=["latents"]) | |
| if image is None: | |
| result = pipe(height=512, width=512, **kwargs) | |
| else: | |
| result = feedback(image=image, strength=effective_drift, **kwargs) | |
| finally: | |
| active.latent_observer = None | |
| image = result.images[0] | |
| history = (history + [(image.copy(), f"Frame {frame}")])[-32:] | |
| state = dict(seed=seed, image=image, frame=frame, history=history) | |
| stages.append((image.copy(), "Completed image")) | |
| elapsed = time.perf_counter()-started | |
| return state, stages, f"{model.split('/')[-1]} | Frame {frame} | seed {seed} | drift {effective_drift:g} | {elapsed:.2f}s | empty prompt" | |
| class Session: | |
| def __init__(self): | |
| self.data = {} | |
| self.running = False | |
| self.revision = 0 | |
| self.wake = threading.Event() | |
| self.lock = threading.Lock() | |
| self.model = "stabilityai/sd-turbo" | |
| self.stages = [] | |
| self.cursor = -1 | |
| def __deepcopy__(self, memo): | |
| return Session() | |
| def start_session(session): | |
| session.running = True | |
| session.wake.clear() | |
| return gr.Timer(active=True), "Evolving continuously..." | |
| def pause_session(session): | |
| session.running = False | |
| session.revision += 1 | |
| session.wake.set() | |
| return gr.Timer(active=False), "Paused. Start continues from the latest completed image." | |
| def playback_button(session): | |
| return gr.update(value="Pause" if session.running else "Start") | |
| def toggle_playback(session): | |
| timer, message = pause_session(session) if session.running else start_session(session) | |
| return timer, message, playback_button(session) | |
| def same_picture(first, second): | |
| if first is second: | |
| return True | |
| if not hasattr(first, "resize") or not hasattr(second, "resize"): | |
| return first == second | |
| # Ignore sub-visible decoder rounding differences as well as exact repeats. | |
| difference = ImageChops.difference(first.convert("RGB").resize((128, 128)), | |
| second.convert("RGB").resize((128, 128))) | |
| return sum(ImageStat.Stat(difference).mean) / 3 < .5 | |
| def reset(session): | |
| pause_session(session) | |
| session.data = {} | |
| session.stages = [] | |
| session.cursor = -1 | |
| return None, [], "Ready. Start a new drawing from random noise.", gr.Timer(active=False) | |
| def select_model(session, model): | |
| if model not in MODELS: | |
| raise gr.Error("Choose a supported model.") | |
| result = reset(session) | |
| session.model = model | |
| return result | |
| def enter_canvas(session, model): | |
| select_model(session, model) | |
| noise, _ = initialize_noise(session) | |
| timer, message = start_session(session) | |
| return gr.update(visible=False), gr.update(visible=True), noise, [], "Starting noise. " + message, timer, None, None | |
| def initialize_noise(session): | |
| revision = session.revision | |
| data, noise = prepare_noise(session.model, secrets.randbelow(2**31)) | |
| if revision != session.revision: | |
| raise gr.Error("Noise preparation was interrupted. Please try again.") | |
| session.data = data | |
| session.stages = [(noise, "Starting noise")] | |
| session.cursor = 0 | |
| return noise, "Starting noise. Press Start to watch it become an image." | |
| def new_start_image(session): | |
| reset(session) | |
| noise, _ = initialize_noise(session) | |
| timer, _ = start_session(session) | |
| return noise, [], "New starting noise. Evolving continuously...", timer, None, None | |
| def change_noise(session): | |
| reset(session) | |
| noise, message = initialize_noise(session) | |
| return noise, [], message, gr.Timer(active=False), None, None | |
| def inspect_stage(session, direction): | |
| pause_session(session) | |
| if not session.stages: | |
| return gr.skip(), "No changed stages recorded yet.", gr.Timer(active=False) | |
| current = session.stages[session.cursor][0] | |
| candidate = session.cursor + direction | |
| while 0 <= candidate < len(session.stages): | |
| if not same_picture(current, session.stages[candidate][0]): | |
| session.cursor = candidate | |
| break | |
| candidate += direction | |
| image, label = session.stages[session.cursor] | |
| return image, f"Paused | Stage {session.cursor+1}/{len(session.stages)} | {label}", gr.Timer(active=False) | |
| def step_back(session): | |
| return inspect_stage(session, -1) | |
| def step_forward(session): | |
| return inspect_stage(session, 1) | |
| def back_to_start(session): | |
| pause_session(session) | |
| return gr.update(visible=True), gr.update(visible=False), gr.Timer(active=False) | |
| def animate(session, drift, pace): | |
| if not session.running or not session.lock.acquire(blocking=False): | |
| return | |
| revision = session.revision | |
| try: | |
| data, stages, message = evolve(session.data, drift, session.model) | |
| if revision != session.revision or not session.running: | |
| return | |
| session.data = data | |
| # Keep bounded actual snapshots; browsing never reruns inference or changes RNG. | |
| changed = [] | |
| last = session.stages[-1][0] if session.stages else None | |
| for preview, label in stages: | |
| if last is not None and same_picture(last, preview): | |
| continue | |
| changed.append((preview, label)) | |
| last = preview | |
| labeled = [(image, f"Cycle {data['frame']+1} | {label}") for image, label in changed] | |
| session.stages = (session.stages + labeled)[-64:] | |
| offset = len(session.stages) - len(changed) | |
| for index, (preview, label) in enumerate(changed): | |
| if revision != session.revision or not session.running: | |
| return | |
| session.cursor = offset + index | |
| yield preview, gr.skip(), f"{message} | {label}" | |
| if session.wake.wait(float(pace)): | |
| return | |
| yield data["image"], data["history"], message | |
| except Exception: | |
| session.running = False | |
| raise | |
| finally: | |
| session.lock.release() | |
| def export(session): | |
| state = session.data | |
| if not state or not state.get("history"): | |
| raise gr.Error("Generate a drawing first.") | |
| folder = Path(tempfile.mkdtemp(prefix="drawing-")) | |
| png = folder / "drawing.png" | |
| gif = folder / "evolution.gif" | |
| state["image"].save(png) | |
| frames = [item[0] for item in state["history"]] | |
| frames[0].save(gif, save_all=True, append_images=frames[1:], duration=650, loop=0) | |
| return str(png), str(gif) | |
| # Shared look (brand.css, from shared-ui/) first, then this app's layout. | |
| CSS = Path(__file__).with_name("brand.css").read_text(encoding="utf-8") + """ | |
| .gradio-container {max-width:none !important;min-height:100dvh !important;--color-accent:#f4bf67;--color-accent-soft:#f4bf6726} | |
| #experience {position:fixed !important;inset:0 !important;width:100% !important;max-width:100% !important;height:100dvh !important;margin:0 !important;padding:0 !important;gap:0 !important;overflow:hidden !important;background:var(--brand-stage);z-index:50;--brand-return-label:"Change model"} | |
| #canvas {position:absolute !important;inset:0 !important;width:100% !important;height:100% !important;min-height:0 !important;border:0 !important;border-radius:0 !important;background:var(--brand-stage) !important;padding:64px 16px 165px !important;box-sizing:border-box} | |
| #canvas > div {height:100% !important;min-height:0 !important;background:transparent !important} | |
| #canvas img {width:100% !important;height:100% !important;object-fit:contain !important;border-radius:0 !important} | |
| #drawing-caption {position:absolute !important;top:18px;left:clamp(16px,4vw,60px);right:72px;z-index:2;background:transparent;border:0;padding:0} | |
| #drawing-caption .prose p {white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin:0} | |
| #about-drawing {position:absolute !important;top:48px;left:clamp(16px,4vw,60px);width:min(440px,calc(100vw - 32px)) !important;max-height:55dvh;overflow:auto;z-index:3;background:#091622ed !important;border:1px solid #78949d45 !important;border-radius:14px;backdrop-filter:blur(14px);color:#d5e3e6;--block-title-text-color:#d5e3e6;--accordion-text-color:#d5e3e6;--body-text-color:#d5e3e6;--block-background-fill:transparent;--background-fill-primary:transparent} | |
| #about-drawing .label-wrap, #about-drawing .label-wrap span {color:#d5e3e6 !important} | |
| #about-drawing .prose {color:#d5e3e6 !important;font-size:13px;line-height:1.65} | |
| #about-drawing h3 {color:var(--brand-amber) !important;font-family:var(--brand-serif);font-weight:400} | |
| #control-dock {position:absolute !important;bottom:max(16px,env(safe-area-inset-bottom));left:50%;transform:translateX(-50%);width:min(940px,calc(100vw - 120px)) !important;max-width:calc(100% - 24px) !important;max-height:65dvh;overflow-x:hidden !important;overflow-y:auto;z-index:5;padding:12px !important;gap:8px !important} | |
| #control-dock *,#control-dock *::before,#control-dock *::after {box-sizing:border-box;min-width:0 !important} | |
| #control-dock > div,#options,#options > div {max-width:100% !important;min-width:0 !important} | |
| #control-dock .row {flex-wrap:wrap !important;min-width:0 !important} | |
| #control-dock .prose {overflow-wrap:anywhere} | |
| #control-dock button {min-height:44px} | |
| #transport {display:grid !important;grid-template-columns:minmax(0,1.3fr) repeat(2,minmax(0,1fr));width:100% !important;gap:8px !important;position:sticky;top:0;z-index:6;background:var(--brand-mint-solid)} | |
| #transport button {width:100% !important;white-space:normal} | |
| #resume-drawing {font-weight:600} | |
| #options {background:transparent !important;border:0 !important} | |
| @media(max-width:640px){ | |
| #canvas {padding:70px 8px 150px !important} | |
| #drawing-caption {left:12px;top:12px;right:12px} | |
| #drawing-caption .prose p {font-size:11px !important} | |
| #about-drawing {left:12px;top:44px;width:calc(100vw - 24px) !important;max-height:45dvh} | |
| #control-dock {bottom:12px;left:12px;transform:none;width:calc(100vw - 72px) !important;padding:8px !important;max-height:60dvh} | |
| #transport {gap:5px !important} | |
| #transport button {font-size:12px;padding:8px 5px} | |
| } | |
| """ | |
| # Start page follows the browser's light/dark setting; the workspace sets its own colours. | |
| THEME = brand_theme() | |
| with gr.Blocks(title="Automatic Drawing") as demo: | |
| state = gr.State(Session()) | |
| timer = gr.Timer(.5, active=False) | |
| with gr.Column(visible=True, elem_id="welcome", elem_classes=["brand-start"]) as welcome: | |
| gr.HTML('<header class="brand-header"><div class="eyebrow">AN EXPERIMENT IN AUTOMATIC DRAWING</div><h1 class="brand-title">Automatic Drawing<span class="title-stop">.</span></h1><p class="brand-intro">Inspired by automatic drawing, this experiment lets an image unfold without a written prompt. Begin with noise, watch forms emerge, then see the image become the starting point for something new.</p></header>', padding=False) | |
| gpu_note(demo, "Each drawing cycle", "Automatic Drawing", "jejunepixels/automatic-drawing") | |
| model = gr.Dropdown(choices=[("SD-Turbo · faster", "stabilityai/sd-turbo"), | |
| ("SDXL-Turbo · larger model", "stabilityai/sdxl-turbo")], | |
| value="stabilityai/sd-turbo", label="Model") | |
| begin = gr.Button("Start drawing", variant="primary", size="lg", elem_id="begin-drawing", | |
| elem_classes=["brand-primary"]) | |
| with gr.Column(visible=False, elem_id="experience") as experience: | |
| canvas = gr.Image(label="Living canvas", show_label=False, interactive=False, | |
| height=640, elem_id="canvas", type="pil") | |
| status = gr.Markdown("**Automatic Drawing.** No written prompt. Just the next image.", elem_id="drawing-caption", | |
| elem_classes=["brand-caption"]) | |
| with gr.Accordion("About this drawing", open=False, elem_id="about-drawing"): | |
| gr.Markdown('### What is happening?\nThe first image begins as random noise. The model removes noise in a few steps, drawing on patterns learned during training. Each later cycle takes the previous image, adds fresh noise, and removes it again to produce a variation. Every text prompt is empty.\n\nThe canvas shows decoded views of the actual internal image states: before noise, after noise is added, and after each denoising step. Stages play after a cycle has been computed. Brief holds between cycles come from processing and the shared GPU queue. Generation continues until you pause or reach your GPU quota.', elem_id="explanation") | |
| with gr.Column(elem_id="control-dock", elem_classes=["brand-dock"]): | |
| with gr.Row(elem_id="transport"): | |
| playback = gr.Button("Start", variant="primary", elem_id="resume-drawing") | |
| previous = gr.Button("Step back") | |
| following = gr.Button("Step forward") | |
| with gr.Accordion("Settings", open=False, elem_id="options"): | |
| with gr.Row(): | |
| fresh = gr.Button("New start image") | |
| noise_button = gr.Button("Change noise") | |
| with gr.Row(): | |
| drift = gr.Slider(.25, 1, value=.75, step=.25, label="Drift", | |
| info="Lower values preserve more of the previous image; higher values allow bigger changes. Applies next cycle.") | |
| pace = gr.Slider(.15, 1.5, value=.5, step=.05, label="Seconds per stage", | |
| info="How long each stage stays on screen. This changes playback speed.") | |
| gr.Markdown('**Change noise** picks a new random starting noise and pauses so you can inspect it; press Start to generate from it. **New start image** starts from new noise and runs automatically. **Step back / Step forward** pause playback and browse the last 64 visually distinct noise and denoising stages. Browsing does not change generation; Start continues from the latest completed image. The round **↺** button at the bottom right pauses generation and returns to the start page, where you can change model or sign in.') | |
| gallery = gr.Gallery(label="Last 32 completed images", columns=8, height=220) | |
| download = gr.Button("Prepare downloads") | |
| with gr.Row(): | |
| png = gr.File(label="Current image") | |
| gif = gr.File(label="Evolution animation") | |
| # Outside the dock: its transform would otherwise trap position:fixed. | |
| back = gr.Button("Change model", elem_id="return-home", elem_classes=["return-home"]) | |
| # Hidden API controls share the same state; the visible transport has one toggle. | |
| api_start = gr.Button(visible=False) | |
| api_pause = gr.Button(visible=False) | |
| api_start.click(start_session, [state], [timer, status], queue=False, api_name="start").then(playback_button, [state], [playback], queue=False, api_name=False) | |
| api_pause.click(pause_session, [state], [timer, status], queue=False, api_name="pause").then(playback_button, [state], [playback], queue=False, api_name=False) | |
| outputs = [canvas, gallery, status] | |
| begin.click(enter_canvas, [state, model], | |
| [welcome, experience, canvas, gallery, status, timer, png, gif], | |
| concurrency_limit=1, concurrency_id="drawing", api_name="begin").then(playback_button, [state], [playback], queue=False, api_name=False) | |
| playback.click(toggle_playback, [state], [timer, status, playback], queue=False, api_name="toggle") | |
| fresh.click(new_start_image, [state], [canvas, gallery, status, timer, png, gif], | |
| concurrency_limit=1, concurrency_id="drawing", api_name="new_start_image").then(playback_button, [state], [playback], queue=False, api_name=False) | |
| noise_button.click(change_noise, [state], [canvas, gallery, status, timer, png, gif], | |
| concurrency_limit=1, concurrency_id="drawing", api_name="change_noise").then(playback_button, [state], [playback], queue=False, api_name=False) | |
| previous.click(step_back, [state], [canvas, status, timer], queue=False, api_name="step_back").then(playback_button, [state], [playback], queue=False, api_name=False) | |
| following.click(step_forward, [state], [canvas, status, timer], queue=False, api_name="step_forward").then(playback_button, [state], [playback], queue=False, api_name=False) | |
| back.click(back_to_start, [state], [welcome, experience, timer], queue=False, api_name="back") | |
| timer.tick(animate, [state, drift, pace], outputs, concurrency_limit=1, | |
| concurrency_id="drawing", trigger_mode="once", api_name="cycle").then(playback_button, [state], [playback], queue=False, api_name=False) | |
| download.click(export, [state], [png, gif], api_name="export") | |
| if __name__ == "__main__": | |
| demo.queue(max_size=8).launch(css=CSS, theme=THEME) | |