Metadata-Version: 2.5
Name: argus-darkroom
Version: 0.3.0
Summary: Guarded image generation for the Argus suite: prompts and outputs are checked before anything is released.
Project-URL: Repository, https://github.com/smk762/argus-darkroom
Author: smk762
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: argus-cortex[images,remote,server,yaml]<0.8,>=0.7
Requires-Dist: imagehash>=4.3
Requires-Dist: pydantic>=2.7
Requires-Dist: structlog>=24.0
Requires-Dist: websockets>=15
Provides-Extra: age
Requires-Dist: argus-curator[faces]<0.18,>=0.17; extra == 'age'
Provides-Extra: cli
Requires-Dist: rich>=13.0; extra == 'cli'
Requires-Dist: typer>=0.12; extra == 'cli'
Provides-Extra: dev
Requires-Dist: argus-curator<0.18,>=0.17; extra == 'dev'
Requires-Dist: fastapi>=0.110; extra == 'dev'
Requires-Dist: httpx2>=2.7; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: rich>=13.0; extra == 'dev'
Requires-Dist: ruff==0.15.16; extra == 'dev'
Requires-Dist: typer>=0.12; extra == 'dev'
Requires-Dist: uvicorn>=0.27; extra == 'dev'
Provides-Extra: server
Requires-Dist: fastapi>=0.110; extra == 'server'
Requires-Dist: uvicorn>=0.27; extra == 'server'
Description-Content-Type: text/markdown

<h1>
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/smk762/argus-cortex/dev/brand/packages/darkroom/argus-darkroom-lockup-dark.svg">
    <img alt="argus-darkroom" src="https://raw.githubusercontent.com/smk762/argus-cortex/dev/brand/packages/darkroom/argus-darkroom-lockup-light.svg" height="52">
  </picture>
</h1>

Guarded image generation for the Argus suite. A prompt is checked before anything is generated. Each output is checked
twice, once on its own and once alongside the prompt that made it, and only then released or destroyed. A record is kept
for every attempt.

