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
@@ -0,0 +1,380 @@
1
+ // how good a trained splat is, measured: each COLMAP camera rendered with the CPU rasterizer (view dependent
2
+ // colour included) and scored against its frame (PSNR, SSIM), plus the shape of the splats themselves: needles
3
+ // (one axis far longer than the others) and splats few training cameras ever see. Also the pruning those
4
+ // numbers call for. Works in the trainer's own world (the COLMAP export's), before any turn to viewer axes.
5
+ //
6
+ // run: bun examples/rvion/splatEval.ts <trained.ply> <colmap dir> <split.json> [--out <dir>] [--shots name,name]
7
+ // split.json: { heldout: string[], train: string[] } (image names), as splatDataset.ts writes it
8
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
9
+ import { join } from 'pathe'
10
+ import sharp from 'sharp'
11
+ import { readSplatPly } from './flythroughSplat.ts'
12
+ import { F, STRIDE, type Splat, type SplatCamera } from './grow-splat/ply.ts'
13
+ import { quatToMat, render, transpose3, type Pose } from './grow-splat/raster.ts'
14
+
15
+ export type ColmapImage = { id: number; name: string; q: [number, number, number, number]; t: [number, number, number] }
16
+ export type Colmap = { camera: SplatCamera; images: ColmapImage[] }
17
+
18
+ /** a COLMAP text model with one PINHOLE camera (what flythroughColmap.ts writes) */
19
+ export function readColmap(sparse: string): Colmap {
20
+ const camLine = readFileSync(join(sparse, 'cameras.txt'), 'utf8').split('\n').find((l) => l.trim() !== '' && !l.startsWith('#'))
21
+ const w = camLine?.trim().split(/\s+/) ?? []
22
+ if (w[1] !== 'PINHOLE') throw new Error(`readColmap: one PINHOLE camera expected, got ${camLine}`)
23
+ const camera = { width: Number(w[2]), height: Number(w[3]), f: Number(w[4]), cx: Number(w[6]), cy: Number(w[7]) }
24
+ const images: ColmapImage[] = []
25
+ for (const line of readFileSync(join(sparse, 'images.txt'), 'utf8').split('\n')) {
26
+ const p = line.trim().split(/\s+/)
27
+ if (line.startsWith('#') || p.length < 10) continue
28
+ const n = p.slice(0, 8).map(Number)
29
+ images.push({ id: n[0]!, q: [n[1]!, n[2]!, n[3]!, n[4]!], t: [n[5]!, n[6]!, n[7]!], name: p[9]! })
30
+ }
31
+ return { camera, images }
32
+ }
33
+
34
+ /** the rasterizer's pose (camera axes as columns, its centre) from a COLMAP world to camera pose */
35
+ export function colmapToPose(img: Pick<ColmapImage, 'q' | 't'>): Pose {
36
+ const toCam = quatToMat(...img.q)
37
+ const R = transpose3(toCam)
38
+ const t = img.t
39
+ return { R, C: [-(R[0] * t[0] + R[1] * t[1] + R[2] * t[2]), -(R[3] * t[0] + R[4] * t[1] + R[5] * t[2]), -(R[6] * t[0] + R[7] * t[1] + R[8] * t[2])] }
40
+ }
41
+
42
+ /** a trained 3DGS ply (Brush, INRIA layout): the gaussians and their sh rest coefficients (channel major, 15 a channel at degree 3) */
43
+ export type TrainedSplat = Splat & { sh: Float32Array; shCount: number }
44
+
45
+ export function readTrained(bytes: Uint8Array): TrainedSplat {
46
+ const ply = readSplatPly(bytes)
47
+ const P = ply.names.length
48
+ const at = (name: string) => {
49
+ const i = ply.names.indexOf(name)
50
+ if (i < 0) throw new Error(`readTrained: no property ${name}`)
51
+ return i
52
+ }
53
+ const src = ['x', 'y', 'z', 'f_dc_0', 'f_dc_1', 'f_dc_2', 'opacity', 'scale_0', 'scale_1', 'scale_2', 'rot_0', 'rot_1', 'rot_2', 'rot_3'].map(at)
54
+ const rest = ply.names.filter((n) => n.startsWith('f_rest_')).length
55
+ const restAt = Array.from({ length: rest }, (_, k) => at(`f_rest_${k}`))
56
+ const shCount = rest / 3
57
+ const data = new Float32Array(ply.count * STRIDE)
58
+ const sh = new Float32Array(ply.count * rest)
59
+ for (let i = 0; i < ply.count; i++) {
60
+ for (let k = 0; k < STRIDE; k++) data[i * STRIDE + k] = ply.data[i * P + src[k]!]!
61
+ for (let k = 0; k < rest; k++) sh[i * rest + k] = ply.data[i * P + restAt[k]!]!
62
+ }
63
+ return { n: ply.count, data, camera: null, sh, shCount }
64
+ }
65
+
66
+ /** the trained ply again, with only the kept gaussians (and every property, sh included) */
67
+ export function writeTrained(s: TrainedSplat): Uint8Array {
68
+ const rest = s.shCount * 3
69
+ const names = ['x', 'y', 'z', 'f_dc_0', 'f_dc_1', 'f_dc_2', ...Array.from({ length: rest }, (_, k) => `f_rest_${k}`), 'opacity', 'scale_0', 'scale_1', 'scale_2', 'rot_0', 'rot_1', 'rot_2', 'rot_3']
70
+ const header = new TextEncoder().encode(`ply\nformat binary_little_endian 1.0\nelement vertex ${s.n}\n${names.map((p) => `property float ${p}`).join('\n')}\nend_header\n`)
71
+ const row = names.length
72
+ const out = new Float32Array(s.n * row)
73
+ for (let i = 0; i < s.n; i++) {
74
+ const b = i * STRIDE
75
+ const o = i * row
76
+ out.set(s.data.subarray(b, b + 6), o)
77
+ out.set(s.sh.subarray(i * rest, (i + 1) * rest), o + 6)
78
+ out.set(s.data.subarray(b + 6, b + STRIDE), o + 6 + rest)
79
+ }
80
+ const bytes = new Uint8Array(header.length + out.byteLength)
81
+ bytes.set(header)
82
+ bytes.set(new Uint8Array(out.buffer), header.length)
83
+ return bytes
84
+ }
85
+
86
+ const C0 = 0.28209479177387814
87
+ const C1 = 0.4886025119029199
88
+ const C2 = [1.0925484305920792, -1.0925484305920792, 0.31539156525252005, -1.0925484305920792, 0.5462742152960396]
89
+ const C3 = [-0.5900435899266435, 2.890611442640554, -0.4570457994644658, 0.3731763325901154, -0.4570457994644658, 1.445305721320277, -0.5900435899266435]
90
+
91
+ /** each gaussian's colour seen from `eye` (sh up to degree 3), 0..1 */
92
+ export function shColors(s: TrainedSplat, eye: [number, number, number]): Float32Array {
93
+ const out = new Float32Array(s.n * 3)
94
+ const K = s.shCount
95
+ const basis = new Float32Array(15)
96
+ for (let i = 0; i < s.n; i++) {
97
+ const b = i * STRIDE
98
+ let x = s.data[b]! - eye[0]
99
+ let y = s.data[b + 1]! - eye[1]
100
+ let z = s.data[b + 2]! - eye[2]
101
+ const l = Math.hypot(x, y, z) || 1
102
+ x /= l
103
+ y /= l
104
+ z /= l
105
+ if (K >= 3) {
106
+ basis[0] = -C1 * y
107
+ basis[1] = C1 * z
108
+ basis[2] = -C1 * x
109
+ }
110
+ if (K >= 8) {
111
+ const xx = x * x
112
+ const yy = y * y
113
+ const zz = z * z
114
+ basis[3] = C2[0]! * x * y
115
+ basis[4] = C2[1]! * y * z
116
+ basis[5] = C2[2]! * (2 * zz - xx - yy)
117
+ basis[6] = C2[3]! * x * z
118
+ basis[7] = C2[4]! * (xx - yy)
119
+ if (K >= 15) {
120
+ basis[8] = C3[0]! * y * (3 * xx - yy)
121
+ basis[9] = C3[1]! * x * y * z
122
+ basis[10] = C3[2]! * y * (4 * zz - xx - yy)
123
+ basis[11] = C3[3]! * z * (2 * zz - 3 * xx - 3 * yy)
124
+ basis[12] = C3[4]! * x * (4 * zz - xx - yy)
125
+ basis[13] = C3[5]! * z * (xx - yy)
126
+ basis[14] = C3[6]! * x * (xx - 3 * yy)
127
+ }
128
+ }
129
+ for (let c = 0; c < 3; c++) {
130
+ let v = 0.5 + C0 * s.data[b + F.dc + c]!
131
+ const o = (i * 3 + c) * K
132
+ for (let k = 0; k < K; k++) v += basis[k]! * s.sh[o + k]!
133
+ out[i * 3 + c] = Math.min(1, Math.max(0, v))
134
+ }
135
+ }
136
+ return out
137
+ }
138
+
139
+ /** the splat seen from one COLMAP camera, rgb 0..1 */
140
+ export function renderView(s: TrainedSplat, cam: SplatCamera, img: Pick<ColmapImage, 'q' | 't'>): Float32Array {
141
+ const pose = colmapToPose(img)
142
+ return render(s, cam, pose, { colors: shColors(s, pose.C) }).color
143
+ }
144
+
145
+ /** rgb 0..1 of a picture file */
146
+ export async function readRgb(file: string): Promise<{ rgb: Float32Array; width: number; height: number }> {
147
+ const r = await sharp(file).removeAlpha().raw().toBuffer({ resolveWithObject: true })
148
+ const rgb = new Float32Array(r.data.length)
149
+ for (let i = 0; i < r.data.length; i++) rgb[i] = r.data[i]! / 255
150
+ return { rgb, width: r.info.width, height: r.info.height }
151
+ }
152
+
153
+ export async function writeRgb(file: string, rgb: Float32Array, width: number, height: number): Promise<void> {
154
+ const px = new Uint8Array(rgb.length)
155
+ for (let i = 0; i < rgb.length; i++) px[i] = Math.round(Math.min(1, Math.max(0, rgb[i]!)) * 255)
156
+ await sharp(px, { raw: { width, height, channels: 3 } }).png().toFile(file)
157
+ }
158
+
159
+ /** peak signal to noise, dB, of two rgb 0..1 pictures; both quantised to 8 bits first, as a saved frame is */
160
+ export function psnr(a: Float32Array, b: Float32Array): number {
161
+ let se = 0
162
+ for (let i = 0; i < a.length; i++) {
163
+ const d = Math.round(a[i]! * 255) / 255 - Math.round(b[i]! * 255) / 255
164
+ se += d * d
165
+ }
166
+ const mse = se / a.length
167
+ return mse === 0 ? 99 : -10 * Math.log10(mse)
168
+ }
169
+
170
+ /** separable gaussian blur (11 taps, sigma 1.5) of one channel, the window of the SSIM paper; borders clamped */
171
+ function blur(src: Float32Array, W: number, H: number): Float32Array {
172
+ const k: number[] = []
173
+ for (let i = -5; i <= 5; i++) k.push(Math.exp(-(i * i) / (2 * 1.5 * 1.5)))
174
+ const sum = k.reduce((a, b) => a + b, 0)
175
+ const kn = k.map((x) => x / sum)
176
+ const tmp = new Float32Array(W * H)
177
+ const out = new Float32Array(W * H)
178
+ for (let y = 0; y < H; y++)
179
+ for (let x = 0; x < W; x++) {
180
+ let v = 0
181
+ for (let i = -5; i <= 5; i++) v += kn[i + 5]! * src[y * W + Math.min(W - 1, Math.max(0, x + i))]!
182
+ tmp[y * W + x] = v
183
+ }
184
+ for (let y = 0; y < H; y++)
185
+ for (let x = 0; x < W; x++) {
186
+ let v = 0
187
+ for (let i = -5; i <= 5; i++) v += kn[i + 5]! * tmp[Math.min(H - 1, Math.max(0, y + i)) * W + x]!
188
+ out[y * W + x] = v
189
+ }
190
+ return out
191
+ }
192
+
193
+ /** structural similarity of two rgb 0..1 pictures, the mean over the channels (gaussian window, as Brush and gsplat compute it) */
194
+ export function ssim(a: Float32Array, b: Float32Array, W: number, H: number): number {
195
+ const c1 = 0.01 ** 2
196
+ const c2 = 0.03 ** 2
197
+ let total = 0
198
+ for (let c = 0; c < 3; c++) {
199
+ const x = new Float32Array(W * H)
200
+ const y = new Float32Array(W * H)
201
+ for (let i = 0; i < W * H; i++) {
202
+ x[i] = a[i * 3 + c]!
203
+ y[i] = b[i * 3 + c]!
204
+ }
205
+ const mx = blur(x, W, H)
206
+ const my = blur(y, W, H)
207
+ const xx = blur(x.map((v) => v * v), W, H)
208
+ const yy = blur(y.map((v) => v * v), W, H)
209
+ const xy = blur(x.map((v, i) => v * y[i]!), W, H)
210
+ let s = 0
211
+ for (let i = 0; i < W * H; i++) {
212
+ const vx = xx[i]! - mx[i]! ** 2
213
+ const vy = yy[i]! - my[i]! ** 2
214
+ const cxy = xy[i]! - mx[i]! * my[i]!
215
+ s += ((2 * mx[i]! * my[i]! + c1) * (2 * cxy + c2)) / ((mx[i]! ** 2 + my[i]! ** 2 + c1) * (vx + vy + c2))
216
+ }
217
+ total += s / (W * H)
218
+ }
219
+ return total / 3
220
+ }
221
+
222
+ /** how many cameras have each gaussian's centre in their picture, in front of them (occlusion not counted) */
223
+ export function seenBy(s: Splat, cam: SplatCamera, images: Pick<ColmapImage, 'q' | 't'>[]): Uint16Array {
224
+ const count = new Uint16Array(s.n)
225
+ for (const img of images) {
226
+ const R = quatToMat(...img.q)
227
+ const t = img.t
228
+ for (let g = 0; g < s.n; g++) {
229
+ const b = g * STRIDE
230
+ const x = s.data[b]!
231
+ const y = s.data[b + 1]!
232
+ const z = s.data[b + 2]!
233
+ const cz = R[6] * x + R[7] * y + R[8] * z + t[2]
234
+ if (cz < 0.05) continue
235
+ const u = (cam.f * (R[0] * x + R[1] * y + R[2] * z + t[0])) / cz + cam.cx
236
+ const v = (cam.f * (R[3] * x + R[4] * y + R[5] * z + t[1])) / cz + cam.cy
237
+ if (u >= 0 && u < cam.width && v >= 0 && v < cam.height) count[g] = count[g]! + 1
238
+ }
239
+ }
240
+ return count
241
+ }
242
+
243
+ /** each gaussian's axes, longest first, as sizes (not logs) */
244
+ export function axes(s: Splat, g: number): [number, number, number] {
245
+ const b = g * STRIDE + F.scale
246
+ return [Math.exp(s.data[b]!), Math.exp(s.data[b + 1]!), Math.exp(s.data[b + 2]!)].sort((p, q) => q - p) as [number, number, number]
247
+ }
248
+
249
+ export const opacityOf = (s: Splat, g: number): number => 1 / (1 + Math.exp(-s.data[g * STRIDE + F.opacity]!))
250
+
251
+ export type SplatShape = {
252
+ count: number
253
+ /** long axis over the short one above 20 (a needle or a flat disc) */
254
+ ratio20: number
255
+ /** long axis over the middle one above 20: a true needle, long in one direction only */
256
+ needle20: number
257
+ /** the needles among the gaussians that show (opacity over 0.1) */
258
+ needle20Visible: number
259
+ /** seen by no training camera, and by fewer than 3 */
260
+ seen0: number
261
+ seenUnder3: number
262
+ seenUnder3Visible: number
263
+ }
264
+
265
+ export function splatShape(s: Splat, seen: Uint16Array): SplatShape {
266
+ const r: SplatShape = { count: s.n, ratio20: 0, needle20: 0, needle20Visible: 0, seen0: 0, seenUnder3: 0, seenUnder3Visible: 0 }
267
+ for (let g = 0; g < s.n; g++) {
268
+ const [a, b, c] = axes(s, g)
269
+ const visible = opacityOf(s, g) > 0.1
270
+ if (a > 20 * c) r.ratio20++
271
+ if (a > 20 * b) {
272
+ r.needle20++
273
+ if (visible) r.needle20Visible++
274
+ }
275
+ if (seen[g] === 0) r.seen0++
276
+ if (seen[g]! < 3) {
277
+ r.seenUnder3++
278
+ if (visible) r.seenUnder3Visible++
279
+ }
280
+ }
281
+ return r
282
+ }
283
+
284
+ export type PruneRule = {
285
+ /** drop a gaussian seen by fewer training cameras than this */
286
+ minSeen?: number
287
+ /** a needle's long axis cut to this many times its middle one */
288
+ maxNeedle?: number
289
+ }
290
+
291
+ /** the splat with the rule applied: unseen gaussians dropped, needles shortened (their volume shrinks with them) */
292
+ export function prune(s: TrainedSplat, seen: Uint16Array, rule: PruneRule): TrainedSplat {
293
+ const keep: number[] = []
294
+ for (let g = 0; g < s.n; g++) if (rule.minSeen == null || seen[g]! >= rule.minSeen) keep.push(g)
295
+ const rest = s.shCount * 3
296
+ const data = new Float32Array(keep.length * STRIDE)
297
+ const sh = new Float32Array(keep.length * rest)
298
+ keep.forEach((g, i) => {
299
+ data.set(s.data.subarray(g * STRIDE, (g + 1) * STRIDE), i * STRIDE)
300
+ sh.set(s.sh.subarray(g * rest, (g + 1) * rest), i * rest)
301
+ if (rule.maxNeedle != null) {
302
+ const b = i * STRIDE + F.scale
303
+ const logs = [data[b]!, data[b + 1]!, data[b + 2]!]
304
+ const order = [0, 1, 2].sort((p, q) => logs[q]! - logs[p]!)
305
+ const cap = logs[order[1]!]! + Math.log(rule.maxNeedle)
306
+ if (logs[order[0]!]! > cap) data[b + order[0]!] = cap
307
+ }
308
+ })
309
+ return { n: keep.length, data, camera: null, sh, shCount: s.shCount }
310
+ }
311
+
312
+ export type ViewScore = { name: string; psnr: number; ssim: number }
313
+
314
+ export async function scoreViews(s: TrainedSplat, colmap: Colmap, imagesDir: string, names: string[], shots?: { dir: string; names: Set<string> }): Promise<ViewScore[]> {
315
+ const byName = new Map(colmap.images.map((i) => [i.name, i]))
316
+ const out: ViewScore[] = []
317
+ for (const name of names) {
318
+ const img = byName.get(name)
319
+ if (img == null) throw new Error(`scoreViews: no camera for ${name}`)
320
+ const truth = await readRgb(join(imagesDir, name))
321
+ const view = renderView(s, colmap.camera, img)
322
+ out.push({ name, psnr: psnr(view, truth.rgb), ssim: ssim(view, truth.rgb, truth.width, truth.height) })
323
+ if (shots?.names.has(name) === true) await writeRgb(join(shots.dir, name), view, truth.width, truth.height)
324
+ }
325
+ return out
326
+ }
327
+
328
+ const mean = (xs: number[]) => (xs.length === 0 ? Number.NaN : xs.reduce((a, b) => a + b, 0) / xs.length)
329
+
330
+ /** mean scores of a set of views, all and per clip (an image named c<k>-…) */
331
+ export function summarize(scores: ViewScore[]): Record<string, { n: number; psnr: number; ssim: number }> {
332
+ const groups = new Map<string, ViewScore[]>([['all', scores]])
333
+ for (const v of scores) {
334
+ const clip = /^c(\d+)-/.exec(v.name)?.[1] ?? '?'
335
+ groups.set(`clip ${clip}`, [...(groups.get(`clip ${clip}`) ?? []), v])
336
+ }
337
+ const r: Record<string, { n: number; psnr: number; ssim: number }> = {}
338
+ for (const [k, vs] of groups)
339
+ r[k] = { n: vs.length, psnr: Number(mean(vs.map((v) => v.psnr)).toFixed(2)), ssim: Number(mean(vs.map((v) => v.ssim)).toFixed(3)) }
340
+ return r
341
+ }
342
+
343
+ if (import.meta.main) {
344
+ const args = process.argv.slice(2)
345
+ const flag = (name: string) => {
346
+ const i = args.indexOf(name)
347
+ return i < 0 ? undefined : args.splice(i, 2)[1]
348
+ }
349
+ const outDir = flag('--out')
350
+ const shotNames = flag('--shots')
351
+ const pruneSeen = flag('--prune-seen')
352
+ const pruneNeedle = flag('--prune-needle')
353
+ const [plyPath, colmapDir, splitPath] = args
354
+ if (plyPath == null || colmapDir == null || splitPath == null)
355
+ throw new Error('usage: bun examples/rvion/splatEval.ts <trained.ply> <colmap dir> <split.json> [--out dir] [--shots a.png,b.png] [--prune-seen n] [--prune-needle r]')
356
+ const t0 = performance.now()
357
+ const colmap = readColmap(join(colmapDir, 'sparse', '0'))
358
+ const split = JSON.parse(readFileSync(splitPath, 'utf8')) as { heldout: string[]; train: string[]; trainCheck?: string[] }
359
+ const byName = new Map(colmap.images.map((i) => [i.name, i]))
360
+ const trainImages = split.train.map((n) => byName.get(n)).filter((i) => i != null)
361
+ let splat = readTrained(new Uint8Array(readFileSync(plyPath)))
362
+ let seen = seenBy(splat, colmap.camera, trainImages)
363
+ const before = splatShape(splat, seen)
364
+ if (pruneSeen != null || pruneNeedle != null) {
365
+ splat = prune(splat, seen, { minSeen: pruneSeen == null ? undefined : Number(pruneSeen), maxNeedle: pruneNeedle == null ? undefined : Number(pruneNeedle) })
366
+ seen = seenBy(splat, colmap.camera, trainImages)
367
+ }
368
+ const shape = splatShape(splat, seen)
369
+ if (outDir != null) mkdirSync(outDir, { recursive: true })
370
+ const shots = outDir != null && shotNames != null ? { dir: outDir, names: new Set(shotNames.split(',')) } : undefined
371
+ const imagesDir = join(colmapDir, 'images')
372
+ const heldout = await scoreViews(splat, colmap, imagesDir, split.heldout, shots)
373
+ const train = await scoreViews(splat, colmap, imagesDir, split.trainCheck ?? [], shots)
374
+ const report = { ply: plyPath, shapeBeforePrune: before, shape, heldout: summarize(heldout), train: summarize(train), views: { heldout, train }, seconds: Math.round((performance.now() - t0) / 1000) }
375
+ if (outDir != null) {
376
+ writeFileSync(join(outDir, 'eval.json'), JSON.stringify(report, null, 1))
377
+ if (pruneSeen != null || pruneNeedle != null) writeFileSync(join(outDir, 'pruned.ply'), writeTrained(splat))
378
+ }
379
+ console.log(JSON.stringify({ shapeBeforePrune: before, shape, heldout: report.heldout, train: report.train, seconds: report.seconds }, null, 1))
380
+ }