imgutils.sd.metadata

Overview:

Metadata parser and formatter for a1111’s webui generated images.

Here are 2 sample images: sd_metadata_simple.png and sd_metadata_complex.png.

SDMetaData

class imgutils.sd.metadata.SDMetaData(prompt: str, neg_prompt: str, parameters: Dict[str, Any])[source]

Store information parsed from the metadata of a PNG image.

Parameters:
  • prompt (str) – The main prompt text.

  • neg_prompt (str) – The negative prompt text.

  • parameters (Dict[str, Any]) – A dictionary containing various parameters.

__str__()[source]

Get a string representation of the metadata.

Returns:

A string representation of the metadata.

Return type:

str

Examples::
>>> from imgutils.sd import get_sdmeta_from_image
>>>
>>> sd1 = get_sdmeta_from_image('sd_metadata_simple.png')
>>> print(sd1)
(extremely delicate and beautiful), best quality, official art, global illumination, soft shadow, super detailed, Japanese light novel cover, 4K, metal_texture, (striped_background), super detailed background, more detailed, rich detailed, extremely detailed CG unity 8k wallpaper, ((unreal)), sci-fi,(fantasy),(masterpiece),(super delicate), (illustration), (extremely delicate and beautiful), anime coloring,
(silver_skin), ((high-cut silver_impossible_bodysuit), ((gem_on_chest)),(high-cut_silver_mechanical_leotard)),headgear,
(focus-on:1.1),(1_girl),((solo)),slim_waist,white hair, long hair, luminous yellow eyes,(medium_breast:1.2), (Indistinct_cameltoe:0.9), (flat_crotch:1.1),(coquettish), (squint:1.4),(evil_smile :1.35),(dark_persona), [open mouth: 0.7], standing,[wet:0.7],
slim_face, tall_girl,(mature),mature_face, (slim_figure), (slim_legs:1.1), (groin:1.1), ((bare_thighs)),
Negative prompt: EasyNegative, sketch, duplicate, ugly, huge eyes, text, logo, monochrome, worst face, (bad and mutated hands:1.3), (worst quality:2.0), (low quality:2.0), (blurry:2.0), horror, geometry, bad_prompt, (bad hands), (missing fingers), multiple limbs, bad anatomy, (interlocked fingers:1.2), Ugly Fingers, (extra digit and hands and fingers and legs and arms:1.4), ((2girl)), (deformed fingers:1.2), (long fingers:1.2),(bad-artist-anime), bad-artist, bad hand, blush, (lipstick),skindentation, tie, ((big_breast)), (nipple), thighhighs, pubic_hair, pussy, black and white,(3d), ((realistic)),blurry,nipple slip, (nipple), blush, head_out_of_frame,curvy,
Steps: 20, Sampler: DDIM, CFG scale: 7, Seed: 3827064803, Size: 512x848, Model hash: eb49192009, Model: AniDosMix, Clip skip: 2
property pnginfo: PngInfo

Generate a PngInfo object with the metadata.

This can be used when saving an image with custom metadata.

Returns:

A PngInfo object containing the metadata.

Return type:

PngInfo