ComfyUI generates, Ollama optionally expands the prompt, SingGuard and NudeNet judge. Darkroom orchestrates them, decides
and keeps the record. Its demo UI is `argus-safelight`. Part of the
[Argus suite](https://github.com/smk762?tab=repositories&q=argus). The design is in [`spec.md`](spec.md).

```
safelight :3000 ──▶ argus-darkroom :8106 ──▶ ComfyUI :8188
                     record store            Ollama :11434 (optional)
                     output root             SingGuard :9150
                                             NudeNet
```

## How a generation runs

1. **Assemble** the final prompt: your text (or its Ollama expansion), then the LoRA trigger words.
2. **Pre-flight**: SingGuard reads the final prompt and the negative prompt, framed together, under every selected
   policy. An illegal rule refuses. A failed check refuses. Nothing has been rendered yet.
3. **Input scan** (image-to-image and inpainting only): the input image gets the same checks as an output (step 5),
   before anything reaches ComfyUI. It goes on only if its outcome is `passed`; anything else, a check that could not
   run included, refuses the attempt with `outcome_reason` `input image: <reason>`. The input is never written to disk.
   An inpainting mask is not scanned: it only selects which pixels are repainted (see [Inpainting](#inpainting)).
4. **Render** through ComfyUI. The image comes back over the websocket and is held in memory only.
5. **Scan**: per policy, SingGuard judges the image alone and with the prompt. NudeNet scores exposure. If the age check
   is installed, MiVOLO estimates an age per face.
6. **Decide and release or destroy.** `passed` and `review` images are written to the output root. `deleted` and
   `omitted` images are never written.

| Outcome | Means |
|---|---|
| `refused` | pre-flight, or the input image's scan, stopped it; nothing was rendered |
| `passed` | every cell safe |
| `review` | some cell flagged; the image is kept and served behind its shield |
| `deleted` | an illegal rule in any policy, `minor-exposed`, or an enforcing check that could not run |
| `omitted` | SFW only: NudeNet saw exposure, or did not answer |
| `failed` | expansion or generation failed, or the render came back blank; no image |

Nothing is written before the verdict: no temp file, no `SaveImage` node. A workflow containing a node that saves,
previews, exports or writes is refused when it is loaded.

**The age estimate is a tool's guess**, not a fact. It is stored as `age_estimate_years` from `mivolo`, and an
under-18 estimate with exposure deletes the image. The age check is an extra signal on top of SingGuard's minors rule.

## Run it

You need the services darkroom reaches by URL:

- **ComfyUI**, with the `SaveImageWebsocket` node, and for image-to-image and inpainting the `DarkroomLoadImageBase64`
  and `DarkroomLoadMaskBase64` nodes (below).
- **SingGuard** (agent-composer's `/api/guard/check`). **Required**: darkroom never runs unguarded, and an empty
  `ARGUS_DARKROOM_SINGGUARD_URL` makes it refuse to start.
- **NudeNet**. Without it, SFW generation is unavailable (HTTP 400) because every SFW output would be omitted.
- **Ollama**, optional, for `--expand`.

### Compose

```bash
cp .env.example .env     # set SINGGUARD_URL and MODELS_ROOT at least
docker compose up --build
```

This runs darkroom (`:8106`) and safelight (`:3000`), both published on `127.0.0.1` only (`DARKROOM_PUBLISH` /
`SAFELIGHT_PUBLISH` in `.env`). Safelight is built from
`SAFELIGHT_CONTEXT` (default `../argus-safelight`); its darkroom URL is baked in at build time from
`DARKROOM_PUBLIC_URL`. Records and images live in the `darkroom-data` volume. `MODELS_ROOT` is mounted read-only.

`DEVMODE=1` in `.env` becomes `ARGUS_DARKROOM_DEVMODE=1`. It adds `POST /purge` (and safelight's purge button), which
deletes every record and image. Leave it off anywhere you care about the output.

### Without Docker

```bash
uv pip install "argus-darkroom[server,cli]"
export ARGUS_DARKROOM_SINGGUARD_URL=http://localhost:9150
export ARGUS_DARKROOM_MODELS_ROOT=/path/to/ComfyUI/models
export ARGUS_DARKROOM_WORKFLOW=examples/workflows   # a directory: one template per family and LoRA count
argus-darkroom serve            # 127.0.0.1:8106
```

The server binds to localhost by default. It is not meant for public hosting.

### ComfyUI: the `SaveImageWebsocket` node

Darkroom takes the image from the websocket instead of from disk, so ComfyUI needs a `SaveImageWebsocket` node. It
ships with ComfyUI as an example node, `websocket_image_save.py` under `custom_nodes/`. Confirm that ComfyUI knows it:

```bash
curl -s localhost:8188/object_info/SaveImageWebsocket | head -c 200
```

An empty `{}` means the node is not installed. The node does not write to disk, which is why darkroom can use it.

### ComfyUI: the `DarkroomLoadImageBase64` and `DarkroomLoadMaskBase64` nodes (image-to-image, inpainting)

ComfyUI's stock `LoadImage` reads from its `input/` folder, so the caller's image would have to be written there and
would stay behind. Darkroom instead sends the input inside the prompt graph, as base64, to a small node vendored in this
repo: [`comfyui/darkroom_load_image_base64.py`](comfyui/darkroom_load_image_base64.py). `DarkroomLoadImageBase64`
decodes the image in memory and outputs an `IMAGE`; `DarkroomLoadMaskBase64`, in the same file, does the same for an
inpainting mask and outputs a `MASK` (1.0 where the image is repainted). Neither reads or writes a file, and neither is
an output node. The graph, and the input and mask in it, is deleted from ComfyUI's history after every run, like the
prompt. Install the file only if you use image-to-image or inpainting (if you installed it for image-to-image, copy it
again: the mask node is new):

```bash
cp comfyui/darkroom_load_image_base64.py /path/to/ComfyUI/custom_nodes/
# restart ComfyUI, then:
curl -s localhost:8188/object_info/DarkroomLoadImageBase64 | head -c 200
curl -s localhost:8188/object_info/DarkroomLoadMaskBase64 | head -c 200
```

An empty `{}` means ComfyUI has not loaded it; an image-to-image or inpainting run then fails (`failed`) after its
input scan.

### ComfyUI: the `DarkroomDepthAnything` node (depth maps)

`POST /depth/{id}` makes a depth map of a record's stored image with Depth Anything V2 Small, through a node vendored in
this repo: [`comfyui/darkroom_depth.py`](comfyui/darkroom_depth.py). It loads the model with `transformers` from a local
folder under ComfyUI's models directory and never downloads at run time. Only the Small model (Apache-2.0) loads:
Depth Anything V2 Base and Large are CC-BY-NC-4.0, so any other name, or a folder whose `config.json` is not the Small
model's, is refused. One-time setup, beside the base64 loader above (which the depth graph also uses):

```bash
huggingface-cli download depth-anything/Depth-Anything-V2-Small-hf \
    --local-dir /path/to/ComfyUI/models/depth/Depth-Anything-V2-Small-hf
cp comfyui/darkroom_depth.py comfyui/darkroom_load_image_base64.py /path/to/ComfyUI/custom_nodes/
# restart ComfyUI, then:
curl -s localhost:8188/object_info/DarkroomDepthAnything | head -c 200
```

The depth graph is built into darkroom (`argus_darkroom/depth.py`), not a template: generation never selects it and
`/models` does not list it. It needs no ComfyUI node beyond these and `SaveImageWebsocket`.

### Workflow templates

A template is a ComfyUI API-format workflow with `$placeholders`: `$base_checkpoint`, `$vae`, `$positive`, `$negative`,
`$seed`, `$steps`, `$cfg`, `$guidance`, `$sampler`, `$scheduler`, `$width`, `$height`, `$clip_skip`, and `$lora` /
`$lora_weight`, `$lora_2` / `$lora_2_weight` and so on. It must contain exactly one `SaveImageWebsocket` node and no
other node that saves, and a `$positive` slot. No node may load an image (`LoadImage` and the like): an image reaches a
run only as an image-to-image input, which darkroom checks first.

An **image-to-image** template has `$init_image`, as the `image` of exactly one `DarkroomLoadImageBase64` node, and
`$denoise`; a text-to-image template has neither. The examples feed the loader through `ImageScale` (lanczos, to
`$width` x `$height`, cropped to the centre) and `VAEEncode` into the `KSampler`, whose `denoise` is `$denoise`.

An **inpainting** template has those and `$init_mask`, as the `mask` of exactly one `DarkroomLoadMaskBase64` node;
no other template may contain that node. The examples scale the mask as they scale the image (`MaskToImage`,
`ImageScale` nearest-exact with the same size and crop, `ImageToMask` red), grow it by 8 pixels (`GrowMask`, tapered
corners), give it to the sampler with `SetLatentNoiseMask` on the encoded input, and finish with
`ImageCompositeMasked`: the decoded result over the scaled input, through the grown mask, so every pixel outside it is
exactly the input's.

`WORKFLOW` names a file or a directory:

- **A directory** holds one template per checkpoint family, LoRA count and mode, named `<family>.json` (no LoRA slots)
  or `<family>+lora<N>.json` (exactly N), with `+img2img` at the end for an image-to-image template
  (`sdxl+lora1+img2img.json`) or `+inpaint` for an inpainting one (`sdxl+lora1+inpaint.json`). A checkpoint's
  family is its top-level folder under `checkpoints/`, so `sdxl/juggernaut.safetensors` with two LoRAs renders with `sdxl+lora2.json`. When nothing fits, including a
  checkpoint outside a family folder, an input image with no `+img2img` template or a mask with no `+inpaint` one, the
  request is a 400. Darkroom never falls back to another family's template, LoRA count or mode. A misnamed or broken
  file, or one whose name and `$init_image` / `$init_mask` slots disagree, stops the server from starting.
- **A file** is used for every checkpoint, as before. Every run must then fill its LoRA slots exactly, and be of the
  file's mode: text-to-image, image-to-image or inpainting.

A template never silently drops a value the request sets. A request is a 400 if it sets something the chosen template
has no slot for: a negative prompt (Flux takes none), `guidance`, or a `clip_skip` above 2. `/models` lists each
template's `slots`, and each checkpoint's `family` and the LoRA counts it can render with (`lora_counts`, empty when
none). Records name the template in `request.workflow`, beside `workflow_sha256`.

[`examples/workflows/`](examples/workflows) ships these. They are the image's default directory:

| Family | Files | Sampling |
|---|---|---|
| `sdxl` | `sdxl`, `sdxl+lora1`, `sdxl+lora2`; image-to-image `sdxl+img2img`, `sdxl+lora1+img2img`; inpainting `sdxl+inpaint`, `sdxl+lora1+inpaint`, `sdxl+lora2+inpaint` | the usual: a negative prompt, `cfg` around 5, `clip_skip` |
| `flux` | `flux`, `flux+lora1`, `flux+lora2` | `guidance` (around 3.5 for dev), `cfg` 1, `simple` or `beta`, no negative prompt. Schnell: about 4 steps |
| `flux-klein` | `flux-klein` | FLUX.2 Klein 9B (distilled): `cfg` 1, about 4 steps, no negative prompt |
| `sd35` | `sd35` | SD3.5 Large: a negative prompt, `cfg` around 4, `euler` with `sgm_uniform` |

The Flux files under `checkpoints/` hold only the diffusion model, so `flux*.json` and `flux-klein.json` load the text
encoders and VAE by name: `t5xxl_fp8_e4m3fn` and `clip_l` with `ae` for Flux, and `qwen_3_8b_fp8mixed` with
`flux2-vae` for Klein. Edit those names to match your ComfyUI. The record pins them through `workflow_sha256`, not
by their own hash. The non-SDXL families need more VRAM than SDXL and may run out of memory on smaller GPUs.

`$clip_skip` is read as A1111 reads it for SDXL: `clip_skip` 1 and 2 both send `stop_at_clip_layer: -2`, the layer SDXL
conditions on, and `n` above 2 sends `-n`. A request may ask for 1 to 12.

## Configuration

All settings are `ARGUS_DARKROOM_*` environment variables.

| Variable | Default | |
|---|---|---|
| `SINGGUARD_URL` | | **Required.** |
| `COMFYUI_URL` | `http://localhost:8188` | |
| `NUDENET_URL` | | Empty: SFW generation unavailable. Point it at the suite's shared 640m server (argus-cortex#79) once it is up; each record names the detector that scored it. |
| `AGE_URL` | | Curator's `POST /faces?body=true`. Empty: the in-process `[age]` extra, or no age check. |
| `MINOR_EXPOSED` | `frame` | How the `minor-exposed` rule places exposure: `frame` (any estimate under 18 anywhere in the image) or `overlap` (by box, see [Age check](#age-check-optional)). Any other value refuses to start. |
| `OLLAMA_URL`, `OLLAMA_MODEL` | | Both set: `expand` is available. |
| `POLICY` | `default`, or `adult-granular` with `ALLOW_NSFW` | The enforcing policy when a request names none. |
| `THINKING` | `cascade` | `fast`, `fast-slow`, `slow`, `cascade`. |
| `ALLOW_NSFW` | off | Lets an NSFW policy enforce. |
| `OUTPUT_ROOT` | `darkroom-output` | `<id>.json` records and `<id>.png` images. |
| `MODELS_ROOT` | | ComfyUI's models folder: checkpoints and LoRAs are listed and hashed from it. |
| `DEFAULT_CHECKPOINT` | `sdxl` | The checkpoint a form starts on: an exact name, or a folder under `checkpoints/` for the first model in it. When nothing matches, `/models` reports null. |
| `WORKFLOW` | | A template file, used for every checkpoint, or a directory of them chosen per request (see [Workflow templates](#workflow-templates)). The image defaults to `/app/examples/workflows`. |
| `CORS_ORIGINS` | `localhost` and `127.0.0.1` on ports 3000 and 3097 | May read and write. `*` allows reads only. Compose defaults to port 3000 only. |
| `DEVMODE` | off | Adds `POST /purge` and `POST /purge/{id}`. |
| `READ_ONLY` | off | Answers 403 to every write from every origin: `POST /preflight`, `POST /generate/stream`, `DELETE /record/{id}` and both purges. Records and images stay readable. |

`ALLOW_NSFW`, `DEVMODE` and `READ_ONLY` accept `1`/`true`/`yes`/`on`. A mistyped value is warned about, not silently ignored.

### GPU leases (argus-iris)

Darkroom runs no model itself, but ComfyUI and Ollama do, on GPUs other services share. With the suite's GPU broker,
[argus-iris](https://github.com/smk762/argus-iris), each render (and each depth map) holds a lease on `comfyui` and
each prompt expansion one on `ollama:<OLLAMA_MODEL>`, for as long as the work runs. Iris queues them by priority,
makes room first, and may name the node to send the work to: darkroom then calls that node's ComfyUI or Ollama
instead of its own URL. The scans hold no lease: SingGuard, NudeNet and curator are tenants of their own. These are the
suite's host-wide names, read by argus-cortex, not `ARGUS_DARKROOM_*`:

| Variable | Default | |
|---|---|---|
| `ARGUS_GPU_COORDINATOR` | `none` | `broker` for iris; `lease` for a host-wide lock file; `none` gates nothing (as before). |
| `ARGUS_GPU_BROKER_URL` | | Where iris listens, e.g. `http://<GPU_BROKER_HOST>:8120`. Use an IP: the container does not resolve LAN host names. |
| `ARGUS_GPU_BROKER_TOKEN` | | The suite's shared caller token (`Authorization: Bearer`). A secret: the host's `.env` only. |
| `ARGUS_GPU_TENANT_MANIFEST` | compose: `/app/gpu-tenant.yaml` | The committed [`gpu-tenant.yaml`](gpu-tenant.yaml), registered with iris on the first lease. Or `ARGUS_GPU_TENANT=argus-darkroom`. |
| `ARGUS_GPU_BROKER_FALLBACK` | `lease` | Used while iris is unreachable, answers 5xx, or has no lease routes yet: `lease` or `none`. |
| `ARGUS_GPU_LEASE_TIMEOUT_S` | 300 | How long a run waits for its lease. |

- **Priority** comes from the caller's `X-Argus-Priority` header on `POST /generate/stream` and `POST /depth/{id}`:
  `interactive` (the default: a person at safelight or studio), `batch` (mint's sample runs) or `background`.
  `realtime` is taken as `interactive`; anything else is a 400. The CLI takes `--priority`.
- **Queueing.** With `broker`, up to 8 generations and depth runs may be in flight at once, each waiting for its own
  lease, so a second generation waits in iris's queue instead of getting a 409 (callers can drop their retry loops).
  The SSE stream sends `queued` before the wait. A ninth still gets a 409, and a purge still waits for none to run.
  With `none` or `lease`, one at a time as before.
- **A lease is not an OOM.** A refused lease, one not granted in time, or a broker error is a `failed` record whose
  reason says so; nothing retries it. A failed expansion lease is `expansion failed: ...` like any failed expansion.
- **Every ComfyUI is checked.** The output-node check runs once per workflow on each ComfyUI darkroom renders on, the
  prompt is deleted from the history of the ComfyUI that rendered it, and `POST /purge` clears every ComfyUI the
  broker has sent work to since the server started.
- In the container, the `lease` fallback orders darkroom's own runs only: no lock directory is shared with the host.

Policies are chosen by name (`default`, `adult`, `adult-granular`, `adult-cautious`, `adult-cinematic`); a request cannot carry policy
text. `default` and `sfw-*` are SFW, the rest NSFW. SFW refuses on any pre-flight flag and omits exposed output. NSFW
warns on non-illegal flags and blurs exposed output, and illegal content is refused and deleted in both.

## CLI

```bash
argus-darkroom preflight "a cat on a sofa" -n "blurry"
argus-darkroom generate "a cat on a sofa" --checkpoint sdxl/base.safetensors \
    --sampler euler --scheduler normal --steps 20 --cfg 5 --width 1024 --height 1024 \
    --lora style.safetensors:0.8 --trigger sks --expand
argus-darkroom generate "a lighthouse at dusk" --checkpoint flux/flux1-dev-fp8.safetensors \
    --sampler euler --scheduler simple --steps 20 --cfg 1 --guidance 3.5 --width 1024 --height 1024
argus-darkroom serve
argus-darkroom schema --check
argus-darkroom version
```

| Command | Options |
|---|---|
| `generate PROMPT` | **Required:** `--checkpoint`, `--sampler`, `--scheduler`, `--steps`, `--cfg`, `--width`, `--height`. Darkroom does not invent sampling. **Optional:** `--guidance` (Flux; fills the template's `$guidance` slot), `--clip-skip` (1 to 12, default 1), `--seed` (default random, recorded), `--vae`, `--negative`/`-n`, `--lora NAME[:WEIGHT]` and `--trigger WORDS` (both repeatable; with several LoRAs each trigger is `NAME=word,word`), `--expand`, `--policy` (the enforcing policy; default the server's), `--advisory` (repeatable), `--thinking` (`fast`, `fast-slow`, `slow` or `cascade`), `--nsfw-threshold` (default 0.2), `--priority` (the GPU lease class, default `interactive`; see [GPU leases](#gpu-leases-argus-iris)), `--json` (print the whole record instead of a summary) |
| `preflight PROMPT` | The text check alone: `--negative`/`-n`, `--policy`, `--advisory`, `--thinking`, `--trigger-word` (repeatable). Prints the verdicts as JSON |
| `serve` | `--port`/`-p` (default 8106), `--host` (default `127.0.0.1`), `--output-root`, `--allow-nsfw`, `--cors-origin` (repeatable). Each overrides its `ARGUS_DARKROOM_*` variable |
| `schema` | Writes `schema/darkroom-wire.schema.json`, or `--output`/`-o` somewhere else. `--check` exits 1 when the committed file is stale |
| `version` | Prints the version |

The CLI renders text-to-image only. Image-to-image and inpainting (`init_image`, `mask`) are reached over HTTP.

Exit codes for `generate` and `preflight`:

- **`0`:** `generate` released the image (`passed` or `review`), or `preflight`'s verdict was not `refused`.
- **`2`:** anything else (refused, deleted, omitted or failed), **and** a missing or malformed option, which the
  argument parser rejects with the same code. A script that needs to tell these apart should pass `--json` and read
  `outcome`, or look for `Usage:` on stderr.
- **`1`:** a configuration error, such as no `SINGGUARD_URL` or a workflow that cannot load, or a request darkroom
  refuses before running it, such as an unknown policy or a checkpoint with no workflow.

`--expand` has Ollama rewrite the prompt. The expansion replaces your text (trigger words are appended) and is checked
like anything else, so it cannot route around the gate. If Ollama fails, the attempt is a `failed` record, never a
silent fall back to the unexpanded prompt.

## HTTP API

| | |
|---|---|
| `GET /health` | version, whether each backend answers (booleans), `nsfw_allowed`, `sfw_available`, `devmode`, `read_only`, `demo` (true only for `make demo`'s fake backends), age-check status, `minor_exposed` (the rule), `workflows` (names), `generating`, `gpu` as `{coordinator, in_flight, limit}`, and `nudenet_detector` (`640m`, `320n`, or `null` when NudeNet does not say or does not answer) |
| `GET /policies` | `default` (the server's enforcing policy) and `policies`, each as `{name, mode, summary, illegal_rules, enforceable, text}`. `mode` is `sfw` or `nsfw`. `illegal_rules` lists only the rules that make an image illegal, as `{code, name}`. `enforceable` is false for an NSFW policy without `ALLOW_NSFW`, and for an SFW policy without NudeNet. `text` is the policy wording sent to SingGuard (`null` for `default`, which uses SingGuard's own rules) |
| `GET /models` | checkpoints as `{name, family, lora_counts, img2img_lora_counts, inpaint_lora_counts}`, LoRAs and VAEs as `{name}` (`loras`, `vaes`), `workflows` as `{name, family, loras, mode, img2img, slots}` (`mode` is `txt2img`, `img2img` or `inpaint`; `img2img` is true for plain image-to-image only), `default_checkpoint`, plus `samplers` and `schedulers` as ComfyUI offers them (empty lists when ComfyUI does not say) |
| `POST /preflight` | the text check alone. It does not expand: an expansion differs per run, so `expansion_applied` is `false`. An `init_image` is not checked here, only during a generation |
| `POST /generate/stream` | SSE: `preflight`, `input_scan {policy,context,cell}` (image-to-image and inpainting only, one per input cell, before anything is rendered), `queued`, `progress {step,total}`, `scan {policy,context,cell}`, `complete {record}`, `error {detail}`. `X-Argus-Priority` sets the GPU lease class. One at a time and a second gets 409, unless the GPU coordinator is the broker: then it waits for its lease (see [GPU leases](#gpu-leases-argus-iris)) |
| `GET /records`, `GET /record/{id}` | `/records` takes `page`, `page_size`, `outcome` and `mode` |
| `GET /image/{id}` | 404 for a deleted, omitted or refused record |
| `DELETE /record/{id}` | removes the user's own image (and its depth map: `depth` goes back to `null`); the record stays |
| `POST /depth/{id}` | a depth map of the record's stored image; returns the record's new `depth` object. 404 for no such record, 409 when the record has no stored image (deleted, omitted, refused, failed or removed) or the gate is full (it shares the generations' gate: one at a time, or eight with the GPU broker), 502 when ComfyUI fails or no GPU lease is granted. `X-Argus-Priority` sets its lease class. Idempotent: a second call returns the stored map without recomputing. A write: refused cross-site and under `READ_ONLY` |
| `GET /depth/{id}` | the depth map as `image/png`; 404 with the record id when there is none |
| `GET /archive` | streamed zip of every record, stored image (`images/`) and depth map (`depth/<id>.png`) |
| `POST /purge` | `{"confirm": "purge"}`; only with `DEVMODE` |
| `POST /purge/{id}` | the same body: deletes one record and its image; only with `DEVMODE` |

Writes are refused from origins that are not in `CORS_ORIGINS`.

### Depth maps

A depth map is derived from an image darkroom already judged and released, with no new prompt and no new imagery, so it
gets no pre-flight and no scan; the guard for generations is unchanged. The PNG is 8-bit greyscale (`L`) at the image's
size, near bright (255) and far dark (0), stretched min to max per image (Depth Anything's relative inverse depth), with
no metadata. It is stored beside the image as `<id>.depth.png`, and removing or purging the image removes it. The
record's `depth` is `{model: "depth-anything-v2-small", model_license: "Apache-2.0", sha256, width, height, created_at,
workflow, engine_version}` (`sha256` of the stored PNG), or `null`.

The generate and pre-flight body: `user_prompt`, `negative_prompt`, `expand`, `seed`, `sampling`, `checkpoint`, `vae`,
`loras` (`{name, weight, trigger_words}`), `enforcing_policy`, `advisory_policies`, `thinking`, `nsfw_threshold`, and
`init_image` for image-to-image:

| `init_image` field | |
|---|---|
| `data_base64` | PNG, JPEG or WebP bytes, base64. At most 16 MiB decoded and 4096 px on either edge. Anything else is a 400 |
| `denoise` | 0.05 to 1.0, default 0.5: how much of the input the sampler replaces. Out of range is a 422, like any other field |
| `mask_base64` | optional; makes the run inpainting. PNG, JPEG or WebP bytes, base64, with the image's limits, and exactly the input's size once both are upright. White (grey 128 and up) is repainted, black kept. A mask that does not decode, is the wrong size or masks nothing is a 400 |

The input is decoded once, turned upright by its EXIF orientation, made RGB and re-encoded as a PNG with no metadata;
that PNG is what is scanned and what ComfyUI gets. Darkroom does not store it: the record keeps
`request.init_image` (`sha256`, `phash`, `width`, `height` of that PNG, `source_sha256` of the bytes sent, `denoise`)
and `guard.input` (the input's `scans`, `nudenet`, `age`, `outcome` and `reason`).

### Inpainting

With `mask_base64`, only the mask's white region of the input is repainted; every other pixel of the output is the
input's (scaled to the output size). The input is judged exactly as for image-to-image. The mask is not scanned: it is a
region selector with no imagery of its own, and what could be harmful (the input it selects from, and the output) is
judged in full either way. It is cut at 128 into a 1-bit PNG with no metadata, sent to ComfyUI inside the graph like the
input, and never stored. The record keeps `request.init_image.mask` (`sha256` of that PNG, `source_sha256` of the bytes
sent, `masked_fraction`: the share of the input it repaints, to 4 decimals).

Every record under an NSFW policy carries a `guard.nudenet` block (`exposed_score`, `labels`, `threshold`, `blur`,
`detector`, `detector_model`); `blur` is the only place the blur decision lives. `exposed_score` is `null` when NudeNet
could not be reached, and the image is then blurred. `detector` is the NudeNet model that scored the image, as its server
reports it: `640m`, `320n`, or `null` when NudeNet did not answer or its server does not say (the upstream 320n image has
no `/health`). 640m and 320n score the same image differently, so compare scores, and the `threshold` they were judged
against, only within one detector. The default threshold, 0.2, was set before the suite's move to one shared 640m server
(argus-cortex#79) and is re-checked against it there. Each LoRA in `params.loras` keeps the `trigger_words` the request supplied.

## Demo (no GPU)

`demo/run.py` runs the real server and engine against the same fake SingGuard, NudeNet, ComfyUI and Ollama servers the
tests use, so a reviewer can click through every outcome. A marker in the prompt chooses what the fakes say:

```bash
make demo          # http://127.0.0.1:8106, history in ./demo-data
make smoke         # in another shell: 16 prompts, each checked against the outcome it should reach
```

| Marker | Fakes say | Outcome |
|---|---|---|
| none | everything safe | `passed` |
| `[flag]` / `[flag-both]` | the image (or image and prompt) trips rule B | `review` |
| `[unchecked]` | the scan cannot be read | `deleted` (`unchecked`) |
| `[exposed]` | NudeNet reports exposure | SFW: `omitted`; NSFW: `passed`, blurred |
| `[nonude]` | NudeNet is down | SFW: `omitted`; NSFW: `passed`, blurred |
| `[noage]` | MiVOLO has no estimate | `passed` |
| `[minor]` | exposure and an age under 18 | `deleted` (`minor-exposed`) |
| `[illegal]` | the illegal rule fires | `deleted` |
| `[refuse]`, `[refuse-illegal]` | pre-flight flags | `refused` |
| `[preflight-unchecked]` | pre-flight cannot be read | `refused` (`unchecked`) |
| `[fail]` | ComfyUI errors in `KSampler` | `failed` |

`python demo/run.py --help` lists `--host`, `--port`, `--cors-origin`, `--workflow` (by default the whole examples
directory, with fake `sdxl/` and `flux/` checkpoints and two LoRAs; name one file to use it for every checkpoint),
`--latency`, `--step-delay` and `--fresh`.
The demo turns `DEVMODE` and `ALLOW_NSFW` on and uses fake models. Bind it to a non-loopback host only on a network you
trust. No real content is involved; the verdicts are canned.

[argus-safelight](https://github.com/smk762/argus-safelight) is the UI for it: point `NEXT_PUBLIC_DARKROOM_URL` at the
demo.

## Age check (optional)

The age check is an extra signal on top of SingGuard's minors rule, never a replacement for it. SingGuard judges every
image for itself, with or without an estimate: rule A of each adult policy covers anyone who appears to be a minor. So
when the age check is missing, that rule still applies.

The estimate is a tool's reading, and it is never sent to SingGuard. It has one effect of its own, the `minor-exposed`
rule, which deletes the image. Without exposure an estimate is only recorded and shown. `MINOR_EXPOSED` picks how the
rule places exposure:

- `frame` (the default): any estimate under 18 on an image where NudeNet scores an exposed class at 0.2 or more. Where
  the exposure is does not matter, so an adult's exposure beside a clothed minor deletes too.
- `overlap`: argus-curator's original rule. Each exposed NudeNet detection (the five default exposed classes, scored
  0.2 or more) is placed by its box against the person boxes, or the face boxes when no person was detected. It
  deletes when it overlaps a box estimated under 18, or overlaps no box at all; one overlapping only adults' boxes does
  not. It fails closed: a face under 18 whose body was not found makes any exposure count, and so does an exposed score
  with no exposed detection box to place.
  Boxes are trusted only from a NudeNet server that names its detector on `/health`; the upstream 320n image does
  not (and offsets its boxes), so with it the image is judged by `frame`.

Both ignore the user's NudeNet threshold. The record's `age.minor_exposed_rule` says which rule decided, and
`age.people` keeps every person box with the face it was matched to (`face_index`), and `nudenet.detections` keeps
NudeNet's boxes (label, score, box; never pixels), so an `overlap` decision can be recomputed from the record. A
matched person that cannot be placed (a malformed box, an unknown face) is dropped from `people`, which under
`overlap` fails closed. `/health` reports the rule as `minor_exposed`.
A record written before the setting existed has none of these fields and was decided by `frame`.

Set `AGE_URL` to a curator 0.10+ that serves `POST /faces?body=true` (InsightFace + MiVOLO, a body crop per face, and
unmatched people). The Docker image is meant to be used this way. A failed `people_check` is treated as age unavailable,
not as "no one found", and so is an unmatched person with no estimate. An unavailable age check never deletes on its
own: the record says `age: null` and the image is judged by SingGuard and NudeNet.

```bash
uv pip install "argus-darkroom[age]"   # in-process fallback when AGE_URL is empty
```

The extra runs curator's face pipeline in this process and needs the MiVOLO ONNX file (`argus-curator mivolo-convert`).
Without a URL or the extra, records carry `age: null` and `/health` says why.

## Wire schema

Records are versioned (`record_version`) and the schema is committed at
[`schema/darkroom-wire.schema.json`](schema/darkroom-wire.schema.json) for consumers to generate code from.
`argus-darkroom schema` rewrites it; `schema --check` fails if it is stale. Change a model, regenerate, commit both.

## Develop

```bash
make install   # venv + editable install with the "dev" extras
make test
make lint
argus-darkroom schema --check
```

Tests run against fake SingGuard, NudeNet, ComfyUI and Ollama servers. No real sexual, violent or illegal content goes in
the repo or its tests: the illegal-to-deleted path is driven by a fake verdict.
[`scripts/preflight_eval.py`](scripts/preflight_eval.py) scores the pre-flight framing against a real SingGuard server on
the labelled prompts in `eval/`; run it by hand, not in CI.

## CI / Release

- **CI** runs via the shared [`argus-ci`](https://github.com/smk762/argus-ci) reusable workflow, plus a `schema --check`
  job.
- **Release** publishes to PyPI (OIDC trusted publishing) and GHCR on `v*` tags, then creates the GitHub Release.
- Versioning is derived from git tags via `hatch-vcs`: tag `vX.Y.Z` to cut a release.
- Release notes are the version's section of `CHANGELOG.md`. Add a `## [X.Y.Z]` section before tagging: without one,
  the build fails and nothing is published.

This repo was scaffolded from [`argus-pkg-template`](https://github.com/smk762/argus-pkg-template).
Run `copier update` to pull template changes (CI, release, tooling).
