Skip to content

Latest commit

 

History

History
264 lines (203 loc) · 8.49 KB

script-examples.md

File metadata and controls

264 lines (203 loc) · 8.49 KB

Script Examples

Complete, working scripts covering tagging, image editing, tag editing, one-shot vs. persistent, and a JSON descriptor with a user option. See Script Development for the protocol/descriptor reference these build on. The one-shot/persistent examples below are also available as ready-to-copy files in docs/examples/scripts/.

Auto-tagging (one-shot)

Reads one request, replies with tags, exits. tags_mode: "replace_layer" means re-running it replaces its own previous suggestions instead of piling up.

import sys
import json
import random

TAGS = ["cat", "dog", "outdoors", "indoors", "sunlight", "night", "forest", "city", "water", "sky"]

if "-startup" in sys.argv:
    print("Started successfully. To run this on an image, select it and use Run on selected (Ctrl+Q) - exiting for now.", file=sys.stderr, flush=True)
    sys.exit(0)

req  = json.loads(sys.stdin.readline())
path = req["params"]["image_path"]  # load your model and run inference on this

chosen = random.sample(TAGS, random.randint(2, 5))
tags   = [{"name": tag, "layer": "img2tag", "weight": round(random.uniform(0.5, 1.0), 2)} for tag in chosen]
result = {"tags": tags, "tags_mode": "replace_layer", "default_layer": "img2tag"}

print(json.dumps({"id": req["id"], "result": result, "error": None}), flush=True)

Auto-tagging (persistent)

Same behavior, but stays running between images so a slow model load only happens once. Reads stdin on a background thread so the main thread can enforce an idle timeout (60s here) and exit on its own.

import sys
import json
import random
import queue
import threading

TIMEOUT = 60  # seconds of inactivity before quitting

TAGS = ["cat", "dog", "outdoors", "indoors", "sunlight", "night", "forest", "city", "water", "sky"]

def process(params):
    # params["image_path"] is the full path to the image — load your model here.
    chosen = random.sample(TAGS, random.randint(2, 5))
    tags   = [{"name": tag, "layer": "img2tag", "weight": round(random.uniform(0.5, 1.0), 2)} for tag in chosen]
    return {"tags": tags, "tags_mode": "replace_layer", "default_layer": "img2tag"}

def stdin_reader(q):
    for line in sys.stdin:
        q.put(line)
    q.put(None)  # signal EOF / app closed

q = queue.Queue()
threading.Thread(target=stdin_reader, args=(q,), daemon=True).start()

print("ready", file=sys.stderr, flush=True)

while True:
    try:
        line = q.get(timeout=TIMEOUT)
    except queue.Empty:
        print(f"No requests for {TIMEOUT}s — exiting.", file=sys.stderr, flush=True)
        break
    if line is None:
        break
    line = line.strip()
    if not line:
        continue
    try:
        req    = json.loads(line)
        result = process(req.get("params", {}))
        resp   = {"id": req["id"], "result": result, "error": None}
    except Exception as e:
        resp   = {"id": req.get("id"), "result": None, "error": str(e)}
    print(json.dumps(resp), flush=True)

Image editing (one-shot)

Converts the image to grayscale and writes it back to the same path. "image_modified": true tells the app to flush its thumbnail/preview cache so the change shows up.

import sys
import json

if "-startup" in sys.argv:
    print("Started successfully. To run this on an image, select it and use Run on selected (Ctrl+Q) - exiting for now.", file=sys.stderr, flush=True)
    sys.exit(0)

from PIL import Image  # pip install Pillow

req  = json.loads(sys.stdin.readline())
path = req["params"]["image_path"]

# Load, process, then save back to the same path so the app picks up the change.
Image.open(path).convert("L").convert("RGB").save(path)

print(json.dumps({"id": req["id"], "result": {"image_modified": True}, "error": None}), flush=True)

Image editing (persistent)

Same grayscale conversion, kept running between images with the same idle-timeout pattern as the persistent tagger above.

import sys
import json
import queue
import threading
from PIL import Image  # pip install Pillow

TIMEOUT = 60  # seconds of inactivity before quitting

def process(params):
    path = params["image_path"]
    Image.open(path).convert("L").convert("RGB").save(path)