Examples::
>>> from PIL import Image
>>> from imgutils.sd import get_sdmeta_from_image
>>>
>>> # get metadata
>>> sd1 = get_sdmeta_from_image('sd_metadata_simple.png')
>>>
>>> # create an image
>>> img = Image.new('RGB', (256, 256), 'white')
>>>
>>> # save this image with sd1's metadata
>>> img.save('new_image.png', pnginfo=sd1.pnginfo)
>>>
>>> # let's see what is in 'new_image.png'
>>> get_sdmeta_from_image('new_image.png')
SDMetaData(prompt='(extremely delicate and beautiful), best quality, official art, global illumination, soft shadow, super detailed, Japanese light novel cover, 4K, metal_texture, (striped_background), super detailed background, more detailed, rich detailed, extremely detailed CG unity 8k wallpaper, ((unreal)), sci-fi,(fantasy),(masterpiece),(super delicate), (illustration), (extremely delicate and beautiful), anime coloring,\n(silver_skin), ((high-cut silver_impossible_bodysuit), ((gem_on_chest)),(high-cut_silver_mechanical_leotard)),headgear,\n(focus-on:1.1),(1_girl),((solo)),slim_waist,white hair, long hair, luminous yellow eyes,(medium_breast:1.2), (Indistinct_cameltoe:0.9), (flat_crotch:1.1),(coquettish), (squint:1.4),(evil_smile :1.35),(dark_persona), [open mouth: 0.7], standing,[wet:0.7],\nslim_face, tall_girl,(mature),mature_face, (slim_figure), (slim_legs:1.1), (groin:1.1), ((bare_thighs)),', neg_prompt='EasyNegative, sketch, duplicate, ugly, huge eyes, text, logo, monochrome, worst face, (bad and mutated hands:1.3), (worst quality:2.0), (low quality:2.0), (blurry:2.0), horror, geometry, bad_prompt, (bad hands), (missing fingers), multiple limbs, bad anatomy, (interlocked fingers:1.2), Ugly Fingers, (extra digit and hands and fingers and legs and arms:1.4), ((2girl)), (deformed fingers:1.2), (long fingers:1.2),(bad-artist-anime), bad-artist, bad hand, blush, (lipstick),skindentation, tie, ((big_breast)), (nipple), thighhighs, pubic_hair, pussy, black and white,(3d), ((realistic)),blurry,nipple slip, (nipple), blush, head_out_of_frame,curvy,', parameters={'Steps': 20, 'Sampler': 'DDIM', 'CFG scale': 7, 'Seed': 3827064803, 'Size': (512, 848), 'Model hash': 'eb49192009', 'Model': 'AniDosMix', 'Clip skip': 2})
property text: str

Get the metadata as a formatted string.

This property provides a convenient way to access the string representation of the metadata without calling _sdmeta_text() directly.

Returns:

A formatted string containing the metadata.

Return type:

str

Example:
>>> metadata = SDMetaData(
...     prompt="A starry night",
...     neg_prompt="Daylight",
...     parameters={"Steps": 40, "Sampler": "Euler", "CFG scale": 8}
... )
>>> print(metadata.text)
A starry night
Negative prompt: Daylight
Steps: 40, Sampler: Euler, CFG scale: 8

parse_sdmeta_from_text

imgutils.sd.metadata.parse_sdmeta_from_text(x: str) SDMetaData[source]

Parse metadata information from a string.

Parameters:

x (str) – The input string containing metadata.

Returns:

A SDMetaData object containing the parsed metadata.

Return type:

SDMetaData

