comfy-ts 2.23.0 → 2.24.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 (76) hide show
  1. package/dist/{ServeApp-DolRCMHj.js → ServeApp-fsHtW5zG.js} +3 -3
  2. package/dist/{ServeApp-DolRCMHj.js.map → ServeApp-fsHtW5zG.js.map} +1 -1
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-Duneoq6r.js → exampleAssets-DZynSkZm.js} +79 -15
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-DjoJA8y7.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-DjoJA8y7.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +80 -14
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +53 -19
  11. package/dist/index.d.ts +53 -19
  12. package/dist/index.js +80 -15
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Cr0L9lCK.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Cr0L9lCK.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve---qA7o_m.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve---qA7o_m.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-DxXiWo5J.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-DxXiWo5J.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-BTxdABHi.js → schemaDrift-BGYJZGMD.js} +3 -2
  21. package/dist/{schemaDrift-BTxdABHi.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/web.d.ts +53 -19
  23. package/dist/web.js +80 -15
  24. package/dist/web.js.map +1 -1
  25. package/examples/README.md +1 -0
  26. package/examples/depth-explorer/models.ts +6 -56
  27. package/examples/depth-explorer/serve.ts +12 -133
  28. package/examples/depth-explorer/web/App.tsx +20 -91
  29. package/examples/depth-explorer/web/index.html +1 -0
  30. package/examples/depth-explorer/web/state.ts +26 -109
  31. package/examples/depth-explorer/web/styles.css +1 -286
  32. package/examples/explorer-kit/catalog.ts +80 -0
  33. package/examples/explorer-kit/server.ts +167 -0
  34. package/examples/explorer-kit/web/base.css +289 -0
  35. package/examples/explorer-kit/web/runs.ts +160 -0
  36. package/examples/explorer-kit/web/ui.tsx +125 -0
  37. package/examples/rvion/17-relight.cflow.ts +2 -1
  38. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  39. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  40. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  41. package/examples/rvion/flythroughChain.ts +171 -0
  42. package/examples/rvion/flythroughColmap.ts +157 -0
  43. package/examples/rvion/flythroughFuse.ts +199 -0
  44. package/examples/rvion/flythroughGuide.ts +300 -0
  45. package/examples/rvion/flythroughPalette.ts +310 -0
  46. package/examples/rvion/flythroughPath.ts +177 -0
  47. package/examples/rvion/flythroughSplat.ts +73 -0
  48. package/examples/rvion/grow-splat/align.ts +114 -0
  49. package/examples/rvion/grow-splat/grow.ts +198 -0
  50. package/examples/rvion/grow-splat/ply.ts +166 -0
  51. package/examples/rvion/grow-splat/raster.ts +207 -0
  52. package/examples/rvion/grow-splat/sharp.ts +45 -0
  53. package/examples/rvion/splatDataset.ts +80 -0
  54. package/examples/rvion/splatEval.ts +380 -0
  55. package/examples/upscale-explorer/models.ts +341 -0
  56. package/examples/upscale-explorer/serve.ts +19 -0
  57. package/examples/upscale-explorer/web/App.tsx +250 -0
  58. package/examples/upscale-explorer/web/compare.tsx +285 -0
  59. package/examples/upscale-explorer/web/index.html +15 -0
  60. package/examples/upscale-explorer/web/main.tsx +12 -0
  61. package/examples/upscale-explorer/web/state.ts +279 -0
  62. package/examples/upscale-explorer/web/styles.css +241 -0
  63. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  64. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  65. package/examples/world-explorer/web/main.tsx +2 -2
  66. package/package.json +4 -3
  67. package/src/coreExports.ts +5 -0
  68. package/src/host/ComfyHost.ts +6 -0
  69. package/src/runner/ComfyExecution.ts +22 -5
  70. package/src/runner/ComfyWorkflow.ts +22 -0
  71. package/src/runner/ComfyWsApi.ts +1 -1
  72. package/src/runner/comfyOrgApiKey.ts +44 -0
  73. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  74. package/src/state.ts +2 -0
  75. package/src/vars/DefinedWorkflow.ts +1 -0
  76. package/dist/exampleAssets-Duneoq6r.js.map +0 -1
@@ -20,6 +20,7 @@ Every `*.cflow.ts` file here is a runnable workflow module. Run it directly with
20
20
  - `web/`: the browser entry `comfy-ts/web` in a runnable page (`bun examples/web/serve.ts`).
21
21
  - `rvion/17-relight.cflow.ts`: relight a photo in the web panel. It runs one depth model and one normal model (a choice each) and, behind two toggles, Marigold material maps (albedo, roughness, metalness, reflections). Every map is tagged, and the module names the panel's `relight` widget, which draws the photo lit by a point light you drag over it: left/right, up/down, the wheel for nearer/farther, with shadows from the depth map and drifting light motes. Needs the ControlNet preprocessors pack and, for materials, [ComfyUI-Marigold](https://github.com/kijai/ComfyUI-Marigold).
22
22
  - `depth-explorer/`: a small web app that runs every depth, normal and material estimator your host has on one image and compares them: a grid, a wipe slider against the source or another model, a 3D relief of each depth map, and the relight widget fed with the best maps of the grid (`bun examples/depth-explorer/serve.ts [--samples <dir>]`, then http://127.0.0.1:8292). Depth Anything 3, MoGe-2, Marigold v2, Lotus, Depth Anything V2, Metric3D v2, DSINE, Marigold IID and the ControlNet preprocessors; a model your host lacks shows the weight files it needs, with their download links. One ComfyUI graph per model lives in `depth-explorer/models.ts`.
23
+ - `upscale-explorer/`: the same kind of app for upscalers (`bun examples/upscale-explorer/serve.ts [--samples <dir>]`, then http://127.0.0.1:8294). Every result comes out at the same size (×2 or ×4 the source), so you can judge them pixel for pixel: a loupe shows every result on the same crop at 100 %, and a pair view compares two of them side by side, with a curtain, as an onion skin, one over the other on hover, or as the pixels that changed. The wheel zooms at the pointer and every picture follows. UltraSharp V2, IllustrationJaNai V3, Nomos2, AnimeSharp V4, SeedVR2 (3B and 7B sharp, on core ComfyUI nodes) and the ESRGAN classics, each against plain Lanczos. Both apps share `explorer-kit/`.
23
24
 
24
25
  ## Cloud API key
25
26
 
@@ -2,42 +2,22 @@
2
2
  // an entry runs only when the host has its nodes AND its weight files (checked live, see `availability`).
3
3
  // depth outputs follow one convention so the grid compares like with like: near = white.
4
4
  import { fileURLToPath } from 'node:url'
5
- import type { BaseNode, BaseNodeFactory, ChoiceOptionLook, ComfyWorkflow } from 'comfy-ts'
5
+ import type { BaseNode, ChoiceOptionLook } from 'comfy-ts'
6
+ import { base, type CatalogEntry, type WeightFile } from '../explorer-kit/catalog.ts'
7
+ import type { ExplorerImg as Img, ExplorerWf as W } from '../explorer-kit/server.ts'
6
8
 
7
- export type HostId = 'windows-1'
8
- type W = ComfyWorkflow<HostId>
9
9
  type B = W['builder']
10
- type Img = Comfy.Windows1.Accepts['IMAGE']
11
10
 
12
11
  export type ModelKind = 'depth' | 'normal' | 'material'
13
12
 
14
- /** a weight file the graph names, and where to get it when the host lacks it */
15
- export type WeightFile = { node: string; input: string; file: string; folder: string; url: string }
16
-
17
- export type ModelEntry = {
18
- id: string
19
- label: string
20
- family: string
21
- year: number
22
- /** when it came out, as precise as known: `2025-11` */
23
- date: string
24
- /** its weights on disk */
25
- size: string
26
- /** 1 (rough) to 5 (the best of its kind), judged on the explorer's samples */
27
- quality: number
28
- /** one run at detail 768 on an RTX class GPU, weights loaded */
29
- speed: string
13
+ /** `speed`: one run at detail 768; controlnet_aux nodes download their weights on the first run,
14
+ * so their `files` stay empty */
15
+ export type ModelEntry = CatalogEntry & {
30
16
  /** materials: the map it gives the relight widget */
31
17
  map?: 'albedo' | 'roughness' | 'metalness' | 'specular' | 'shading'
32
18
  kind: ModelKind
33
19
  /** classic = pre 2023 baselines, off by default */
34
20
  tier: 'modern' | 'classic'
35
- blurb: string
36
- nodes: string[]
37
- /** weights the host must list; controlnet_aux nodes download theirs on first run instead */
38
- files: WeightFile[]
39
- /** the node pack downloads its weights on the first run (slow once) */
40
- autoDownload?: boolean
41
21
  /** the graph up to its output image; the server adds the websocket save node */
42
22
  build: (b: B, image: Img, p: { detail: number; wf: W }) => Img | BaseNode
43
23
  }
@@ -142,13 +122,6 @@ const mogeGeometry = (b: B, image: Img, detail: number) =>
142
122
  refine_steps: 0,
143
123
  })
144
124
 
145
- /** a factory of the base (untyped) builder, or a loud error naming the node */
146
- function base(wf: W, name: string): BaseNodeFactory {
147
- const f = wf.builderBase[name]
148
- if (f == null) throw new Error(`this host has no ${name} node`)
149
- return f
150
- }
151
-
152
125
  /** the Marigold v2 blueprint (Comfy-Org): one flow step on a qwen image edit base + a task lora.
153
126
  * built on the BASE builder: its weight names are not in the host sdk until they are downloaded */
154
127
  const marigold = (wf: W, image: Img, task: MarigoldTask): BaseNode => {
@@ -697,26 +670,3 @@ export function optionLook(m: ModelEntry): ChoiceOptionLook {
697
670
  ...(m.tier === 'classic' ? { tags: ['classic'] } : {}),
698
671
  }
699
672
  }
700
-
701
- /** raw object_info, as the host schema keeps it */
702
- type ObjectInfo = Record<string, { input?: { required?: Record<string, unknown>; optional?: Record<string, unknown> } }>
703
-
704
- /** the options of a COMBO input in both object_info spellings: [[...]] and ['COMBO', { options }] */
705
- function comboOptions(info: ObjectInfo, node: string, input: string): string[] {
706
- const def = info[node]?.input
707
- const slot = def?.required?.[input] ?? def?.optional?.[input]
708
- if (!Array.isArray(slot)) return []
709
- const head: unknown = slot[0]
710
- if (Array.isArray(head)) return head.filter((x): x is string => typeof x === 'string')
711
- const meta: unknown = slot[1]
712
- const opts: unknown = typeof meta === 'object' && meta != null && 'options' in meta ? meta.options : null
713
- return Array.isArray(opts) ? opts.filter((x): x is string => typeof x === 'string') : []
714
- }
715
-
716
- export type Availability = { ok: boolean; missingNodes: string[]; missingFiles: WeightFile[] }
717
-
718
- export function availability(info: ObjectInfo, m: ModelEntry): Availability {
719
- const missingNodes = m.nodes.filter((n) => info[n] == null)
720
- const missingFiles = m.files.filter((f) => !comboOptions(info, f.node, f.input).includes(f.file))
721
- return { ok: missingNodes.length === 0 && missingFiles.length === 0, missingNodes, missingFiles }
722
- }
@@ -1,140 +1,19 @@
1
1
  // depth explorer: drop any image, run every depth / normal estimator the host has, compare them
2
2
  // side by side, as a 3D relief or relit by the normals.
3
3
  // bun examples/depth-explorer/serve.ts [--samples <dir>] → http://127.0.0.1:8292
4
- // one ComfyUI prompt per model, so each card fills as its model finishes and one failure stays one card.
5
- import { createHash } from 'node:crypto'
6
- import { readdirSync } from 'node:fs'
7
- import { ComfyTS, exampleImagePath, MediaImage } from 'comfy-ts'
8
- import { basename, dirname, resolve } from 'pathe'
9
- import { availability, MODELS, type HostId } from './models.ts'
4
+ import { serveExplorer } from '../explorer-kit/server.ts'
5
+ import { MODELS } from './models.ts'
10
6
  import page from './web/index.html'
11
7
 
12
- const HOST_ID: HostId = 'windows-1'
13
- const PORT = Number(process.env.PORT ?? 8292)
14
-
15
- const comfy = ComfyTS.create()
16
- const host = comfy.host({ id: HOST_ID })
17
- // a live schema: availability reads the loaders' file lists, and a weight downloaded since the
18
- // cache was written must show up as runnable
19
- await host.connect({ schema: 'refresh' })
20
-
21
- /** uploaded source images, by content hash (the page sends each one once) */
22
- const images = new Map<string, Uint8Array>()
23
-
24
- /** the bundled example images, plus every `--samples <dir>` given: name → file */
25
- const samplePaths = new Map<string, string>()
26
- const sampleDirs = [dirname(exampleImagePath('dog_512x512.jpg'))]
27
- for (let i = 2; i < process.argv.length; i++)
28
- if (process.argv[i] === '--samples' && process.argv[i + 1] != null)
29
- sampleDirs.push(resolve(String(process.argv[++i])))
30
- for (const dir of sampleDirs)
31
- for (const f of readdirSync(dir)) if (/\.(jpe?g|png|webp)$/i.test(f)) samplePaths.set(f, `${dir}/${f}`)
32
- const samples = [...samplePaths.keys()]
33
-
34
- const json = (data: unknown, status = 200): Response => Response.json(data, { status })
35
-
36
- function modelsPayload(): unknown {
37
- const info = host.schema.data.spec
38
- return {
39
- host: HOST_ID,
40
- models: MODELS.map((m) => ({
41
- id: m.id,
42
- label: m.label,
43
- family: m.family,
44
- year: m.year,
45
- kind: m.kind,
46
- tier: m.tier,
47
- blurb: m.blurb,
48
- date: m.date,
49
- size: m.size,
50
- quality: m.quality,
51
- speed: m.speed,
52
- autoDownload: m.autoDownload === true,
53
- ...availability(info, m),
54
- })),
55
- }
56
- }
57
-
58
- type RunBody = { image: string; model: string; detail: number }
59
-
60
- function readRunBody(raw: unknown): RunBody {
61
- const r = raw as Partial<RunBody> | null
62
- if (r == null || typeof r.image !== 'string' || typeof r.model !== 'string' || typeof r.detail !== 'number')
63
- throw new Error('body must be { image: string, model: string, detail: number }')
64
- return { image: r.image, model: r.model, detail: Math.min(2048, Math.max(256, Math.round(r.detail))) }
65
- }
66
-
67
- async function run(body: RunBody): Promise<Response> {
68
- const model = MODELS.find((m) => m.id === body.model)
69
- if (model == null) return json({ error: `unknown model ${body.model}` }, 404)
70
- const avail = availability(host.schema.data.spec, model)
71
- if (!avail.ok) return json({ error: 'not on this host', ...avail }, 409)
72
- const bytes = images.get(body.image)
73
- if (bytes == null) return json({ error: 'unknown image, upload it again' }, 404)
74
-
75
- const started = performance.now()
76
- const wf = host.workflow({ id: `depth-explorer-${model.id}` })
77
- const loaded = await new MediaImage({ buffer: bytes }).loadInWorkflow_viaLoadImageNode(wf)
78
- const out = model.build(wf.builder, loaded, { detail: body.detail, wf })
79
- const save = wf.builderBase.SaveImageWebsocket
80
- if (save == null) throw new Error('this host has no SaveImageWebsocket node')
81
- save({ images: out })
82
- // SaveImageWebsocket: the result never touches the server disk; the source image is uploaded
83
- // once (hash named) and reused by every model
84
- const execution = await wf.run({ scrubHistory: true })
85
- const ms = Math.round(performance.now() - started)
86
- const first = execution.images[0]
87
- if (execution.status !== 'Success' || first == null) {
88
- // ComfyUI's own reason (a missing weight, an oom) sits in the error message's data
89
- const err = execution.data.error
90
- const message =
91
- err != null && 'exception_message' in err.data
92
- ? `${err.data.node_type ?? 'a node'}: ${err.data.exception_message}`
93
- : `run ended ${execution.status}, no image`
94
- console.error(`🔴 ${model.id}: ${message}`)
95
- return json({ error: message, ms }, 500)
96
- }
97
- console.log(`🟢 ${model.id} ${ms} ms`)
98
- return new Response(first.buffer as Uint8Array<ArrayBuffer>, {
99
- headers: { 'content-type': `image/${first.metadata.type ?? 'png'}`, 'x-ms': String(ms) },
100
- })
101
- }
102
-
103
- const server = Bun.serve({
104
- port: PORT,
105
- hostname: '127.0.0.1',
106
- development: true,
107
- idleTimeout: 255, // a cold model load on the GPU box takes minutes
108
- routes: {
109
- '/': page,
110
- '/api/models': () => json(modelsPayload()),
111
- '/api/samples': () => json(samples),
112
- '/api/samples/:name': (req) => {
113
- const path = samplePaths.get(basename(req.params.name))
114
- if (path == null) return json({ error: 'no such sample' }, 404)
115
- return new Response(Bun.file(path))
116
- },
117
- '/api/image': {
118
- POST: async (req) => {
119
- const bytes = new Uint8Array(await req.arrayBuffer())
120
- if (bytes.length === 0) return json({ error: 'empty body' }, 400)
121
- const key = createHash('sha1').update(bytes).digest('hex').slice(0, 16)
122
- images.set(key, bytes)
123
- return json({ key })
124
- },
125
- },
126
- '/api/run': {
127
- POST: async (req) => {
128
- try {
129
- return await run(readRunBody(await req.json()))
130
- } catch (e) {
131
- const message = e instanceof Error ? e.message : String(e)
132
- console.error('🔴 run failed:', message)
133
- return json({ error: message }, 500)
134
- }
135
- },
136
- },
8
+ await serveExplorer({
9
+ name: 'depth explorer',
10
+ port: 8292,
11
+ page,
12
+ catalog: MODELS,
13
+ card: (m) => ({ kind: m.kind, tier: m.tier }),
14
+ readParams: (raw) => {
15
+ if (typeof raw.detail !== 'number') throw new Error('body needs { detail: number }')
16
+ return { detail: Math.min(2048, Math.max(256, Math.round(raw.detail))) }
137
17
  },
18
+ build: (wf, image, m, p) => m.build(wf.builder, image, { detail: p.detail, wf }),
138
19
  })
139
-
140
- console.log(`depth explorer → http://127.0.0.1:${server.port}/ (host ${HOST_ID})`)
@@ -1,5 +1,6 @@
1
1
  import { observer } from 'mobx-react-lite'
2
- import { useEffect, useRef, useState, type ReactNode } from 'react'
2
+ import { useEffect, useRef, useState } from 'react'
3
+ import { RunBody, Seg, SourcePicker, timeOf } from '../../explorer-kit/web/ui.tsx'
3
4
  import { GlView, type GlParams } from './gl.ts'
4
5
  import { greyDepth, loadImage, paintDepth } from './pixels.ts'
5
6
  import { RelightWidgetView } from '../../../src/cli/serve/web/widgets/RelightWidget.tsx'
@@ -42,44 +43,18 @@ const Card = observer(function Card(p: { st: AppSt; model: ModelInfo }) {
42
43
  const { st, model } = p
43
44
  const r = st.result(model.id)
44
45
  const aspect = st.source != null ? `${st.source.width} / ${st.source.height}` : '1'
45
- let body: ReactNode
46
- if (!model.ok) {
47
- body = (
48
- <div className="missing">
49
- <b>not on this host</b>
50
- {model.missingNodes.length > 0 && <span>nodes: {model.missingNodes.join(', ')}</span>}
51
- {model.missingFiles.map((f) => (
52
- <a key={f.file} href={f.url} target="_blank" rel="noreferrer">
53
- models/{f.folder}/{f.file}
54
- </a>
55
- ))}
56
- </div>
57
- )
58
- } else if (r == null) {
59
- body = (
60
- <button className="ghost" onClick={() => st.enqueue(model.id)} disabled={st.source == null}>
61
- run
62
- </button>
63
- )
64
- } else if (r.status === 'queued') body = <span className="dim">queued</span>
65
- else if (r.status === 'running')
66
- body = (
67
- <span className="dim">
68
- <span className="spin" /> {((st.now - r.startedAt) / 1000).toFixed(1)} s
69
- {model.autoDownload && st.now - r.startedAt > 8000 && <small>first run downloads the weights</small>}
70
- </span>
71
- )
72
- else if (r.status === 'error')
73
- body = (
74
- <div className="err">
75
- <span>{r.error}</span>
76
- <button className="ghost" onClick={() => st.enqueue(model.id)}>
77
- retry
78
- </button>
79
- </div>
46
+ const body =
47
+ r?.status === 'done' && r.url != null ? (
48
+ <MapImage st={st} model={model} url={r.url} />
49
+ ) : (
50
+ <RunBody
51
+ model={model}
52
+ run={r}
53
+ now={st.runs.now}
54
+ canRun={st.source != null}
55
+ onRun={() => st.enqueue(model.id)}
56
+ />
80
57
  )
81
- else if (r.url != null) body = <MapImage st={st} model={model} url={r.url} />
82
-
83
58
  const done = r?.status === 'done'
84
59
  return (
85
60
  <div className={`card ${done ? 'done' : ''} ${model.ok ? '' : 'off'}`}>
@@ -88,7 +63,7 @@ const Card = observer(function Card(p: { st: AppSt; model: ModelInfo }) {
88
63
  {model.label} <span className="fam">{model.family}</span>
89
64
  </span>
90
65
  <span className="meta">
91
- {r?.ms != null && done ? `${(r.ms / 1000).toFixed(1)} s · ` : ''}
66
+ {done ? `${timeOf(r)} · ` : ''}
92
67
  {model.year}
93
68
  </span>
94
69
  </div>
@@ -114,62 +89,16 @@ const Section = observer(function Section(p: { st: AppSt; title: string; models:
114
89
  )
115
90
  })
116
91
 
117
- function Seg<T extends string | number>(p: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
118
- return (
119
- <div className="seg">
120
- {p.options.map(([v, label]) => (
121
- <button key={String(v)} className={v === p.value ? 'on' : ''} onClick={() => p.onChange(v)}>
122
- {label}
123
- </button>
124
- ))}
125
- </div>
126
- )
127
- }
128
-
129
92
  const Sidebar = observer(function Sidebar(p: { st: AppSt }) {
130
93
  const { st } = p
131
- const [drag, setDrag] = useState(false)
132
- const fileRef = useRef<HTMLInputElement>(null)
133
- const take = (f: File | undefined): void => {
134
- if (f != null && f.type.startsWith('image/')) void st.setSource(f, f.name)
135
- }
136
- useEffect(() => {
137
- const onPaste = (e: ClipboardEvent): void => {
138
- const f = [...(e.clipboardData?.files ?? [])].find((x) => x.type.startsWith('image/'))
139
- take(f)
140
- }
141
- window.addEventListener('paste', onPaste)
142
- return () => window.removeEventListener('paste', onPaste)
143
- })
144
94
  return (
145
95
  <aside>
146
- <div
147
- className={`drop ${drag ? 'over' : ''}`}
148
- onDragOver={(e) => {
149
- e.preventDefault()
150
- setDrag(true)
151
- }}
152
- onDragLeave={() => setDrag(false)}
153
- onDrop={(e) => {
154
- e.preventDefault()
155
- setDrag(false)
156
- take(e.dataTransfer.files[0])
157
- }}
158
- onClick={() => fileRef.current?.click()}
159
- >
160
- {st.source != null ? <img src={st.source.url} alt={st.source.name} /> : <span>drop an image</span>}
161
- <input ref={fileRef} type="file" accept="image/*" hidden onChange={(e) => take(e.target.files?.[0])} />
162
- </div>
163
- <div className="dim small">
164
- {st.source != null ? `${st.source.name} · ${st.source.width}×${st.source.height}` : ''}
165
- <br />
166
- drop, click or paste an image
167
- </div>
168
- <div className="samples">
169
- {st.samples.map((s) => (
170
- <img key={s} src={`/api/samples/${s}`} alt={s} title={s} onClick={() => void st.loadSample(s)} />
171
- ))}
172
- </div>
96
+ <SourcePicker
97
+ source={st.source}
98
+ samples={st.samples}
99
+ onFile={(f, name) => void st.setSource(f, name)}
100
+ onSample={(name) => void st.loadSample(name)}
101
+ />
173
102
 
174
103
  <label>detail</label>
175
104
  <Seg
@@ -5,6 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
6
  <title>depth explorer</title>
7
7
  <meta name="shot-ready" content="wait" />
8
+ <link rel="stylesheet" href="../../explorer-kit/web/base.css" />
8
9
  <link rel="stylesheet" href="./styles.css" />
9
10
  </head>
10
11
  <body>
@@ -1,36 +1,20 @@
1
1
  // the one state tree of the page: the catalog from the server, the source image, one result per
2
- // (image, detail, model), the view settings. A sequential run queue: one prompt at a time on the GPU.
2
+ // (image, detail, model), the view settings. The run queue is the explorer kit's.
3
3
  import { makeAutoObservable, runInAction } from 'mobx'
4
-
5
- export type WeightFile = { node: string; input: string; file: string; folder: string; url: string }
6
- export type ModelInfo = {
7
- id: string
8
- label: string
9
- family: string
10
- year: number
11
- kind: 'depth' | 'normal' | 'material'
12
- tier: 'modern' | 'classic'
13
- blurb: string
14
- autoDownload: boolean
15
- ok: boolean
16
- missingNodes: string[]
17
- missingFiles: WeightFile[]
18
- }
19
- export type Source = { key: string; url: string; name: string; width: number; height: number }
4
+ import {
5
+ fetchCatalog,
6
+ RunQueue,
7
+ sampleBlob,
8
+ uploadSource,
9
+ type CardInfo,
10
+ type RunSt,
11
+ type Source,
12
+ } from '../../explorer-kit/web/runs.ts'
13
+
14
+ export type ModelInfo = CardInfo & { kind: 'depth' | 'normal' | 'material'; tier: 'modern' | 'classic' }
20
15
  export type Colormap = 'gray' | 'turbo'
21
16
  export type FocusView = 'wipe' | '3d' | 'light'
22
17
 
23
- export class ResultSt {
24
- status: 'queued' | 'running' | 'done' | 'error' = 'queued'
25
- url: string | null = null
26
- ms: number | null = null
27
- error: string | null = null
28
- startedAt = 0
29
- constructor() {
30
- makeAutoObservable(this)
31
- }
32
- }
33
-
34
18
  export class AppSt {
35
19
  host = ''
36
20
  models: ModelInfo[] = []
@@ -50,25 +34,19 @@ export class AppSt {
50
34
  wipeX = 50
51
35
  /** the 3D relief camera and surface */
52
36
  relief = { yaw: 0.35, pitch: 0.2, zoom: 1, depthScale: 0.3, shade: 0.6 }
53
- results = new Map<string, ResultSt>()
54
- private queue: { key: string; model: string; image: string; detail: number }[] = []
55
- private draining = false
56
- /** ticks every 200 ms while something runs, for the elapsed timers */
57
- now = Date.now()
37
+ runs = new RunQueue()
58
38
 
59
39
  constructor() {
60
- makeAutoObservable(this, { results: true })
61
- setInterval(() => runInAction(() => (this.now = Date.now())), 200)
40
+ makeAutoObservable(this)
62
41
  }
63
42
 
64
43
  async boot(): Promise<void> {
65
44
  try {
66
- const [m, s] = await Promise.all([fetch('/api/models'), fetch('/api/samples')])
67
- const mj = (await m.json()) as { host: string; models: ModelInfo[] }
68
- const sj = (await s.json()) as string[]
45
+ const c = await fetchCatalog<ModelInfo>()
46
+ const sj = c.samples
69
47
  runInAction(() => {
70
- this.host = mj.host
71
- this.models = mj.models
48
+ this.host = c.host
49
+ this.models = c.models
72
50
  this.samples = sj
73
51
  })
74
52
  // deep link: ?image=<sample>&run=all|<id,id>&focus=<id>&view=wipe|3d|light
@@ -197,7 +175,7 @@ export class AppSt {
197
175
  return this.visibleModels.filter((m) => m.ok)
198
176
  }
199
177
  get busy(): boolean {
200
- return this.queue.length > 0 || this.draining
178
+ return this.runs.busy
201
179
  }
202
180
 
203
181
  model(id: string): ModelInfo | undefined {
@@ -206,29 +184,21 @@ export class AppSt {
206
184
  resultKey(model: string): string {
207
185
  return `${this.source?.key ?? '-'}:${this.detail}:${model}`
208
186
  }
209
- result(model: string): ResultSt | undefined {
210
- return this.results.get(this.resultKey(model))
187
+ result(model: string): RunSt | undefined {
188
+ return this.runs.get(this.resultKey(model))
211
189
  }
212
190
  get doneModels(): ModelInfo[] {
213
191
  return this.models.filter((m) => this.result(m.id)?.status === 'done')
214
192
  }
215
193
 
216
194
  async loadSample(name: string): Promise<void> {
217
- const blob = await (await fetch(`/api/samples/${encodeURIComponent(name)}`)).blob()
218
- await this.setSource(blob, name)
195
+ await this.setSource(await sampleBlob(name), name)
219
196
  }
220
197
 
221
198
  async setSource(blob: Blob, name: string): Promise<void> {
222
- const url = URL.createObjectURL(blob)
223
- const img = new Image()
224
- img.src = url
225
- await img.decode()
226
- const res = await fetch('/api/image', { method: 'POST', body: blob })
227
- const j = (await res.json()) as { key?: string; error?: string }
228
- if (j.key == null) throw new Error(j.error ?? 'upload failed')
229
- const key = j.key
199
+ const source = await uploadSource(blob, name)
230
200
  runInAction(() => {
231
- this.source = { key, url, name, width: img.naturalWidth, height: img.naturalHeight }
201
+ this.source = source
232
202
  this.focus = null
233
203
  })
234
204
  }
@@ -236,12 +206,7 @@ export class AppSt {
236
206
  enqueue(model: string): void {
237
207
  const src = this.source
238
208
  if (src == null) return
239
- const key = this.resultKey(model)
240
- const prev = this.results.get(key)
241
- if (prev != null && (prev.status === 'queued' || prev.status === 'running')) return
242
- this.results.set(key, new ResultSt())
243
- this.queue.push({ key, model, image: src.key, detail: this.detail })
244
- void this.drain()
209
+ this.runs.enqueue(this.resultKey(model), { image: src.key, model, detail: this.detail })
245
210
  }
246
211
 
247
212
  runAll(): void {
@@ -250,55 +215,7 @@ export class AppSt {
250
215
 
251
216
  /** resolves once the run queue is empty */
252
217
  settled(): Promise<void> {
253
- return new Promise((resolve) => {
254
- const tick = (): void => {
255
- if (this.busy) setTimeout(tick, 100)
256
- else resolve()
257
- }
258
- tick()
259
- })
260
- }
261
-
262
- private async drain(): Promise<void> {
263
- if (this.draining) return
264
- this.draining = true
265
- try {
266
- for (;;) {
267
- const job = this.queue.shift()
268
- if (job == null) break
269
- const r = this.results.get(job.key)
270
- if (r == null) continue
271
- runInAction(() => {
272
- r.status = 'running'
273
- r.startedAt = Date.now()
274
- })
275
- try {
276
- const res = await fetch('/api/run', {
277
- method: 'POST',
278
- headers: { 'content-type': 'application/json' },
279
- body: JSON.stringify({ image: job.image, model: job.model, detail: job.detail }),
280
- })
281
- if (!res.ok) {
282
- const j = (await res.json()) as { error?: string }
283
- throw new Error(j.error ?? `http ${res.status}`)
284
- }
285
- const url = URL.createObjectURL(await res.blob())
286
- const ms = Number(res.headers.get('x-ms'))
287
- runInAction(() => {
288
- r.url = url
289
- r.ms = ms
290
- r.status = 'done'
291
- })
292
- } catch (e) {
293
- runInAction(() => {
294
- r.error = e instanceof Error ? e.message : String(e)
295
- r.status = 'error'
296
- })
297
- }
298
- }
299
- } finally {
300
- runInAction(() => (this.draining = false))
301
- }
218
+ return this.runs.settled()
302
219
  }
303
220
 
304
221
  openFocus(model: string): void {