npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

sd-parsers

v1.3.2

Published

A library to read metadata from images created by Stable Diffusion

Readme

SD-Parsers

Read structured metadata from images created with stable diffusion.

A TypeScript package for extracting prompt information and generation parameters for AI-generated images. You need images that are already embedded with generation data to use this library, it does not "predict" anything.

Website & API: https://sd-parsers.vercel.app/ (drop an image to read its metadata; parsing happens in your browser). Source in web/.

Note: This started as a TypeScript port of the Python sd-parsers library. It keeps output parity with the Python version (checked by tests) and adds async/await, full TypeScript types and a few parsing improvements.

sd-parsers: read prompts and generation settings embedded in Stable Diffusion images

Features

Prompts, models, samplers and other well-known generation parameters are provided as easily accessible properties.

Supports reading metadata from images generated with:

| Generator | Parser | | --- | --- | | Automatic1111's Stable Diffusion web UI and the tools that write its format: Forge, Forge Classic, Forge Neo, reForge, EasyReforge, SD.Next, CivitAI (AUTOMATIC1111 style), Fooocus (A1111 scheme), ComfyUI save nodes | AUTOMATIC1111Parser | | Fooocus | FooocusParser | | ComfyUI (including JPEG / WEBP save nodes, group nodes, custom samplers and popular node packs) | ComfyUIParser | | InvokeAI | InvokeAIParser | | NovelAI (PNG and WEBP) | NovelAIParser | | SwarmUI | SwarmUIParser | | Easy Diffusion | EasyDiffusionParser | | Draw Things | DrawThingsParser | | RuinedFooocus | RuinedFooocusParser | | Stability Matrix | StabilityMatrixParser | | TensorArt | TensorArtParser | | CivitAI (node graph format) | CivitaiParser | | Hugging Face Spaces (Stable Diffusion XL spaces) | HFSpaceParser | | Dezgo | DezgoParser | | KusArt | KusArtParser | | ChatGPT, Gemini, Grok Imagine, Meta AI and other services that label their images with C2PA manifests (Content Credentials) or an IPTC digital source type | ProvenanceParser |

PromptInfo.generator names the metadata format, and PromptInfo.software the tool that actually made the image when it can be told apart, for example Forge Neo, SD.Next or Civitai for images in the AUTOMATIC1111 format.

Beyond the prompts and settings, every result also lists the LoRAs that were applied (with their weights and hashes when recorded, see getLoras()) and the image size, and toInfotext() writes the generation data of any supported tool as AUTOMATIC1111 style text, the format most tools and sites accept for pasting settings.