Examples::
>>> from imgutils.sd import parse_sdmeta_from_text
>>>
>>> sd1 = parse_sdmeta_from_text("""
... (extremely delicate and beautiful), best quality, official art, global illumination, soft shadow, super detailed, Japanese light novel cover, 4K, metal_texture, (striped_background), super detailed background, more detailed, rich detailed, extremely detailed CG unity 8k wallpaper, ((unreal)), sci-fi,(fantasy),(masterpiece),(super delicate), (illustration), (extremely delicate and beautiful), anime coloring,
... (silver_skin), ((high-cut silver_impossible_bodysuit), ((gem_on_chest)),(high-cut_silver_mechanical_leotard)),headgear,
... (focus-on:1.1),(1_girl),((solo)),slim_waist,white hair, long hair, luminous yellow eyes,(medium_breast:1.2), (Indistinct_cameltoe:0.9), (flat_crotch:1.1),(coquettish), (squint:1.4),(evil_smile :1.35),(dark_persona), [open mouth: 0.7], standing,[wet:0.7],
... slim_face, tall_girl,(mature),mature_face, (slim_figure), (slim_legs:1.1), (groin:1.1), ((bare_thighs)),
... Negative prompt: EasyNegative, sketch, duplicate, ugly, huge eyes, text, logo, monochrome, worst face, (bad and mutated hands:1.3), (worst quality:2.0), (low quality:2.0), (blurry:2.0), horror, geometry, bad_prompt, (bad hands), (missing fingers), multiple limbs, bad anatomy, (interlocked fingers:1.2), Ugly Fingers, (extra digit and hands and fingers and legs and arms:1.4), ((2girl)), (deformed fingers:1.2), (long fingers:1.2),(bad-artist-anime), bad-artist, bad hand, blush, (lipstick),skindentation, tie, ((big_breast)), (nipple), thighhighs, pubic_hair, pussy, black and white,(3d), ((realistic)),blurry,nipple slip, (nipple), blush, head_out_of_frame,curvy,
... Steps: 20, Sampler: DDIM, CFG scale: 7, Seed: 3827064803, Size: 512x848, Model hash: eb49192009, Model: AniDosMix, Clip skip: 2
... """)
>>> sd1
SDMetaData(prompt='(extremely delicate and beautiful), best quality, official art, global illumination, soft shadow, super detailed, Japanese light novel cover, 4K, metal_texture, (striped_background), super detailed background, more detailed, rich detailed, extremely detailed CG unity 8k wallpaper, ((unreal)), sci-fi,(fantasy),(masterpiece),(super delicate), (illustration), (extremely delicate and beautiful), anime coloring,\n(silver_skin), ((high-cut silver_impossible_bodysuit), ((gem_on_chest)),(high-cut_silver_mechanical_leotard)),headgear,\n(focus-on:1.1),(1_girl),((solo)),slim_waist,white hair, long hair, luminous yellow eyes,(medium_breast:1.2), (Indistinct_cameltoe:0.9), (flat_crotch:1.1),(coquettish), (squint:1.4),(evil_smile :1.35),(dark_persona), [open mouth: 0.7], standing,[wet:0.7],\nslim_face, tall_girl,(mature),mature_face, (slim_figure), (slim_legs:1.1), (groin:1.1), ((bare_thighs)),', neg_prompt='EasyNegative, sketch, duplicate, ugly, huge eyes, text, logo, monochrome, worst face, (bad and mutated hands:1.3), (worst quality:2.0), (low quality:2.0), (blurry:2.0), horror, geometry, bad_prompt, (bad hands), (missing fingers), multiple limbs, bad anatomy, (interlocked fingers:1.2), Ugly Fingers, (extra digit and hands and fingers and legs and arms:1.4), ((2girl)), (deformed fingers:1.2), (long fingers:1.2),(bad-artist-anime), bad-artist, bad hand, blush, (lipstick),skindentation, tie, ((big_breast)), (nipple), thighhighs, pubic_hair, pussy, black and white,(3d), ((realistic)),blurry,nipple slip, (nipple), blush, head_out_of_frame,curvy,', parameters={'Steps': 20, 'Sampler': 'DDIM', 'CFG scale': 7, 'Seed': 3827064803, 'Size': (512, 848), 'Model hash': 'eb49192009', 'Model': 'AniDosMix', 'Clip skip': 2})
>>> type(sd1)
<class 'imgutils.sd.metadata.SDMetaData'>
>>>
>>> sd2 = parse_sdmeta_from_text("""
... 1girl, solo, blue eyes, black footwear, white hair, looking at viewer, shoes, full body, standing, bangs, indoors, wide sleeves, ahoge, dress, closed mouth, blush, long sleeves, potted plant, bag, plant, hair bun, window,<lora:BlueArchive10:1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1>,BlueArchive,
... Negative prompt: Neg1,Negative,
... Steps: 20, Sampler: DPM++ 2M SDE Karras, CFG scale: 7, Seed: 2647703743, Size: 768x768, Model hash: 72bd94132e, Model: CuteMix, Denoising strength: 0.7, ControlNet 0: "preprocessor: openpose, model: control_v11p_sd15_openpose [cab727d4], weight: 1, starting/ending: (0, 1), resize mode: Crop and Resize, pixel perfect: False, control mode: Balanced, preprocessor params: (512, 64, 64)", Hires upscale: 2, Hires upscaler: Latent, TI hashes: "Neg1: 339cc9210f70, Negative: 66a7279a88dd", Version: v1.5.1
... """)
>>> sd2
SDMetaData(prompt='1girl, solo, blue eyes, black footwear, white hair, looking at viewer, shoes, full body, standing, bangs, indoors, wide sleeves, ahoge, dress, closed mouth, blush, long sleeves, potted plant, bag, plant, hair bun, window,<lora:BlueArchive10:1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1>,BlueArchive,', neg_prompt='Neg1,Negative,', parameters={'Steps': 20, 'Sampler': 'DPM++ 2M SDE Karras', 'CFG scale': 7, 'Seed': 2647703743, 'Size': (768, 768), 'Model hash': '72bd94132e', 'Model': 'CuteMix', 'Denoising strength': 0.7, 'ControlNet 0': 'preprocessor: openpose, model: control_v11p_sd15_openpose [cab727d4], weight: 1, starting/ending: (0, 1), resize mode: Crop and Resize, pixel perfect: False, control mode: Balanced, preprocessor params: (512, 64, 64)', 'Hires upscale': 2, 'Hires upscaler': 'Latent', 'TI hashes': 'Neg1: 339cc9210f70, Negative: 66a7279a88dd', 'Version': 'v1.5.1'})
>>> type(sd2)
<class 'imgutils.sd.metadata.SDMetaData'>