def stdin_reader(q):
    for line in sys.stdin:
        q.put(line)
    q.put(None)

q = queue.Queue()
threading.Thread(target=stdin_reader, args=(q,), daemon=True).start()

print("ready", file=sys.stderr, flush=True)

while True:
    try:
        line = q.get(timeout=TIMEOUT)
    except queue.Empty:
        print(f"No requests for {TIMEOUT}s — exiting.", file=sys.stderr, flush=True)
        break
    if line is None:
        break
    line = line.strip()
    if not line:
        continue
    try:
        req  = json.loads(line)
        process(req.get("params", {}))
        resp = {"id": req["id"], "result": {"image_modified": True}, "error": None}
    except Exception as e:
        resp = {"id": req.get("id"), "result": None, "error": str(e)}
    print(json.dumps(resp), flush=True)

Tag editing (one-shot)

Receives the image's current tags and returns a modified set — here, just sorted alphabetically. tags_mode: "replace_all" means the entire tag set is replaced with whatever's returned, not merged.

import sys
import json

if "-startup" in sys.argv:
    print("Started successfully. To run this on an image's tags, select it and use Run on selected (Ctrl+Q) - exiting for now.", file=sys.stderr, flush=True)
    sys.exit(0)

req  = json.loads(sys.stdin.readline())
tags = req["params"].get("tags", [])

# Each tag is a dict with at least "name". May also have: layer, weight, bound_area.
sorted_tags = sorted(tags, key=lambda t: t.get("name", "").lower())
result = {"tags": sorted_tags, "tags_mode": "replace_all"}

print(json.dumps({"id": req["id"], "result": result, "error": None}), flush=True)

Tag editing (persistent)

Same sorting logic, kept running between calls.

import sys
import json
import queue
import threading

TIMEOUT = 60  # seconds of inactivity before quitting

def process(params):
    tags = params.get("tags", [])
    sorted_tags = sorted(tags, key=lambda t: t.get("name", "").lower())
    return {"tags": sorted_tags, "tags_mode": "replace_all"}

def stdin_reader(q):
    for line in sys.stdin:
        q.put(line)
    q.put(None)

q = queue.Queue()
threading.Thread(target=stdin_reader, args=(q,), daemon=True).start()

print("ready", file=sys.stderr, flush=True)

while True:
    try:
        line = q.get(timeout=TIMEOUT)
    except queue.Empty:
        print(f"No requests for {TIMEOUT}s — exiting.", file=sys.stderr, flush=True)
        break
    if line is None:
        break
    line = line.strip()
    if not line:
        continue
    try:
        req    = json.loads(line)
        result = process(req.get("params", {}))
        resp   = {"id": req["id"], "result": result, "error": None}
    except Exception as e:
        resp   = {"id": req.get("id"), "result": None, "error": str(e)}
    print(json.dumps(resp), flush=True)

A script with a JSON descriptor and an option

A descriptor is needed as soon as a script wants user-configurable options, a specific interpreter, or a dedicated Python environment. This one adds a single option — a configurable tag prefix — that shows up in the app's Script Options dialog.

Scripts/prefix_tagger/SharpTagScript.json:

{
  "name": "Prefix Tagger",
  "run":  "python",
  "args": ["prefix_tagger.py"],
  "options": [
    {
      "arg":     "--prefix",
      "label":   "Tag prefix",
      "type":    "string",
      "default": "auto_"
    }
  ]
}

Scripts/prefix_tagger/prefix_tagger.py:

import sys
import json
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--prefix", default="auto_")
parser.add_argument("-process", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("-startup", action="store_true", help=argparse.SUPPRESS)
args = parser.parse_args()

if args.startup:
    print("Started successfully.", file=sys.stderr, flush=True)
    sys.exit(0)

req = json.loads(sys.stdin.readline())
tag = {"name": f"{args.prefix}tagged", "layer": "auto"}
result = {"tags": [tag], "tags_mode": "replace_layer", "default_layer": "auto"}

print(json.dumps({"id": req["id"], "result": result, "error": None}), flush=True)

Whatever value the user sets for "Tag prefix" gets appended as --prefix <value> on the command line, parsed by argparse, and used directly when building the tag. Change the prefix from auto_ to wd14_ in the Script Options dialog and the same script starts tagging images as wd14_tagged — no code changes needed.