stylegan-js 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +21 -0
  3. package/PROVENANCE.json +16 -0
  4. package/README.md +241 -2
  5. package/THIRD_PARTY_NOTICES +76 -0
  6. package/dist/blend/blend.d.ts +29 -0
  7. package/dist/blend/blend.js +76 -0
  8. package/dist/blend/recipe.d.ts +29 -0
  9. package/dist/blend/recipe.js +66 -0
  10. package/dist/contracts/canonical-json.d.ts +8 -0
  11. package/dist/contracts/canonical-json.js +34 -0
  12. package/dist/contracts/capability.d.ts +91 -0
  13. package/dist/contracts/capability.js +59 -0
  14. package/dist/contracts/crop-policy.d.ts +126 -0
  15. package/dist/contracts/crop-policy.js +310 -0
  16. package/dist/contracts/descriptor.d.ts +186 -0
  17. package/dist/contracts/descriptor.js +270 -0
  18. package/dist/contracts/numerics.d.ts +48 -0
  19. package/dist/contracts/numerics.js +83 -0
  20. package/dist/contracts/operations.d.ts +242 -0
  21. package/dist/contracts/operations.js +92 -0
  22. package/dist/contracts/photo-admission.d.ts +35 -0
  23. package/dist/contracts/photo-admission.js +72 -0
  24. package/dist/contracts/recovery-metadata.d.ts +89 -0
  25. package/dist/contracts/recovery-metadata.js +371 -0
  26. package/dist/contracts/sha256.d.ts +4 -0
  27. package/dist/contracts/sha256.js +77 -0
  28. package/dist/contracts/timing.d.ts +25 -0
  29. package/dist/contracts/timing.js +4 -0
  30. package/dist/contracts/worker-messages.d.ts +88 -0
  31. package/dist/contracts/worker-messages.js +266 -0
  32. package/dist/engine/adapters/cpu.d.ts +17 -0
  33. package/dist/engine/adapters/cpu.js +69 -0
  34. package/dist/engine/adapters/direct-shaders.d.ts +21 -0
  35. package/dist/engine/adapters/direct-shaders.js +191 -0
  36. package/dist/engine/adapters/direct-webgpu.d.ts +26 -0
  37. package/dist/engine/adapters/direct-webgpu.js +341 -0
  38. package/dist/engine/adapters/fused-resample.d.ts +26 -0
  39. package/dist/engine/adapters/fused-resample.js +86 -0
  40. package/dist/engine/adapters/generator.d.ts +122 -0
  41. package/dist/engine/adapters/generator.js +384 -0
  42. package/dist/engine/adapters/gpu-constants.d.ts +10 -0
  43. package/dist/engine/adapters/gpu-constants.js +10 -0
  44. package/dist/engine/adapters/ort-webgpu.d.ts +39 -0
  45. package/dist/engine/adapters/ort-webgpu.js +251 -0
  46. package/dist/engine/adapters/ort.d.ts +70 -0
  47. package/dist/engine/adapters/ort.js +58 -0
  48. package/dist/engine/canary.d.ts +95 -0
  49. package/dist/engine/canary.js +203 -0
  50. package/dist/engine/encode.d.ts +125 -0
  51. package/dist/engine/encode.js +358 -0
  52. package/dist/engine/engine.d.ts +59 -0
  53. package/dist/engine/engine.js +257 -0
  54. package/dist/engine/identity.d.ts +76 -0
  55. package/dist/engine/identity.js +188 -0
  56. package/dist/engine/index.d.ts +15 -0
  57. package/dist/engine/index.js +17 -0
  58. package/dist/engine/model.d.ts +41 -0
  59. package/dist/engine/model.js +80 -0
  60. package/dist/engine/reader.d.ts +40 -0
  61. package/dist/engine/reader.js +31 -0
  62. package/dist/engine/reference-png.d.ts +9 -0
  63. package/dist/engine/reference-png.js +137 -0
  64. package/dist/engine/routes.d.ts +109 -0
  65. package/dist/engine/routes.js +163 -0
  66. package/dist/engine/webgpu.d.ts +2 -0
  67. package/dist/engine/webgpu.js +5 -0
  68. package/dist/engine/worker.d.ts +34 -0
  69. package/dist/engine/worker.js +154 -0
  70. package/dist/index.d.ts +20 -0
  71. package/dist/index.js +22 -0
  72. package/dist/media/envelope.d.ts +70 -0
  73. package/dist/media/envelope.js +522 -0
  74. package/dist/media/inspect-still.d.ts +39 -0
  75. package/dist/media/inspect-still.js +96 -0
  76. package/dist/media/mp4-project.d.ts +136 -0
  77. package/dist/media/mp4-project.js +550 -0
  78. package/dist/media/recovery-v3.d.ts +86 -0
  79. package/dist/media/recovery-v3.js +184 -0
  80. package/dist/media/webp-lossless.d.ts +7 -0
  81. package/dist/media/webp-lossless.js +400 -0
  82. package/dist/morph/infill.d.ts +15 -0
  83. package/dist/morph/infill.js +42 -0
  84. package/dist/morph/latent-path.d.ts +62 -0
  85. package/dist/morph/latent-path.js +331 -0
  86. package/dist/morph/render.d.ts +111 -0
  87. package/dist/morph/render.js +275 -0
  88. package/package.json +51 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ All notable changes to `stylegan-js` are recorded here. Versions follow [semantic versioning](https://semver.org/);
4
+ while the major version is 0, a minor release may break the API and a patch release does not. A published version
5
+ is never changed: a fix is a new version. Each tarball carries `PROVENANCE.json`, naming the commit and the digest
6
+ of the `dist/` it was built from ([releasing](../../docs/packages/RELEASING.md)).
7
+
8
+ ## 0.1.0 (not yet published)
9
+
10
+ First release.
11
+
12
+ - StyleGAN2 mapping and synthesis on the CPU (ONNX Runtime WASM) and WebGPU (ONNX Runtime WebGPU and direct WGSL kernels), admitted only after the model's own canaries pass.
13
+ - The e4e photo encoder for the FFHQ generator.
14
+ - Morph paths, frame ordering and `renderMorph`; blends with clamped weights.
15
+ - PNG and lossless WebP stills that carry the exact W+ latent and generator identity (recovery schema 3), and readers for schemas 1 to 3.
16
+ - Model descriptors for FFHQ config-F 1024 and AFHQ cat 512.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chris Dilger
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,16 @@
1
+ {
2
+ "schema": "facemorph.package-provenance/2",
3
+ "name": "stylegan-js",
4
+ "version": "0.1.0",
5
+ "sourceCommit": "59a1544aaca0cf1fedd5bc96883ffeec76e49d60",
6
+ "sourceTreeClean": true,
7
+ "sourceIdentity": "ddbb7a0f3a3e4917d230ecf9bd510e130eb8430b3c8fd3d9dd4e80776b1a6ed9",
8
+ "distSha256": "a7ed40b3483f0b15669941a292f9f6581d26151b8b2ced02df40ee08015c7bdc",
9
+ "distFiles": 82,
10
+ "build": {
11
+ "repository": "facemorph-me/facemorph.me",
12
+ "runId": "46234816541",
13
+ "runAttempt": "1",
14
+ "workflow": "packages"
15
+ }
16
+ }
package/README.md CHANGED
@@ -1,3 +1,242 @@
1
- # Temporary Holding Version
1
+ # stylegan-js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ StyleGAN2 mapping, synthesis and e4e photo encoding in the browser, with morphs, blends and saved files that
4
+ reopen exactly. It runs a converted StyleGAN2 generator in a web page or worker on the CPU (ONNX Runtime WASM) or
5
+ on WebGPU, from model bytes that you host and it verifies.
6
+
7
+ Using a new dataset means acquiring or training a compatible StyleGAN2 checkpoint first; this project does not train models.
8
+
9
+ What it is not:
10
+ - **Not a server or Node inference library.** The documented deployment is a browser app with static model assets.
11
+ Node, headless and server inference are unsupported: no provider for them has its own evidence.
12
+ - **Not bundled with weights.** You host converted model files (see [Models](#models)); this package never fetches
13
+ anything by itself.
14
+ - **Not a trainer or converter.** Checkpoints are converted by `model-conv` (see
15
+ [compatibility](../model-conv/docs/compatibility.md)).
16
+
17
+ Entry points: `.` (contracts, media, blend, morph), `./engine` (the engine core: loading, canaries, mapping,
18
+ synthesis, the e4e encoder, worker helpers) and `./engine/webgpu` (just the two WebGPU generator loaders, so a worker
19
+ can `import()` them only when it takes a WebGPU route). Every export is listed in the [API reference](docs/api.md).
20
+ See also [capabilities](docs/capabilities.md) and [saved file formats](docs/formats.md).
21
+
22
+ ## Install
23
+
24
+ <!-- docs-test: install -->
25
+ ```sh
26
+ npm install stylegan-js
27
+ ```
28
+
29
+ The package is ESM only, with `.d.ts` declarations, no runtime dependencies and `"sideEffects": false`. Importing
30
+ it does no I/O and touches no globals.
31
+
32
+ ## Quick start: load a model and make a face
33
+
34
+ [`examples/caller-loaded`](examples/caller-loaded) is the complete, tested quick start: a page that loads a model
35
+ capability from a runtime directory you serve, maps two seeds, synthesizes them and their W+ midpoint, shows
36
+ progress and Abort, and disposes. Its `test/engine/caller-loaded-example.test.ts` runs it from the packed tarball in
37
+ Chromium on the CPU (and on WebGPU where a hardware adapter exists) and checks every face against the runtime's
38
+ references.
39
+
40
+ The order of calls is always the same:
41
+
42
+ 1. **Read bytes only through a verifying reader.** `createVerifyingReader` in the example checks each chunk's size
43
+ and SHA-256 before the engine sees it. With `browser-model-manager`, its verified local reader takes
44
+ that place.
45
+ 2. **Load a generator for one route**: `loadCpuGenerator` (ONNX Runtime WASM), or `loadOrtWebGpuGenerator` /
46
+ `loadDirectWebGpuGenerator` from `./engine/webgpu`.
47
+ 3. **Admit it**: `createEngine({ generator, qualification })` and `engine.admit()` run the model's product canaries
48
+ against its own references before any user work. A route that fails them is not used.
49
+ 4. **Map and synthesize**: `engine.map` turns a seed's z into a W+ latent and `engine.synthesize` turns a W+ latent
50
+ into RGBA pixels.
51
+ 5. **Dispose** when done; it releases sessions, GPU devices and buffers.
52
+
53
+ Constructing the engine and reading its status make no request. Every model read is one your reader performs.
54
+
55
+ ## Browsers, providers and build targets
56
+
57
+ | Route | Engine | Qualified on |
58
+ | --- | --- | --- |
59
+ | CPU | `ort-wasm` | Chromium, Firefox and WebKit (Linux, Playwright builds) |
60
+ | WebGPU | `ort-webgpu` (ONNX Runtime WebGPU EP) | Desktop Chromium with an NVIDIA adapter |
61
+ | WebGPU | `direct-webgpu` (WGSL kernels) | Desktop Chromium with an NVIDIA adapter, within `DIRECT_LIMITS` (`directSupported`) |
62
+
63
+ Everything else is **unqualified**; [capabilities](docs/capabilities.md) lists each cell and its evidence. Falling
64
+ back to the CPU never counts as a WebGPU pass.
65
+
66
+ - **Threads and COOP/COEP.** The CPU route uses ONNX Runtime threads only when the page is cross-origin isolated
67
+ (`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`, so
68
+ `SharedArrayBuffer` exists). Without isolation it runs single-threaded, correctly but more slowly; `cpuThreads`
69
+ reports which.
70
+ - **WASM paths.** There is no `wasmPaths` setting. ONNX Runtime's JS and WASM are model assets named in your
71
+ runtime manifest; they are read through your verifying reader and imported from those verified bytes.
72
+ - **Workers.** Run the engine in a dedicated worker with `serveEngine(port, engine)` and talk to it from the page
73
+ with `connectEngine(port)`. Bundlers need nothing special: the package has no `new Worker` of its own and no
74
+ asset URLs. A CPU-only worker should import the WebGPU loaders with `import('stylegan-js/engine/webgpu')`
75
+ so they are bundled into a separate chunk.
76
+
77
+ ## Resources, cancellation, errors and progress
78
+
79
+ - **Ownership.** Whoever loads a generator owns it and calls `dispose()` once. A disposed engine refuses work with a
80
+ typed error.
81
+ - **Abort.** Loads and operations take an `AbortSignal`. An aborted read stops at once; a late result after abort is
82
+ discarded, never delivered.
83
+ - **Errors.** Failures are typed values, never strings: `engineError(error)` gives a clone-safe
84
+ `{ code, message, cause }` (for example a missing or corrupt asset, an unavailable provider, a lost device).
85
+ - **Progress.** Loads report each asset read through the reader; operations accept a `StageTimingHook` that reports
86
+ each stage with its timing.
87
+ - **First use and warm use.** The first load on a device reads the whole route's model files (about 150 MB for the
88
+ FFHQ CPU route) and runs the admission canaries. Later loads read verified bytes from local storage when a model
89
+ manager caches them, and a warm face costs only mapping and synthesis.
90
+
91
+ ## Models
92
+
93
+ A model is described by a `ModelDescriptor`: its identity (model and noise digests), latent shape, output shape,
94
+ noise planes, truncation and conditioning. Latents are W+ tensors of the descriptor's `[layers, width]`.
95
+
96
+ Supported model shapes (the qualified rows of the [model-conv compatibility table](../model-conv/docs/compatibility.md)):
97
+
98
+ <!-- docs-test: supported-shapes -->
99
+ | Model | Resolution / channels | Z / W / W+ layers |
100
+ | --- | --- | --- |
101
+ | FFHQ config-F (`FFHQ_1024_DESCRIPTOR`) | 1024 / 3 | 512 / 512 / 18 |
102
+ | AFHQ cat (`AFHQ_CAT_512_DESCRIPTOR`) | 512 / 3 | 512 / 512 / 16 |
103
+ <!-- docs-test: end -->
104
+
105
+ Acquire checkpoints yourself from NVIDIA under their terms: StyleGAN2 config-F
106
+ ([NVlabs/stylegan2](https://github.com/NVlabs/stylegan2)) and StyleGAN2-ADA
107
+ ([NVlabs/stylegan2-ada-pytorch](https://github.com/NVlabs/stylegan2-ada-pytorch)). The compatibility table names
108
+ the exact files and digests that were converted and verified. No weights are bundled.
109
+
110
+ ### Numerical qualification
111
+
112
+ A route is admitted only when the model's product canaries pass the frozen tolerances against references made
113
+ independently of this package: decoded RGB within 1/255 per channel and sampled raw floats within 0.002 of the
114
+ reference. The e4e photo encoder must reproduce the reference W+ within 0.0001. Other models declare their own
115
+ tolerance in their descriptor's conversion record, fixed before their verification run (AFHQ cat: raw 1e-3, RGB 1).
116
+
117
+ ### Photo encoding
118
+
119
+ Photo-to-latent inversion needs a separately trained encoder compatible with the generator. The shipped FFHQ e4e encoder works only for the FFHQ face generator; it is not a generic encoder. Non-face generation and morphs load no face detector and no e4e encoder.
120
+
121
+ ### Non-face models
122
+
123
+ Non-face support is **unqualified** until the joint non-face proof passes: converted AFHQ cat loaded through
124
+ `browser-model-manager`, mapped, synthesized, morphed and saved from the packed packages (bead
125
+ `fm-tqub`). This package is extracted from a face app; that is not generic dataset support.
126
+
127
+ [`examples/non-face`](examples/non-face) loads converted AFHQ cat on the CPU, manager-loaded or caller-loaded, maps
128
+ and synthesizes three seeds, morphs through them with `renderMorph`, saves and reopens PNG and lossless WebP, and
129
+ shows a latent from another checkpoint refused for combination. Its test (`test/engine/nonface-example.test.ts`) runs
130
+ its README's commands from the packed tarballs and checks that no request names a face detector or the e4e encoder.
131
+
132
+ ## Morphs and blends
133
+
134
+ `createLatentPath` interpolates W+ latents along the path a morph takes, `infillFrames` orders frames so a preview
135
+ fills in coarse-to-fine, and `renderMorph` drives a morph end to end through a frame source you supply (your
136
+ engine's `synthesize`), a writer and an optional frame store. `blend` mixes W+ latents of one model with clamped
137
+ weights. All of them refuse latents whose shape is not the descriptor's.
138
+
139
+ ## Saved files and recovery metadata
140
+
141
+ Saved stills carry the exact W+ latent and the identity of the generator that made it, so a file reopens as the
142
+ same face:
143
+
144
+ <!-- docs-test: run examples/readme/save-and-reopen.ts -->
145
+ ```ts
146
+ import {
147
+ checkCombinable,
148
+ encodeLosslessWebp,
149
+ encodePng,
150
+ FFHQ_1024_DESCRIPTOR,
151
+ latentDigest,
152
+ readRecovery,
153
+ type LatentTensor,
154
+ type RgbaPixels,
155
+ } from 'stylegan-js';
156
+
157
+ // In an app these are a face's W+ latent and the RGBA pixels `synthesize` returned for it.
158
+ const d = FFHQ_1024_DESCRIPTOR;
159
+ const [, , height, width] = d.output.shape;
160
+ const { modelSha256, noiseSha256 } = d.identity;
161
+ const latent: LatentTensor = {
162
+ space: 'w-plus',
163
+ shape: [d.latent.layers, d.latent.width],
164
+ values: Float32Array.from({ length: d.latent.layers * d.latent.width }, (_, i) => Math.sin(i)),
165
+ };
166
+ const pixels: RgbaPixels = {
167
+ width,
168
+ height,
169
+ rgba: new Uint8Array(width * height * 4).map((_, i) => (i % 4 === 3 ? 255 : i % 251)),
170
+ };
171
+
172
+ // Save: an exact PNG and a lossless WebP, each carrying the latent and the generator that made it.
173
+ const recovery = {
174
+ descriptor: d,
175
+ generationKind: 'latent' as const,
176
+ generationSha256: latentDigest(latent),
177
+ provenance: { modelSha256, noiseSha256 },
178
+ latent,
179
+ };
180
+ const png = await encodePng(pixels, recovery);
181
+ const webp = encodeLosslessWebp(pixels, recovery);
182
+
183
+ // Reopen: the latent and the model identity come back exactly. Nothing here fetches anything.
184
+ for (const file of [png, webp]) {
185
+ const read = readRecovery(file);
186
+ if (read.kind !== 'parsed') throw new Error(`not reopenable: ${read.kind}`);
187
+ const { recovered } = read;
188
+ if (recovered.schemaVersion !== 3) throw new Error('expected schema 3');
189
+ if (recovered.provenance.modelSha256 !== modelSha256) throw new Error('model identity changed');
190
+ if (!recovered.latent.values.every((v, i) => v === latent.values[i]))
191
+ throw new Error('latent changed');
192
+ }
193
+
194
+ // Latents of two different checkpoints never combine, even when their shapes are equal.
195
+ const other = { modelSha256: 'f'.repeat(64), noiseSha256, latent };
196
+ const mixed = checkCombinable(d, [{ modelSha256, noiseSha256, latent }, other]);
197
+ if (mixed.ok || mixed.error.code !== 'mixed-model') throw new Error('mixed models must be refused');
198
+
199
+ console.log(`saved and reopened: PNG ${png.length} bytes, lossless WebP ${webp.length} bytes`);
200
+ ```
201
+
202
+ Recovery semantics: stills are written as schema 3 (dynamic shape: the generator record and the W+ shape come from the model descriptor). Schema-1 PNG and schema-2 PNG and WebP files are still read. Combining equal-shaped latents from different checkpoints is refused with a typed error (`mixed-model`). A file from a model you do not have stays viewable as media, without editable inference, and URLs found in its metadata are never followed.
203
+
204
+ `encodePng` and `encodeLosslessWebp` are lossless library helpers; they do not change the FaceMorph app's lossy WebP
205
+ quality 0.8 policy. The exact model, latent and provenance values in a file are separate from its decoded pixel
206
+ quality. [Saved file formats](docs/formats.md) gives every format, limit and damage case.
207
+
208
+ ## Troubleshooting
209
+
210
+ - **The CPU route is slow.** Check `cpuThreads`: without cross-origin isolation the CPU route is single-threaded.
211
+ - **WebGPU is not chosen.** The route is admitted only after its canaries pass on this adapter; an unsupported
212
+ adapter or failed canary leaves the CPU route, and that is reported, not hidden.
213
+ - **A load fails with a cache-miss or corrupt-asset error.** Your reader's bytes did not match the manifest's size
214
+ or SHA-256; the model host is serving different files from the ones the manifest names.
215
+ - **A saved file does not reopen.** `readRecovery` says why: `missing`, `damaged` (with the reason) or
216
+ `incompatible-schema` (with the version the file claims).
217
+
218
+ ## Related packages
219
+
220
+ - [browser-model-manager](../browser-model-manager/README.md) asks the person before any download, then acquires,
221
+ verifies and caches the model files; the engine loads them through its verified local reader.
222
+ - [cloudflare-model-host](../cloudflare-model-host/README.md) stages converted models for any HTTPS static host, with
223
+ an optional Cloudflare guide.
224
+ - [model-conv](../model-conv/README.md) converts a trusted StyleGAN2 checkpoint into the files this package loads. The
225
+ [compatibility table](../model-conv/docs/compatibility.md) lists the checkpoints that are qualified.
226
+
227
+ ## Licence and model weights
228
+
229
+ The code is MIT licensed (`LICENSE`; bundled third-party code in `THIRD_PARTY_NOTICES`). **The model weights are
230
+ not included.** A model host supplies them, and they come under their own terms, separate from this package's
231
+ licence and limited to non-commercial use:
232
+
233
+ <!-- model-terms:start -->
234
+ - NVIDIA StyleGAN2 licence: [upstream text](https://github.com/NVlabs/stylegan2/blob/master/LICENSE.txt); served beside the weights as `notices/NVIDIA-StyleGAN2-NC.txt`
235
+ - NVIDIA StyleGAN2-ADA licence: [upstream text](https://github.com/NVlabs/stylegan2-ada-pytorch/blob/main/LICENSE.txt); served beside the weights as `notices/NVIDIA-StyleGAN2-ADA.txt`
236
+ - FFHQ dataset terms: [upstream text](https://github.com/NVlabs/ffhq-dataset#licenses); served beside the weights as `notices/FFHQ-terms.txt`
237
+ - e4e MIT licence: [upstream text](https://github.com/omertov/encoder4editing/blob/main/LICENSE); served beside the weights as `notices/e4e-MIT.txt`
238
+ - dlib landmark model notice: [upstream text](https://www.dlib.net/face_landmark_detection_ex.cpp.html); served beside the weights as `notices/index.html#dlib-landmarks`
239
+ <!-- model-terms:end -->
240
+
241
+ A host publishes these texts beside the weights, under `notices/` next to the runtime manifest, and the manifest's
242
+ `distribution.notices` points at their index.
@@ -0,0 +1,76 @@
1
+ stylegan-js bundles no third-party packages. Its emitted JavaScript has no runtime dependencies; the parts
2
+ noted as ported in the sources come from FaceMorph's own earlier application, under this package's licence.
3
+
4
+ ONNX Runtime Web (MIT, Microsoft) is not part of this package. The ORT routes import the runtime from bytes the
5
+ caller supplies (normally verified by browser-model-manager from a model manifest), so its licence travels
6
+ with those bytes. Model weights are not part of this package either; their usage and redistribution terms are recorded
7
+ per model in the docs.
8
+
9
+ The seed and text inputs use NumPy's legacy RandomState generator (MT19937 with the polar Gaussian), reimplemented in
10
+ src/engine/identity.ts so a seed gives the same face as NumPy. It is not recorded whether that implementation was
11
+ translated from NumPy or from the reference mt19937ar.c, so both notices are reproduced here.
12
+
13
+ --- MT19937 (mt19937ar.c) ---
14
+
15
+ Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
16
+ All rights reserved.
17
+
18
+ Redistribution and use in source and binary forms, with or without
19
+ modification, are permitted provided that the following conditions
20
+ are met:
21
+
22
+ 1. Redistributions of source code must retain the above copyright
23
+ notice, this list of conditions and the following disclaimer.
24
+
25
+ 2. Redistributions in binary form must reproduce the above copyright
26
+ notice, this list of conditions and the following disclaimer in the
27
+ documentation and/or other materials provided with the distribution.
28
+
29
+ 3. The names of its contributors may not be used to endorse or promote
30
+ products derived from this software without specific prior written
31
+ permission.
32
+
33
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
34
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
35
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
36
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
37
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
38
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
39
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
40
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
41
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
42
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
43
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44
+
45
+ --- NumPy ---
46
+
47
+ Copyright (c) 2005-2025, NumPy Developers.
48
+ All rights reserved.
49
+
50
+ Redistribution and use in source and binary forms, with or without
51
+ modification, are permitted provided that the following conditions are
52
+ met:
53
+
54
+ * Redistributions of source code must retain the above copyright
55
+ notice, this list of conditions and the following disclaimer.
56
+
57
+ * Redistributions in binary form must reproduce the above
58
+ copyright notice, this list of conditions and the following
59
+ disclaimer in the documentation and/or other materials provided
60
+ with the distribution.
61
+
62
+ * Neither the name of the NumPy Developers nor the names of any
63
+ contributors may be used to endorse or promote products derived
64
+ from this software without specific prior written permission.
65
+
66
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
67
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
68
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
69
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
70
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
71
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
72
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
73
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
74
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
75
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
76
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,29 @@
1
+ import { type ModelDescriptor, type Result } from '../contracts/descriptor.ts';
2
+ import type { LatentTensor } from '../contracts/operations.ts';
3
+ export declare const BLEND_WEIGHT_MIN = -2;
4
+ export declare const BLEND_WEIGHT_MAX = 2;
5
+ export type BlendErrorCode = 'no-slots' | 'weight-count' | 'weight-not-finite' | 'not-w-plus' | 'shape-mismatch';
6
+ export interface BlendError {
7
+ readonly code: BlendErrorCode;
8
+ /** The offending slot, when one is. */
9
+ readonly slot?: number;
10
+ readonly message: string;
11
+ }
12
+ export interface BlendResult {
13
+ readonly latent: LatentTensor;
14
+ /** The weights as used, after clamping. */
15
+ readonly weights: readonly number[];
16
+ /** Their sum, which the view shows (the blend is not normalised by it). */
17
+ readonly weightSum: number;
18
+ /** SHA-256 over the model, each slot's latent digest and its clamped weight, in slot order. */
19
+ readonly cacheKey: string;
20
+ }
21
+ /** A weight clamped to [-2, 2], as the API's `max(-2.0, min(2.0, amount))`. */
22
+ export declare const clampWeight: (w: number) => number;
23
+ /** SHA-256 of a latent's little-endian float32 bytes. */
24
+ export declare function latentDigest(latent: LatentTensor): string;
25
+ /**
26
+ * Blends W+ latents of one model: sum(clamp(w_k) * latent_k). Refuses no slots, a weight count that differs from
27
+ * the slot count, a non-finite weight, a non-W+ latent and a latent whose shape is not the descriptor's.
28
+ */
29
+ export declare function blend(descriptor: ModelDescriptor, latents: readonly LatentTensor[], weights: readonly number[]): Result<BlendResult, BlendError>;
@@ -0,0 +1,76 @@
1
+ // Weighted face blend (fm-mtax, plan: compute.blend): the retired API's `num_multi` arithmetic on W+ latents,
2
+ // sum(weight_k * W+_k) with each weight clamped to [-2, 2] and not normalised, ready for one synthesis. It matches
3
+ // classic LatentByMultiLerp (the legacy Python server) on dlatent inputs; the API's Z-space sums for word
4
+ // and seed slots are deliberately not matched, since the app holds every face as W+. Pure arithmetic, shaped by
5
+ // the model descriptor (no hard-coded 18 x 512), with any number of slots from 1. Retained-input memory is the
6
+ // caller's admission check against the byte budgets, not a slot count here.
7
+ import { canonicalJson } from '../contracts/canonical-json.js';
8
+ import { latentFitsDescriptor, } from '../contracts/descriptor.js';
9
+ import { sha256Hex, utf8Bytes } from '../contracts/sha256.js';
10
+ export const BLEND_WEIGHT_MIN = -2;
11
+ export const BLEND_WEIGHT_MAX = 2;
12
+ /** A weight clamped to [-2, 2], as the API's `max(-2.0, min(2.0, amount))`. */
13
+ export const clampWeight = (w) => Math.max(BLEND_WEIGHT_MIN, Math.min(BLEND_WEIGHT_MAX, w));
14
+ /** SHA-256 of a latent's little-endian float32 bytes. */
15
+ export function latentDigest(latent) {
16
+ const v = latent.values;
17
+ const bytes = new Uint8Array(v.length * 4);
18
+ const view = new DataView(bytes.buffer);
19
+ for (let i = 0; i < v.length; i++)
20
+ view.setFloat32(i * 4, v[i], true);
21
+ return sha256Hex(bytes);
22
+ }
23
+ const fail = (code, message, slot) => ({
24
+ ok: false,
25
+ error: slot === undefined ? { code, message } : { code, slot, message },
26
+ });
27
+ /**
28
+ * Blends W+ latents of one model: sum(clamp(w_k) * latent_k). Refuses no slots, a weight count that differs from
29
+ * the slot count, a non-finite weight, a non-W+ latent and a latent whose shape is not the descriptor's.
30
+ */
31
+ export function blend(descriptor, latents, weights) {
32
+ if (latents.length === 0)
33
+ return fail('no-slots', 'A blend needs at least one face.');
34
+ if (weights.length !== latents.length)
35
+ return fail('weight-count', 'Give one weight per face.');
36
+ const clamped = [];
37
+ for (const [k, w] of weights.entries()) {
38
+ if (!Number.isFinite(w))
39
+ return fail('weight-not-finite', 'Each weight must be a number.', k);
40
+ clamped.push(clampWeight(w));
41
+ }
42
+ for (const [k, l] of latents.entries()) {
43
+ if (l.space !== 'w-plus' || !(l.values instanceof Float32Array))
44
+ return fail('not-w-plus', 'Each face must be a W+ latent; map Z first.', k);
45
+ if (!latentFitsDescriptor(l, descriptor))
46
+ return fail('shape-mismatch', `Each face must be ${descriptor.latent.layers} x ${descriptor.latent.width} W+.`, k);
47
+ }
48
+ const n = descriptor.latent.layers * descriptor.latent.width;
49
+ // Accumulate in float64, then store float32, as one weighted sum over the slots.
50
+ const sum = new Float64Array(n);
51
+ for (const [k, l] of latents.entries()) {
52
+ const w = clamped[k];
53
+ const v = l.values;
54
+ for (let i = 0; i < n; i++)
55
+ sum[i] = sum[i] + w * v[i];
56
+ }
57
+ const values = Float32Array.from(sum);
58
+ const cacheKey = sha256Hex(utf8Bytes(canonicalJson({
59
+ kind: 'blend-v1',
60
+ model: descriptor.identity.modelSha256,
61
+ slots: latents.map((l, k) => ({ latent: latentDigest(l), weight: clamped[k] })),
62
+ })));
63
+ return {
64
+ ok: true,
65
+ value: {
66
+ latent: {
67
+ space: 'w-plus',
68
+ shape: [descriptor.latent.layers, descriptor.latent.width],
69
+ values,
70
+ },
71
+ weights: clamped,
72
+ weightSum: clamped.reduce((a, b) => a + b, 0),
73
+ cacheKey,
74
+ },
75
+ };
76
+ }
@@ -0,0 +1,29 @@
1
+ import type { ModelDescriptor, Result } from '../contracts/descriptor.ts';
2
+ import type { LatentTensor } from '../contracts/operations.ts';
3
+ import { type BlendRecipe, type BlendSlotKind } from '../media/recovery-v3.ts';
4
+ import { type BlendError, type BlendResult } from './blend.ts';
5
+ /** SHA-256 over the model and each slot's latent digest and weight, in slot order (blend()'s cacheKey). */
6
+ export declare function blendRecipeDigest(modelSha256: string, recipe: BlendRecipe): string;
7
+ export interface BlendSlotInput {
8
+ readonly kind: BlendSlotKind;
9
+ readonly latent: LatentTensor;
10
+ }
11
+ export interface BlendWithRecipe {
12
+ readonly result: BlendResult;
13
+ readonly recipe: BlendRecipe;
14
+ /** The saved still's generationSha256: the recipe digest (equal to result.cacheKey). */
15
+ readonly generationSha256: string;
16
+ }
17
+ /** blend() plus the recipe a saved blend carries. Refuses an unknown slot kind and an oversized recipe. */
18
+ export declare function blendWithRecipe(descriptor: ModelDescriptor, slots: readonly BlendSlotInput[], weights: readonly number[]): Result<BlendWithRecipe, BlendError>;
19
+ /**
20
+ * What a blend contributes to its export identity (apps/web contracts exportIdentity): ordered inputs naming
21
+ * each slot's kind, latent digest and weight, so blends differing in any weight get different identities,
22
+ * and the filename label `blend-<n>-faces`.
23
+ */
24
+ export declare function blendExportInputs(recipe: BlendRecipe): {
25
+ readonly orderedInputs: readonly string[];
26
+ readonly label: string;
27
+ };
28
+ /** The recipe slots whose latent digest matches `latent`, for restoring weights in the blend view. */
29
+ export declare function recipeSlotsFor(recipe: BlendRecipe, latent: LatentTensor): readonly number[];
@@ -0,0 +1,66 @@
1
+ // The weighted-blend recipe saved with a blend (fm-fzzd, PLAN.md "Weighted face blend (advanced mode)"): per
2
+ // slot, its kind (word, seed, name or photo), the SHA-256 of its W+ latent and its weight as used. Typed words,
3
+ // seeds and file names are never part of it: a slot is identified only by its latent digest, so the blend view
4
+ // can restore the weight of a slot whose latent matches. The recipe digest is blend()'s cacheKey, so a saved
5
+ // blend's generation identity and the engine's cache key are one value.
6
+ import { canonicalJson } from '../contracts/canonical-json.js';
7
+ import { sha256Hex, utf8Bytes } from '../contracts/sha256.js';
8
+ import { BLEND_RECIPE_MAX_SLOTS, BLEND_SLOT_KINDS, } from '../media/recovery-v3.js';
9
+ import { blend, latentDigest } from './blend.js';
10
+ /** SHA-256 over the model and each slot's latent digest and weight, in slot order (blend()'s cacheKey). */
11
+ export function blendRecipeDigest(modelSha256, recipe) {
12
+ return sha256Hex(utf8Bytes(canonicalJson({
13
+ kind: 'blend-v1',
14
+ model: modelSha256,
15
+ slots: recipe.slots.map((s) => ({ latent: s.latentSha256, weight: s.weight })),
16
+ })));
17
+ }
18
+ /** blend() plus the recipe a saved blend carries. Refuses an unknown slot kind and an oversized recipe. */
19
+ export function blendWithRecipe(descriptor, slots, weights) {
20
+ for (const [slot, s] of slots.entries())
21
+ if (!BLEND_SLOT_KINDS.includes(s.kind))
22
+ return { ok: false, error: { code: 'not-w-plus', slot, message: 'Unknown slot kind.' } };
23
+ if (slots.length > BLEND_RECIPE_MAX_SLOTS)
24
+ return {
25
+ ok: false,
26
+ error: {
27
+ code: 'weight-count',
28
+ message: `A saved blend records at most ${BLEND_RECIPE_MAX_SLOTS} faces.`,
29
+ },
30
+ };
31
+ const r = blend(descriptor, slots.map((s) => s.latent), weights);
32
+ if (!r.ok)
33
+ return r;
34
+ const recipe = Object.freeze({
35
+ kind: 'blend-v1',
36
+ slots: Object.freeze(slots.map((s, k) => Object.freeze({
37
+ kind: s.kind,
38
+ latentSha256: latentDigest(s.latent),
39
+ weight: r.value.weights[k],
40
+ }))),
41
+ });
42
+ return {
43
+ ok: true,
44
+ value: {
45
+ result: r.value,
46
+ recipe,
47
+ generationSha256: blendRecipeDigest(descriptor.identity.modelSha256, recipe),
48
+ },
49
+ };
50
+ }
51
+ /**
52
+ * What a blend contributes to its export identity (apps/web contracts exportIdentity): ordered inputs naming
53
+ * each slot's kind, latent digest and weight, so blends differing in any weight get different identities,
54
+ * and the filename label `blend-<n>-faces`.
55
+ */
56
+ export function blendExportInputs(recipe) {
57
+ return {
58
+ orderedInputs: recipe.slots.map((s) => `blend:${s.kind}:${s.latentSha256}:${JSON.stringify(s.weight)}`),
59
+ label: `blend-${recipe.slots.length}-faces`,
60
+ };
61
+ }
62
+ /** The recipe slots whose latent digest matches `latent`, for restoring weights in the blend view. */
63
+ export function recipeSlotsFor(recipe, latent) {
64
+ const digest = latentDigest(latent);
65
+ return recipe.slots.flatMap((s, i) => (s.latentSha256 === digest ? [i] : []));
66
+ }
@@ -0,0 +1,8 @@
1
+ export type CanonicalValue = string | number | boolean | null | readonly CanonicalValue[] | {
2
+ readonly [key: string]: CanonicalValue;
3
+ };
4
+ export declare class CanonicalJsonError extends Error {
5
+ readonly code: 'non-finite-number' | 'unsupported-value' | 'lone-surrogate';
6
+ constructor(code: CanonicalJsonError['code'], message: string);
7
+ }
8
+ export declare function canonicalJson(value: unknown): string;
@@ -0,0 +1,34 @@
1
+ // Canonical JSON for contract identities: object keys sorted by UTF-16 code unit, no whitespace,
2
+ // numbers as JSON.stringify writes them (integers exactly as written), UTF-8 encoded for hashing.
3
+ // Only plain JSON values are canonical; anything else is rejected rather than coerced.
4
+ export class CanonicalJsonError extends Error {
5
+ code;
6
+ constructor(code, message) {
7
+ super(message);
8
+ this.name = 'CanonicalJsonError';
9
+ this.code = code;
10
+ }
11
+ }
12
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
13
+ export function canonicalJson(value) {
14
+ if (value === null || typeof value === 'boolean')
15
+ return JSON.stringify(value);
16
+ if (typeof value === 'number') {
17
+ if (!Number.isFinite(value))
18
+ throw new CanonicalJsonError('non-finite-number', `${value} has no JSON form`);
19
+ return JSON.stringify(Object.is(value, -0) ? 0 : value);
20
+ }
21
+ if (typeof value === 'string') {
22
+ if (LONE_SURROGATE.test(value))
23
+ throw new CanonicalJsonError('lone-surrogate', 'a string has no UTF-8 form');
24
+ return JSON.stringify(value);
25
+ }
26
+ if (Array.isArray(value))
27
+ return `[${value.map(canonicalJson).join(',')}]`;
28
+ if (typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
29
+ const entries = Object.entries(value).filter(([, v]) => v !== undefined);
30
+ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
31
+ return `{${entries.map(([k, v]) => `${canonicalJson(k)}:${canonicalJson(v)}`).join(',')}}`;
32
+ }
33
+ throw new CanonicalJsonError('unsupported-value', `${typeof value} is not a plain JSON value`);
34
+ }