get_sdmeta_from_image

imgutils.sd.metadata.get_sdmeta_from_image(image: str | PathLike | bytes | bytearray | BinaryIO | Image) SDMetaData | None[source]

Extract and parse Stable Diffusion metadata from an image.

This function attempts to read SD metadata from various sources within the image, including PNG info, EXIF data, and GIF metadata. If found, it parses the metadata into an SDMetaData object.

Parameters:

image (ImageTyping) – The input image, which can be a file path, URL, or PIL Image object.

Returns:

An SDMetaData object containing the parsed metadata if available, else None.

Return type:

Optional[SDMetaData]

Raises:

Various exceptions may be raised by the underlying image loading and metadata reading functions.

Example usage:
>>> from imgutils.sd import get_sdmeta_from_image
>>> sd_meta = get_sdmeta_from_image('path/to/image.png')
>>> if sd_meta:
...     print(f"Prompt: {sd_meta.prompt}")
...     print(f"Negative prompt: {sd_meta.neg_prompt}")
...     print(f"Parameters: {sd_meta.parameters}")
... else:
...     print("No SD metadata found in the image.")

Note: This function depends on the load_image and parse_sdmeta_from_text functions. Ensure these are properly imported or defined in the current scope.

save_image_with_sdmeta

imgutils.sd.metadata.save_image_with_sdmeta(image: str | PathLike | bytes | bytearray | BinaryIO | Image, dst_file: str | PathLike, metadata: SDMetaData, **kwargs)[source]

Save an image with Stable Diffusion metadata.

This function saves the given image to the specified destination file, including the provided SD metadata. The metadata is saved in a format appropriate for the output image type (PNG, JPEG, WebP, or GIF).

Parameters:
  • image (ImageTyping) – The input image, which can be a file path, URL, or PIL Image object.

  • dst_file (Union[str, os.PathLike]) – The destination file path where the image will be saved.

  • metadata (SDMetaData) – The SD metadata to include with the image.

  • kwargs – Additional keyword arguments to pass to the underlying save function.

Raises:

SystemError – If the output file type is not supported for saving with metadata.

Raises:

Various exceptions may be raised by the underlying image loading and saving functions.

Example usage:
>>> from imgutils.sd import get_sdmeta_from_image, save_image_with_sdmeta
>>> input_image = 'path/to/input.png'
>>> output_image = 'path/to/output.png'
>>> sd_meta = get_sdmeta_from_image(input_image)
>>> if sd_meta:
...     save_image_with_sdmeta(input_image, output_image, sd_meta)
...     print(f"Image saved with SD metadata to {output_image}")
... else:
...     print("No SD metadata found in the input image.")