Helpers turn the result into plain settings, split prompts into weighted tokens, compare two images and summarize a folder of them (getGenerationSettings(), parsePromptTokens(), compareMetadata(), analyzeCollection(), and the CLI's diff and stats commands). Files and streams are read without their image or media data, so large videos take a few small reads.

Images that are labelled as AI made but carry no generation data, like those from ChatGPT or Gemini, are reported with Generators.C2PA or Generators.IPTC and the tool's name in software. Every result also gets PromptInfo.provenance when the image has C2PA manifests or an XMP digital source type, see readProvenance(). Signatures are not verified, so treat these labels as claims.

Metadata is read from:

  • PNG: tEXt, zTXt and iTXt chunks, including text stored after the image data, the eXIf chunk (CivitAI) and XMP packets. tEXt chunks holding UTF-8 text are decoded as UTF-8
  • JPEG / WEBP: the EXIF UserComment (in either UTF-16 byte order, or as ASCII / UTF-8 text), the ImageDescription, Make, Model, Software and MakerNote tags, JPEG comments (COM segments) and XMP packets. Values that ComfyUI save nodes label with a chunk name (prompt:{...}, Workflow: {...}) and JSON objects holding PNG chunk names (NovelAI, ComfyUI) are read like the PNG chunks they stand for
  • MP4 / MOV / WebM / MKV videos: ffmpeg metadata tags, which ComfyUI (Video Helper Suite and the core video nodes) and Forge use for their generation data, iTunes style items, XMP and C2PA boxes. Media data is skipped without being decoded, see readVideoMetadata()
  • PNG alpha channel: "stealth" metadata (NovelAI and the A1111 stealth-pnginfo extension), at Eagerness.EAGER

Installation

npm install sd-parsers

Requires Node.js 22 or newer (use 22.23.4, 24.22.1, 26.12.1 or later, which fix CVE-2026-111497), or any modern browser / JavaScript runtime (Deno, Bun, edge functions).

The metadata is read straight from the file contents, without decoding the image. sharp is an optional dependency, only used in Node.js to decode pixels for stealth metadata (Eagerness.EAGER). Install with npm install sd-parsers --omit=optional to skip it; everything else keeps working.

Python

The same library is published on PyPI as sd-parse, with the same version numbers and the same results for every image (checked by python/tests/test_parity.py):

pip install sd-parse

See python/README.md for its API and command line.

Command Line Usage

You can use sd-parsers from the command line to quickly print the metadata of one or more images:

npx sd-parsers image1.png image2.jpg

For each image this prints the models, samplers with their parameters, the prompt, the negative prompt and any other metadata found.

For scripts, --json prints a JSON array with one entry per file, in the same shape as promptInfoToDict() plus file, format and found (or file and error when a file can't be read):

npx sd-parsers --json image1.png image2.jpg | jq '.[].full_prompt'

--infotext prints AUTOMATIC1111 style text instead, ready to paste into the PNG Info tab of a web UI or a prompt sharing site:

npx sd-parsers --infotext comfyui.png

Commands write a new image file (-o may name the input to change it in place):

npx sd-parsers strip image.png -o clean.png                 # remove all metadata
npx sd-parsers copy original.png edited.jpg -o edited.jpg   # carry metadata over to another file, in its format
npx sd-parsers to-a1111 comfyui.png -o comfyui.png          # rewrite the generation data as AUTOMATIC1111 text

Two more commands look at the generation data, and take --json:

npx sd-parsers diff first.png second.png   # settings, prompt tokens and LoRAs that differ
npx sd-parsers stats outputs/*.png         # the software, models, samplers, sizes, LoRAs and tags a folder uses

Add --eager to also read stealth metadata from the PNG alpha channel (needs sharp). The command exits with 1 when any file can't be read. This runs locally, so prefer it over the website's /api/parse endpoint for batch jobs.

Usage

Basic usage

Import ParserManager from sd-parsers and call its parse() method. It accepts a file path (Node.js only), the file contents as a Buffer, Uint8Array or ArrayBuffer, a Blob / File, a web ReadableStream or Node.js stream, or a sharp instance, and resolves to a PromptInfo object, or null when no known metadata is found.

Read prompt information from a file:

import { ParserManager, getFullPrompt, getFullNegativePrompt, getModels } from 'sd-parsers';

const parserManager = new ParserManager();

async function main() {
  const promptInfo = await parserManager.parse('image.png');

  if (promptInfo) {
    console.log(`Generator: ${promptInfo.generator}`);
    console.log(`Prompt: ${getFullPrompt(promptInfo)}`);
    console.log(`Negative prompt: ${getFullNegativePrompt(promptInfo)}`);

    for (const model of getModels(promptInfo)) {
      console.log(`Model: ${model.name ?? model.hash}`);
    }

    for (const sampler of promptInfo.samplers) {
      console.log(`Sampler: ${sampler.name}`, sampler.parameters);
    }
  }
}

Read prompt information from a Buffer:

import { ParserManager } from 'sd-parsers';
import { readFile } from 'fs/promises';

const parserManager = new ParserManager();

async function main() {
  const imageBuffer = await readFile('image.png');
  const promptInfo = await parserManager.parse(imageBuffer);

  if (promptInfo) {
    console.log(promptInfo);
  }
}

Read prompt information in the browser:

import { ParserManager, Eagerness } from 'sd-parsers';

const parserManager = new ParserManager();

input.addEventListener('change', async () => {
  const promptInfo = await parserManager.parse(input.files[0], Eagerness.EAGER);
  console.log(promptInfo);
});

In browsers, stealth metadata is decoded with a canvas (createImageBitmap and OffscreenCanvas). To use another decoder, or when neither sharp nor a canvas is available, pass decodePixels, which resolves to raw, interleaved pixels:

const promptInfo = await parserManager.parse(bytes, {
  eagerness: Eagerness.EAGER,
  decodePixels: async () => ({ data, width, height, channels: 4 }),
});

Without a pixel decoder, stealth metadata is skipped and the other metadata is still read.

Pass a file path or the file contents to get all metadata. When a sharp instance is passed, the original file contents are not available, so text chunks stored after the image data cannot be told apart from the ones before it.

Parsing options

Configure metadata extraction:

import { ParserManager, Eagerness } from 'sd-parsers';

const parserManager = new ParserManager({ eagerness: Eagerness.EAGER });

// or per call
const promptInfo = await parserManager.parse('image.png', Eagerness.FAST);

Eagerness sets the metadata searching effort:

  • FAST: cut some corners to save some time (PNG text chunks before the image data, JPEG / WEBP UserComment)
  • DEFAULT: try to ensure all metadata is read (all PNG text chunks; default)
  • EAGER: include additional methods to try and retrieve metadata, such as stealth metadata in the alpha channel (computationally expensive!)

Only use specific parser modules:

import { ParserManager, AUTOMATIC1111Parser } from 'sd-parsers';

const parserManager = new ParserManager({
  managedParsers: [AUTOMATIC1111Parser]
});

Keep the original parameter names:

By default, parameter names are normalized (for example cfg_scale, steps, seed). Turn this off to get the names as the generator wrote them:

const parserManager = new ParserManager({ normalizeParameters: false });

Debug mode:

const parserManager = new ParserManager({ debug: true });

Prints the errors that individual parsers ran into while trying an image.

Output

parse() returns a PromptInfo object:

interface PromptInfo {
  generator: Generators;              // metadata format, e.g. Generators.COMFYUI
  software?: string;                  // the tool that made the image, e.g. 'Forge Neo'
  samplers: Sampler[];                // samplers with their model, prompts and parameters
  loras?: Lora[];                     // { name, weight?, clipWeight?, hash? }
  width?: number;                     // generation size, or the size in the image header
  height?: number;
  metadata: Record<string, any>;      // other generator-specific parameters
  rawParameters: Record<string, any>; // unprocessed metadata as found in the image
}

interface Sampler {
  name: string;
  parameters: Record<string, any>;    // cfg_scale, steps, seed, scheduler, ...
  samplerId?: string;
  model?: Model;                      // { name?, hash?, modelId?, metadata }
  prompts: Prompt[];                  // { value, promptId?, metadata }
  negativePrompts: Prompt[];
}

Helper functions for common lookups:

import {
  getFullPrompt,
  getFullNegativePrompt,
  getPrompts,
  getNegativePrompts,
  getModels,
  promptInfoToDict,
  promptInfoToJSON,
  toInfotext,
  getLoras,
  readImageSize
} from 'sd-parsers';

const prompt = getFullPrompt(promptInfo);              // whole prompt as a string
const negativePrompt = getFullNegativePrompt(promptInfo);
const prompts = getPrompts(promptInfo);                // unique Prompt objects across samplers
const models = getModels(promptInfo);                  // unique Model objects across samplers
const json = promptInfoToJSON(promptInfo);             // serializable summary
const infotext = toInfotext(promptInfo);               // "a cat\nNegative prompt: ...\nSteps: 20, Sampler: ..."
const size = readImageSize(bytes);                     // { width, height } from a PNG, JPEG or WEBP header

Writing metadata

writeMetadata, stripMetadata and copyMetadata take the bytes of a PNG, JPEG or WEBP file and return new bytes, without re-encoding the image:

import { readFileSync, writeFileSync } from 'fs';
import { ParserManager, toInfotext, writeMetadata, stripMetadata, copyMetadata, readMetadataEntries } from 'sd-parsers';

const image = new Uint8Array(readFileSync('comfyui.png'));

// make the image readable by tools that only know the AUTOMATIC1111 format
const promptInfo = await new ParserManager().parse(image);
writeFileSync('a1111.png', writeMetadata(image, toInfotext(promptInfo!)));

// write raw entries: PNG text chunks, or EXIF tags and a JSON UserComment in JPEG / WEBP files
writeFileSync('copy.png', writeMetadata(image, { prompt: '{...}', workflow: '{...}' }));

// move metadata to a file in another format, for example after converting the image
const jpeg = new Uint8Array(readFileSync('converted.jpg'));
writeFileSync('converted.jpg', copyMetadata(image, jpeg));

// remove it before sharing
writeFileSync('clean.png', stripMetadata(image));

const entries = readMetadataEntries(image); // { prompt: '...', workflow: '...' }

Videos

parse() reads videos like images. readVideoMetadata() gives the raw tags:

import { readVideoMetadata } from 'sd-parsers';

const video = readVideoMetadata(bytes);
// { format: 'MP4', entries: { prompt: '{...}', workflow: '{...}', encoder: 'Lavf61.7.100' }, width: 736, height: 736 }

Writing and stripping metadata is supported for images only.

Provenance

import { readProvenance, readC2pa } from 'sd-parsers';

const provenance = readProvenance(bytes);
// { source: 'C2PA', aiGenerated: true, digitalSourceType: 'trainedAlgorithmicMedia',
//   vendor: 'OpenAI', software: 'ChatGPT', c2pa: { manifests: [...] } }

const store = readC2pa(bytes); // every manifest: claim generator, actions, signers, decoded assertions

JPEG files hold at most 64 KB of metadata. Larger generation data is written as UTF-8 instead of UTF-16, and writeMetadata throws a RangeError when even that doesn't fit. stripMetadata leaves the image data alone, so stealth metadata hidden in the alpha channel stays.

Large files and streams

parse() reads files, Blobs and streams without loading their image or media data: it reads the chunks, segments or boxes that hold metadata and skips the rest. A multi-gigabyte video is read in a few small reads, and a stream is consumed only up to its last metadata, dropping skipped data as it arrives. Only Eagerness.EAGER reads everything, because stealth metadata lives in the pixels.

import { createReadStream } from 'fs';
import { ParserManager, readMetadataBytes } from 'sd-parsers';

const parser = new ParserManager();
await parser.parse('huge-video.mp4');                     // reads only the metadata boxes
await parser.parse(createReadStream('image.png'));         // Node.js streams
await parser.parse((await fetch(url)).body!);              // web streams
await parser.parse(file);                                  // a File / Blob is read in slices

const bytes = await readMetadataBytes(file);               // the metadata parts as one small file

readMetadataBytes() returns the file with its image data left out (PNG IDAT, JPEG scan data, WEBP image data but its header, MP4 mdat, Matroska clusters). Every reader of this library accepts it, but it is not a viewable image.

Analyzing metadata

import { getGenerationSettings, parsePromptTokens, compareMetadata, analyzeCollection } from 'sd-parsers';

getGenerationSettings(info);
// { software: 'Forge Neo', model: 'waiIllustriousSDXL_v160', sampler: 'Euler a', scheduler: 'Automatic',
//   steps: 24, cfgScale: 6, seed: 449383496, width: 1024, height: 1024, loras: [], prompt: '...', negativePrompt: '...' }

parsePromptTokens('(best quality:1.2), [blurry], {cute}, <lora:detail:0.6>');
// [{ text: 'best quality', weight: 1.2, kind: 'tag' }, { text: 'blurry', weight: 0.9091, kind: 'tag' },
//  { text: 'cute', weight: 1.05, kind: 'tag' }, { text: 'detail', weight: 0.6, kind: 'lora' }]  (plus `normalized`)

compareMetadata(first, second);
// { settings: { steps: [24, 20], ... }, prompt: { added, removed, reweighted }, negativePrompt: {...},
//   loras: { added, removed, reweighted }, promptSimilarity: 0.78 }

analyzeCollection(infos);
// { count: 82, software: [{ value: 'ComfyUI', count: 23 }, ...], models, samplers, schedulers, sizes, loras,
//   tags: [{ value: '1girl', count: 78 }, ...], negativeTags, steps: { min, max, mean }, cfgScale: {...} }

getGenerationSettings() turns the parsed data into plain values (numbers stay numbers, whatever the tool wrote), using the first sampler. parsePromptTokens() understands A1111 / ComfyUI and NovelAI emphasis, LoRA tags, embeddings and BREAK. diffPrompts() and promptSimilarity() work on prompt text alone. Model and LoRA names compare equal with or without their folder and file extension.

Errors

Images without known metadata, and images in formats other than PNG, JPEG and WEBP, resolve to null. When a parser cannot read the metadata it raises a ParserError internally, and ParserManager moves on to the next parser instead of crashing. Turn on debug to see these errors. Errors unrelated to metadata, such as a missing file, are thrown as usual, and input that is not an image at all is rejected with an UnidentifiedImageError.

API Reference

Classes

  • ParserManager: Parses images and videos with every parser, see Basic usage
  • Parser: Base class for parsers; MANAGED_PARSERS lists the ones ParserManager uses, in order
  • Parsers, one per metadata format: AUTOMATIC1111Parser, ComfyUIParser, FooocusParser, InvokeAIParser, NovelAIParser, SwarmUIParser, EasyDiffusionParser, DrawThingsParser, RuinedFooocusParser, StabilityMatrixParser, TensorArtParser, CivitaiParser, HFSpaceParser, DezgoParser, KusArtParser, ProvenanceParser
  • ParserError, MetadataError: Errors raised while parsing, caught by ParserManager
  • UnidentifiedImageError: Raised when the input is not an image or video

Functions

Reading the parsed data:

  • getFullPrompt(), getFullNegativePrompt(): The positive and negative prompt as one string
  • getPrompts(), getNegativePrompts(), getModels(): The unique prompts and models of all samplers
  • promptInfoToDict(), promptInfoToJSON(): A plain object or JSON string, the shape the CLI prints with --json
  • toInfotext(): The generation data as AUTOMATIC1111 style text
  • getLoras(), lorasFromPromptTags(), lorasFromA1111(), lorasFromComfyGraph(): LoRAs, from the whole result or one source
  • getGenerationSize(): The image size recorded in the generation data
  • detectSoftware(), detectA1111Software(): The tool that made the image

Analyzing (Analyzing metadata):

  • getGenerationSettings(): Model, sampler, steps, CFG scale, seed, size, LoRAs and prompts as plain values
  • parsePromptTokens(), normalizeTag(): Weighted prompt tokens
  • compareMetadata(), diffPrompts(), promptSimilarity(): What differs between two images
  • analyzeCollection(): What many images use

Reading files:

  • readMetadataBytes(): The metadata parts of a file, Blob or stream, see Large files and streams
  • readMetadataEntries(): The text metadata of an image, keyed by chunk or tag name
  • readImageSize(): Width and height from the image header
  • detectFormat(), detectVideoFormat(): The image or video format of some bytes
  • readVideoMetadata(): The metadata tags of a video, see Videos
  • readProvenance(), readC2pa(), extractC2pa(), readJumbf(), decodeCbor(): C2PA and XMP provenance labels, see Provenance

Writing files (Writing metadata):

  • writeMetadata(), stripMetadata(), copyMetadata(): Write, remove or carry over the metadata of PNG, JPEG and WEBP files

Building results (for custom parsers): createPromptInfo(), createSampler(), createModel(), createPrompt(), modelToString(), promptToString()

Types

  • PromptInfo: Contains structured image generation parameters
  • Sampler: Represents a sampler used during image generation
  • Model: Represents a checkpoint model
  • Prompt: Represents an image generation prompt
  • Lora: A LoRA applied to the image, with its weights and hash
  • ImageSize: Width and height of an image
  • GenerationSettings, PromptToken, PromptDiff, MetadataComparison, CollectionStats, Count, Range: Results of the analysis helpers
  • Provenance, C2paManifestStore, C2paManifest, C2paAction, JumbfBox, CborTagged: C2PA and XMP provenance labels
  • VideoFormat, VideoMetadata: Video formats and their metadata
  • ImageFormat, ImageSource: Image formats and encoded images
  • ParseInput, ParseOptions: Inputs and per-call options of ParserManager.parse()
  • StreamInput: Inputs of readMetadataBytes(): file path, Blob, web ReadableStream or async iterable
  • DecodedPixels, PixelDecoder: Raw pixel data for stealth metadata

Enums

  • Generators: The metadata formats that are understood: AUTOMATIC1111, ComfyUI, Fooocus, InvokeAI, NovelAI, SwarmUI, Easy Diffusion, Draw Things, RuinedFooocus, Stability Matrix, TensorArt, Civitai, Hugging Face Space, Dezgo, KusArt, C2PA, IPTC, Unknown
  • Eagerness: Metadata extraction effort levels (FAST, DEFAULT, EAGER)

Development

Building

npm run build

Testing

npm test

Watch mode

npm run dev

Differences from Python Version

This TypeScript port has some differences from the original Python version:

  1. Image Processing: Metadata is read from the file contents directly; pixels are only decoded (with sharp or a canvas) for stealth metadata
  2. Async/Await: All parsing operations are asynchronous
  3. Type Safety: Full TypeScript type definitions
  4. Field Names: Data fields use camelCase (rawParameters, negativePrompts, samplerId, ...)
  5. Module System: Uses ES modules/CommonJS instead of Python imports
  6. More Metadata Sources: JPEG / WEBP files written by ComfyUI and NovelAI, CivitAI images and UTF-8 text in PNG tEXt chunks are read
  7. More Lenient Parsing: Malformed metadata is rejected with a ParserError instead of crashing, JSON containing NaN / Infinity is accepted and Fooocus images without a model hash or negative prompt are still parsed

Checking against the Python library

tests/resources/upstream-expected.json holds the output of the Python library for every test image, and tests/integration/upstream-parity.test.ts checks that this package produces the same results. To refresh it after upstream changes:

git clone https://github.com/d3x-at/sd-parsers /tmp/sd-parsers-upstream
pip install /tmp/sd-parsers-upstream
python scripts/generate-upstream-fixtures.py /tmp/sd-parsers-upstream

Contributing

Contributions are welcome! If you find issues or want to add support for additional image generators, please open an issue or pull request.

License

MIT License, same as the original Python version.

Credits