Implementation:AUTOMATIC1111 Stable diffusion webui Script Callbacks
| Knowledge Sources | |
|---|---|
| Domains | Extension API, Event System, Plugin Architecture |
| Last Updated | 2025-05-15 00:00 GMT |
Overview
Provides an event-driven callback system that allows extensions and scripts to register hooks for key application lifecycle events, such as app startup, model loading, image saving, CFG denoising steps, and UI construction.
Description
This module implements the core extension API through the following components:
Parameter Classes:
ImageSaveParams: Holds the PIL image, processing parameters, filename, and PNG info for image save callbacks.ExtraNoiseParams: Contains noise tensor, latent image, and noisy latent for extra noise callbacks.CFGDenoiserParams: Provides access to latent state, conditioning, sigma, sampling step counts, and the denoiser object during CFG denoising.CFGDenoisedParams: Provides the denoised latent state and inner model reference after denoising.AfterCFGCallbackParams: Provides latent state after CFG calculations for post-processing.UiTrainTabParams,ImageGridLoopParams,BeforeTokenCounterParams: Specialized parameter objects for their respective callbacks.
Callback Infrastructure:
ScriptCallback: A dataclass storing the callback function, source script filename, and unique name.callback_map: A global dictionary containing lists of registered callbacks for over 20 event categories.add_callback: Registers a callback with automatic extension detection and unique name generation.sort_callbacks: Topologically sorts callbacks based on before/after dependency ordering from extension metadata, with optional user priority overrides.ordered_callbacks: Cached sorted callback retrieval for performance.
Registration Functions (on_* API):
Over 20 registration functions including on_app_started, on_model_loaded, on_ui_tabs, on_ui_settings, on_before_image_saved, on_image_saved, on_extra_noise, on_cfg_denoiser, on_cfg_denoised, on_cfg_after_cfg, on_before_component, on_after_component, on_image_grid, on_infotext_pasted, on_script_unloaded, on_before_ui, on_list_optimizers, on_list_unets, on_before_token_counter, and on_before_reload.
Dispatch Functions:
Each event category has a corresponding dispatch function (e.g., app_started_callback, model_loaded_callback) that iterates through sorted callbacks, calls each with appropriate parameters, and handles exceptions via report_exception.
Cleanup:
remove_current_script_callbacks: Removes all callbacks registered by the calling script.remove_callbacks_for_function: Removes callbacks matching a specific function reference.clear_callbacks: Clears all registered callbacks globally.
Usage
Use this module to integrate extensions with the WebUI. Extensions call the on_* registration functions during their initialization to hook into application lifecycle events. The callback system provides the primary mechanism for extending the WebUI's functionality without modifying core code.
Code Reference
Source Location
- Repository: AUTOMATIC1111_Stable_diffusion_webui
- File: modules/script_callbacks.py
- Lines: 1-613
Signature
def on_app_started(callback, *, name=None):
def on_model_loaded(callback, *, name=None):
def on_ui_tabs(callback, *, name=None):
def on_ui_settings(callback, *, name=None):
def on_before_image_saved(callback, *, name=None):
def on_image_saved(callback, *, name=None):
def on_cfg_denoiser(callback, *, name=None):
def on_cfg_denoised(callback, *, name=None):
def on_cfg_after_cfg(callback, *, name=None):
def on_before_component(callback, *, name=None):
def on_after_component(callback, *, name=None):
def on_infotext_pasted(callback, *, name=None):
def on_script_unloaded(callback, *, name=None):
def on_before_ui(callback, *, name=None):
def on_list_optimizers(callback, *, name=None):
def on_list_unets(callback, *, name=None):
def on_before_token_counter(callback, *, name=None):
Import
from modules import script_callbacks
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| callback | callable | Yes | The function to be called when the event fires |
| name | str | No | Optional human-readable name for the callback for identification and ordering |
Outputs
| Name | Type | Description |
|---|---|---|
| (none) | None | Registration functions return None; dispatch functions call registered callbacks with event-specific parameters |
Usage Examples
from modules import script_callbacks
from modules.script_callbacks import ImageSaveParams
# Register a callback when the app starts
def on_app_start(demo, app):
print("App started!")
script_callbacks.on_app_started(on_app_start, name="my_startup_hook")
# Register a callback when a model is loaded
def on_model_load(sd_model):
print(f"Model loaded: {sd_model.sd_checkpoint_info.title}")
script_callbacks.on_model_loaded(on_model_load)
# Register a callback before images are saved
def before_save(params: ImageSaveParams):
# Modify the image or metadata before saving
params.pnginfo["parameters"] += "\nCustom metadata"
script_callbacks.on_before_image_saved(before_save)
# Register a new UI tab
def add_tab():
import gradio as gr
with gr.Blocks() as tab:
gr.Markdown("My Extension Tab")
return [(tab, "My Tab", "my_tab")]
script_callbacks.on_ui_tabs(add_tab)
# Clean up when script is unloaded
def cleanup():
print("Extension unloaded")
script_callbacks.on_script_unloaded(cleanup)