Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(create): Kopf-Zuschnitt der Figurfotos im Swap-Bildschritt (Port des Web-Stands a582338f)

purple8f63111de862
diff --git a/eslint.config.js b/eslint.config.js
index 014a7e01..94ec60d7 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -71,6 +71,8 @@ export default defineConfig([
'.design-shots',
// Laeufe des Abnahmerahmens: der Trockenlauf legt dort den Vite-Cache seiner Vorschau ab (gebuendelte Abhaengigkeiten).
'mobile-tests/out',
+ // Kopien der Wasm-Dateien der Gesichtserkennung aus node_modules (scripts/copy-face-assets.mjs), in public/face/.gitignore.
+ 'public/face/vision_wasm_*',
// Rohdaten eines Geraeteberichts: Rumpfstuecke, die der Treiber als Funktionskoerper ausfuehrt
// (oberstes return und await), keine Module. Genau dieser eine Ordner, nicht mobile-docs.
'mobile-docs/r25/kurzpruefung-paket-10/ios/skripte',
diff --git a/package-lock.json b/package-lock.json
index 592ee55e..74192e73 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -9,6 +9,7 @@
"version": "3.1.0",
"license": "AGPL-3.0-only",
"dependencies": {
+ "@mediapipe/tasks-vision": "1.2.0",
"@pipecat-ai/client-js": "1.13.1",
"@pipecat-ai/websocket-transport": "1.7.2",
"@react-three/drei": "^10.7.7",
@@ -920,9 +921,9 @@
}
},
"node_modules/@mediapipe/tasks-vision": {
- "version": "0.10.17",
- "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-0.10.17.tgz",
- "integrity": "sha512-CZWV/q6TTe8ta61cZXjfnnHsfWIdFhms03M9T7Cnd5y2mdpylJM0rF1qRq+wsQVRMLz1OYPVEBU9ph2Bx8cxrg==",
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-1.2.0.tgz",
+ "integrity": "sha512-7+dr9GbGyTtcuLh11wE5TOn4dNFRncIT9oAWs72620WX99KW5FfzF6rFJ/ChTgXG9vJ6dCiE9FrEEY4CnwPWKQ==",
"license": "Apache-2.0"
},
"node_modules/@monogrid/gainmap-js": {
@@ -1387,6 +1388,12 @@
}
}
},
+ "node_modules/@react-three/drei/node_modules/@mediapipe/tasks-vision": {
+ "version": "0.10.17",
+ "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-0.10.17.tgz",
+ "integrity": "sha512-CZWV/q6TTe8ta61cZXjfnnHsfWIdFhms03M9T7Cnd5y2mdpylJM0rF1qRq+wsQVRMLz1OYPVEBU9ph2Bx8cxrg==",
+ "license": "Apache-2.0"
+ },
"node_modules/@react-three/fiber": {
"version": "9.5.0",
"resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-9.5.0.tgz",
diff --git a/package.json b/package.json
index c2f9986e..eaa351a6 100644
--- a/package.json
+++ b/package.json
@@ -25,8 +25,8 @@
},
"type": "module",
"scripts": {
- "dev": "vite",
- "build": "vite build",
+ "dev": "node scripts/copy-face-assets.mjs && vite",
+ "build": "node scripts/copy-face-assets.mjs && vite build",
"dev:mobile": "VITE_LU_BUILD_TARGET=mobile vite",
"build:mobile": "VITE_LU_BUILD_TARGET=mobile vite build",
"lint": "eslint .",
@@ -41,6 +41,7 @@
"test:e2e": "playwright test"
},
"dependencies": {
+ "@mediapipe/tasks-vision": "1.2.0",
"@pipecat-ai/client-js": "1.13.1",
"@pipecat-ai/websocket-transport": "1.7.2",
"@react-three/drei": "^10.7.7",
diff --git a/public/face/.gitignore b/public/face/.gitignore
new file mode 100644
index 00000000..d3a6fb8d
--- /dev/null
+++ b/public/face/.gitignore
@@ -0,0 +1,2 @@
+# Kopien aus node_modules (scripts/copy-face-assets.mjs), nicht einchecken.
+vision_wasm_*
diff --git a/public/face/blaze_face_short_range.tflite b/public/face/blaze_face_short_range.tflite
new file mode 100644
index 00000000..1b2b5220
Binary files /dev/null and b/public/face/blaze_face_short_range.tflite differ
diff --git a/scripts/copy-face-assets.mjs b/scripts/copy-face-assets.mjs
new file mode 100644
index 00000000..ab18b190
--- /dev/null
+++ b/scripts/copy-face-assets.mjs
@@ -0,0 +1,27 @@
+// Kopiert die Wasm-Dateien der Gesichtserkennung (MediaPipe Tasks Vision,
+// exakt gepinnt in package.json) aus node_modules nach public/face/, damit die
+// App sie selbst ausliefert und zur Laufzeit kein CDN braucht. Laeuft vor
+// `vite` und `vite build` (npm run dev/build, also auch vor dem Tauri-Build
+// ueber beforeBuildCommand), ohne Netz. Die Kopien stehen in .gitignore;
+// das Modell (blaze_face_short_range.tflite) liegt im Repository. Port des
+// Web-Stands (apps/web/scripts/copy-face-assets.mjs).
+//
+// node scripts/copy-face-assets.mjs
+import { copyFileSync, mkdirSync, statSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const here = dirname(fileURLToPath(import.meta.url))
+const require = createRequire(import.meta.url)
+const out = join(here, '..', 'public', 'face')
+mkdirSync(out, { recursive: true })
+
+// Nur die SIMD-Fassung: face-detect.ts laedt keine andere.
+for (const name of ['vision_wasm_internal.js', 'vision_wasm_internal.wasm']) {
+ const from = require.resolve(`@mediapipe/tasks-vision/${name}`)
+ const to = join(out, name)
+ let same = false
+ try { same = statSync(to).size === statSync(from).size && statSync(to).mtimeMs >= statSync(from).mtimeMs } catch { same = false }
+ if (!same) copyFileSync(from, to)
+}
diff --git a/src/lib/__tests__/desktop-bau-ohne-handy.test.ts b/src/lib/__tests__/desktop-bau-ohne-handy.test.ts
index cb48090f..7e4f9fde 100644
--- a/src/lib/__tests__/desktop-bau-ohne-handy.test.ts
+++ b/src/lib/__tests__/desktop-bau-ohne-handy.test.ts
@@ -80,9 +80,13 @@ describe('only a build that names the phone carries the mobile shell', () => {
const scripts = (JSON.parse(read('package.json')) as { scripts: Record<string, string> }).scripts
expect(scripts['dev:mobile']).toBe('VITE_LU_BUILD_TARGET=mobile vite')
expect(scripts['build:mobile']).toBe('VITE_LU_BUILD_TARGET=mobile vite build')
- // The desktop scripts are untouched.
+ // The desktop scripts name no phone. Before Vite they only copy the Wasm
+ // files of the face detection out of node_modules (head crop of the swap
+ // photos, scripts/copy-face-assets.mjs), nothing else.
expect(scripts.dev).not.toContain('VITE_LU_BUILD_TARGET')
- expect(scripts.build).toBe('vite build')
+ expect(scripts.build).not.toContain('VITE_LU_BUILD_TARGET')
+ expect(scripts.dev).toBe('node scripts/copy-face-assets.mjs && vite')
+ expect(scripts.build).toBe('node scripts/copy-face-assets.mjs && vite build')
const playwright = read('playwright.config.ts')
expect(playwright).toContain("env: { VITE_LU_BUILD_TARGET: 'mobile' }")
expect(playwright).toContain('baseURL: mobileOrigin')
diff --git a/src/lib/create/__tests__/head-crop.test.ts b/src/lib/create/__tests__/head-crop.test.ts
new file mode 100644
index 00000000..0cab225d
--- /dev/null
+++ b/src/lib/create/__tests__/head-crop.test.ts
@@ -0,0 +1,178 @@
+/**
+ * Kopf-Zuschnitt der Figurfotos fuer den Bildschritt des Swaps (14.11.2026):
+ * die Geometrie, die Wahl des Gesichts, der Rueckfall aufs ganze Foto und die
+ * festgehaltene Pruefsumme des Modells.
+ */
+import { createHash } from 'node:crypto'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { describe, it, expect, vi } from 'vitest'
+import { headCropBox, headCropPhoto, pickFace, HEAD_CROP, type FaceBox, type HeadCropDeps } from '../head-crop'
+import { FACE_MODEL_PATH, FACE_MODEL_SHA256, searchRegions } from '../face-detect'
+
+const face = (x: number, y: number, width: number, height: number, score = 0.9): FaceBox => ({ x, y, width, height, score })
+
+describe('headCropBox: Kopf, Haar, ein Stueck Hals', () => {
+ it('erweitert die Gesichtsbox auf 2,2 x Breite und 2,6 x Hoehe, oben mehr Rand als unten', () => {
+ // Gesicht 200 x 240 mitten in einem grossen Foto.
+ const box = headCropBox({ width: 2000, height: 3000 }, [face(900, 800, 200, 240)])!
+ expect(box.width).toBe(440)
+ expect(box.height).toBe(624)
+ // Waagrecht mittig um das Gesicht.
+ expect(box.x + box.width / 2).toBe(1000)
+ // Ueber dem Gesicht 1,2 x Hoehe (Haar), darunter 0,4 x Hoehe (Hals).
+ const above = 800 - box.y
+ const below = box.y + box.height - (800 + 240)
+ expect(above).toBe(288)
+ expect(below).toBe(96)
+ expect(above).toBeGreaterThan(below)
+ })
+
+ it('waagrecht verschoben, senkrecht gekappt: unten nie tiefer als der Hals', () => {
+ // Gesicht oben links: waagrecht rutscht der Ausschnitt ins Foto, oben
+ // fehlt das Stueck ueber dem Rand, unten endet er weiter am Hals.
+ const box = headCropBox({ width: 1200, height: 1600 }, [face(10, 20, 200, 240)])!
+ expect(box).toEqual({ x: 0, y: 0, width: 440, height: 20 + 240 + 96 })
+ // Gesicht unten rechts: rechts verschoben, unten gekappt.
+ const low = headCropBox({ width: 1200, height: 1600 }, [face(1000, 1300, 200, 240)])!
+ expect(low.x + low.width).toBe(1200)
+ expect(low.width).toBe(440)
+ expect(low.y).toBe(1300 - 288)
+ expect(low.y + low.height).toBe(1600)
+ })
+
+ it('kappt auf die Bildgrenzen, wenn der Ausschnitt breiter ist als das Foto', () => {
+ // Nahaufnahme: 2,2 x 400 = 880 > 700 Breite, die Hoehe passt.
+ const box = headCropBox({ width: 700, height: 2000 }, [face(150, 600, 400, 400)])!
+ expect(box.x).toBe(0)
+ expect(box.width).toBe(700)
+ expect(box.height).toBe(1040)
+ })
+
+ it('bleibt beim ganzen Foto, wenn der Ausschnitt kleiner als 256 px waere', () => {
+ expect(HEAD_CROP.minSide).toBe(256)
+ // 100 x 110 Gesicht: 220 x 286, zu schmal.
+ expect(headCropBox({ width: 1000, height: 1500 }, [face(400, 300, 100, 110)])).toBeNull()
+ // Knapp darueber geht es.
+ expect(headCropBox({ width: 1000, height: 1500 }, [face(400, 300, 117, 110)])).not.toBeNull()
+ })
+
+ it('bleibt beim ganzen Foto, wenn der Ausschnitt das ganze Foto waere', () => {
+ expect(headCropBox({ width: 500, height: 600 }, [face(100, 100, 300, 350)])).toBeNull()
+ })
+
+ it('ohne Gesicht, mit unsicherem Gesicht oder kaputten Massen: null', () => {
+ expect(headCropBox({ width: 1000, height: 1500 }, [])).toBeNull()
+ expect(headCropBox({ width: 1000, height: 1500 }, [face(400, 300, 200, 240, 0.3)])).toBeNull()
+ expect(headCropBox({ width: 0, height: 1500 }, [face(400, 300, 200, 240)])).toBeNull()
+ expect(headCropBox({ width: NaN, height: 1500 }, [face(400, 300, 200, 240)])).toBeNull()
+ })
+
+ it('liefert ganze Pixel innerhalb des Fotos', () => {
+ const box = headCropBox({ width: 1657, height: 2629 }, [face(512.4, 233.7, 201.3, 199.9)])!
+ for (const v of Object.values(box)) expect(Number.isInteger(v)).toBe(true)
+ expect(box.x).toBeGreaterThanOrEqual(0)
+ expect(box.y).toBeGreaterThanOrEqual(0)
+ expect(box.x + box.width).toBeLessThanOrEqual(1657)
+ expect(box.y + box.height).toBeLessThanOrEqual(2629)
+ })
+})
+
+describe('pickFace: das groesste sichere Gesicht', () => {
+ it('nimmt das groesste, nicht das erste', () => {
+ expect(pickFace([face(0, 0, 50, 50), face(100, 100, 200, 200), face(400, 0, 120, 120)])).toEqual(face(100, 100, 200, 200))
+ })
+ it('laesst unsichere Gesichter aus, auch wenn sie groesser sind', () => {
+ expect(pickFace([face(0, 0, 400, 400, 0.2), face(500, 0, 150, 150, 0.8)])).toEqual(face(500, 0, 150, 150, 0.8))
+ })
+ it('ein groesseres, aber deutlich unsichereres Scheingesicht verliert (echter Lauf sam-altman.png)', () => {
+ // Gemessen am 14.11.2026 im Webview-Lauf: Gesicht oben, Scheingesicht auf
+ // Pullover und Haenden.
+ const echt = face(447, 255, 378, 378, 0.826)
+ const schein = face(234, 1163, 443, 443, 0.521)
+ expect(pickFace([echt, schein])).toEqual(echt)
+ expect(pickFace([schein, echt])).toEqual(echt)
+ const box = headCropBox({ width: 1657, height: 2629 }, [schein, echt])!
+ // Der Ausschnitt endet am Hals, nicht im Bauch.
+ expect(box.y).toBe(0)
+ expect(box.y + box.height).toBe(Math.round(255 + 378 * 1.4))
+ })
+ it('unter fast gleich sicheren Gesichtern bleibt es das groesste', () => {
+ expect(pickFace([face(0, 0, 100, 100, 0.9), face(200, 0, 200, 200, 0.85)])).toEqual(face(200, 0, 200, 200, 0.85))
+ })
+ it('bei gleicher Groesse das sicherere', () => {
+ expect(pickFace([face(0, 0, 100, 100, 0.6), face(200, 0, 100, 100, 0.95)])!.score).toBe(0.95)
+ })
+ it('leer: null', () => {
+ expect(pickFace([])).toBeNull()
+ })
+})
+
+describe('headCropPhoto: Rueckfall aufs ganze Foto', () => {
+ const photo = new Blob(['ganzes foto'], { type: 'image/png' })
+
+ it('schneidet zu, wenn ein Gesicht da ist', async () => {
+ const cut = vi.fn(async () => new Blob(['kopf'], { type: 'image/png' }))
+ const deps: HeadCropDeps = { detect: async () => ({ width: 1657, height: 2629, faces: [face(600, 200, 220, 260)] }), cut }
+ const out = await headCropPhoto(photo, deps)
+ expect(await out.text()).toBe('kopf')
+ expect(cut).toHaveBeenCalledWith(photo, { x: 468, y: 0, width: 484, height: 200 + 260 + 104 })
+ })
+
+ it('ohne Gesicht: das ganze Foto, nichts geschnitten', async () => {
+ const cut = vi.fn(async () => new Blob(['kopf']))
+ const out = await headCropPhoto(photo, { detect: async () => ({ width: 800, height: 1200, faces: [] }), cut })
+ expect(out).toBe(photo)
+ expect(cut).not.toHaveBeenCalled()
+ })
+
+ it('wenn die Erkennung nicht laedt: das ganze Foto', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const out = await headCropPhoto(photo, { detect: async () => { throw new Error('wasm failed') }, cut: async () => new Blob(['x']) })
+ expect(out).toBe(photo)
+ warn.mockRestore()
+ })
+
+ it('wenn das Schneiden scheitert: das ganze Foto', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const out = await headCropPhoto(photo, {
+ detect: async () => ({ width: 1657, height: 2629, faces: [face(600, 200, 220, 260)] }),
+ cut: async () => { throw new Error('canvas') },
+ })
+ expect(out).toBe(photo)
+ warn.mockRestore()
+ })
+
+ it('wenn die Erkennung haengt: nach der Wartezeit das ganze Foto', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const out = await headCropPhoto(photo, { detect: () => new Promise(() => {}), cut: async () => new Blob(['x']) }, 20)
+ expect(out).toBe(photo)
+ warn.mockRestore()
+ })
+
+ it('ohne Browser (kein createImageBitmap): der echte Weg faellt aufs ganze Foto zurueck', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ expect(await headCropPhoto(photo)).toBe(photo)
+ warn.mockRestore()
+ })
+})
+
+describe('Modell und Suchbereiche', () => {
+ it('das Modell im Repository hat die festgehaltene Pruefsumme', () => {
+ const file = join(__dirname, '..', '..', '..', '..', 'public', FACE_MODEL_PATH)
+ expect(createHash('sha256').update(readFileSync(file)).digest('hex')).toBe(FACE_MODEL_SHA256)
+ expect(FACE_MODEL_SHA256).toBe('b4578f35940bf5a1a655214a1cce5cab13eba73c1297cd78e1a04c2380b0152f')
+ })
+
+ it('sucht erst im ganzen Foto, bei hohen Fotos dann oben', () => {
+ const r = searchRegions(1657, 2629)
+ expect(r[0]).toEqual({ x: 0, y: 0, width: 1657, height: 2629 })
+ expect(r[1]).toEqual({ x: 0, y: 0, width: 1657, height: 1657 })
+ for (const b of r) {
+ expect(b.x + b.width).toBeLessThanOrEqual(1657)
+ expect(b.y + b.height).toBeLessThanOrEqual(2629)
+ }
+ // Ein quadratisches Foto bekommt kein eigenes oberes Quadrat.
+ expect(searchRegions(1000, 1000).filter((b) => b.width === 1000)).toHaveLength(1)
+ })
+})
diff --git a/src/lib/create/__tests__/swap-chain.test.ts b/src/lib/create/__tests__/swap-chain.test.ts
index ef3f0732..690d23fd 100644
--- a/src/lib/create/__tests__/swap-chain.test.ts
+++ b/src/lib/create/__tests__/swap-chain.test.ts
@@ -149,6 +149,42 @@ describe('one click: frame, then video, then done', () => {
})
})
+describe('head crop of the photos (14.11.2026)', () => {
+ it('the frame step gets the cut photos, the video step does not', async () => {
+ const f = fakeDeps((s) => ok(s.kind === 'image' ? 'https://r/frame.jpg' : 'https://r/video.mp4'))
+ const blobs: Blob[] = []
+ const cropped: Blob[] = []
+ f.deps.uploadInput = async (b, role) => { blobs.push(b); f.uploads.push(role); return `u/${f.uploads.length}-${role}` }
+ f.deps.cropFace = async (b) => { const out = new Blob(['head'], { type: b.type }); cropped.push(out); return out }
+ const s = start()
+ const video = structuredClone(s.videoSubmit)
+ await startSwapChain(s, f.deps)
+ // Uploaded: the first frame (whole), then the two heads.
+ expect(blobs).toHaveLength(3)
+ expect(cropped).toHaveLength(2)
+ expect(cropped).not.toContain(blobs[0])
+ expect(blobs.slice(1)).toEqual(cropped)
+ expect(params(f.submits[0]).image_paths).toEqual(['u/1-source', 'u/2-source', 'u/3-source'])
+ // The video: the job from outside, unchanged, plus the result of the
+ // frame step as source_path. None of the heads is in it.
+ const { source_path, ...rest } = params(f.submits[1])
+ expect(rest).toEqual(video.params)
+ expect(source_path).toBe('a/1-image')
+ expect(JSON.stringify(f.submits[1])).not.toMatch(/u\/[23]-source/)
+ })
+
+ it('without a face (crop gives the photo back) the whole photo goes up', async () => {
+ const f = fakeDeps((s) => ok(s.kind === 'image' ? 'https://r/frame.jpg' : 'https://r/video.mp4'))
+ const blobs: Blob[] = []
+ const given: Blob[] = []
+ f.deps.uploadInput = async (b, role) => { blobs.push(b); f.uploads.push(role); return `u/${f.uploads.length}-${role}` }
+ f.deps.cropFace = async (b) => { given.push(b); return b }
+ await startSwapChain(start(), f.deps)
+ expect(blobs.slice(1)).toEqual(given)
+ expect(swapChainStore.getState().chain!.stage).toBe('done')
+ })
+})
+
describe('Check first frame before video', () => {
it('stops after the frame; the video starts only on Continue', async () => {
const f = fakeDeps((s) => ok(s.kind === 'image' ? 'https://r/frame.jpg' : 'https://r/video.mp4'))
diff --git a/src/lib/create/__tests__/swap.test.ts b/src/lib/create/__tests__/swap.test.ts
index 3110a5db..3b5e2329 100644
--- a/src/lib/create/__tests__/swap.test.ts
+++ b/src/lib/create/__tests__/swap.test.ts
@@ -482,6 +482,22 @@ describe('the frame step', () => {
expect(calls).toEqual([])
})
+ it('the photos go up cut to the head, the first frame does not (head crop, 14.11.2026)', async () => {
+ const sent: string[] = []
+ const cropped: string[] = []
+ const deps = {
+ uploadInput: async (b: Blob, role: string) => { sent.push(`${role} ${await b.text()}`); return `u/${sent.length}` },
+ cropFace: async (b: Blob) => { cropped.push(b.type); return new Blob([`head ${cropped.length}`], { type: 'image/png' }) },
+ submitCloudJob: async () => ({ id: 'job-9' }),
+ pollJob: async (id: string) => ({ id, status: 'succeeded', result_url: 'https://ours/x.jpg' } as never),
+ cancelJob: async () => ({ status: 'canceled' }),
+ }
+ await runSwapFrame(request({ figures: [{ imageUrl: FOTO, role: '' }, { imageUrl: FOTO, role: '' }] }), deps as never)
+ // Each photo cut once, the first frame of the video never.
+ expect(cropped).toHaveLength(2)
+ expect(sent.map((s) => s.includes('head'))).toEqual([false, true, true])
+ })
+
it('another video, photo, mark or role makes the built frame expire', () => {
const fig = (url: string, role = '', mark: { x: number; y: number } | null = null) => ({ image: { url }, role, mark })
const base = swapKeyOf('blob:v1', [fig('data:a')])
diff --git a/src/lib/create/face-detect.ts b/src/lib/create/face-detect.ts
new file mode 100644
index 00000000..272c107d
--- /dev/null
+++ b/src/lib/create/face-detect.ts
@@ -0,0 +1,130 @@
+// Gesichtserkennung im Webview fuer den Kopf-Zuschnitt (head-crop.ts), Port
+// des Web-Stands (apps/web/lib/create/face-detect.ts).
+//
+// MediaPipe Tasks Vision (Google, Apache-2.0, im package.json exakt gepinnt)
+// mit dem Modell BlazeFace short range. Alles kommt aus der App selbst:
+// die Wasm-Dateien kopiert scripts/copy-face-assets.mjs vor dev und build aus
+// node_modules nach public/face/, das Modell liegt dort im Repository. Zur
+// Laufzeit geht keine Anfrage an ein CDN.
+//
+// Diese Datei wird nur ueber import() aus head-crop.ts geladen, also erst,
+// wenn der Bildschritt des Swaps Fotos hochlaedt.
+
+import type { CropBox, FaceBox } from './head-crop'
+
+/** Wo die Dateien liegen (public/face/). */
+export const FACE_ASSET_BASE = '/face'
+export const FACE_MODEL_PATH = `${FACE_ASSET_BASE}/blaze_face_short_range.tflite`
+
+/** SHA-256 des Modells, wie es am 14.11.2026 von der offiziellen Quelle kam:
+ * storage.googleapis.com/mediapipe-models/face_detector/blaze_face_short_range/float16/1/blaze_face_short_range.tflite
+ * Ein anderes Modell wird nicht geladen; dann geht das ganze Foto hoch. */
+export const FACE_MODEL_SHA256 = 'b4578f35940bf5a1a655214a1cce5cab13eba73c1297cd78e1a04c2380b0152f'
+
+interface Detector {
+ detect: (image: ImageBitmap | HTMLCanvasElement | OffscreenCanvas) => { detections: { categories: { score: number }[]; boundingBox?: { originX: number; originY: number; width: number; height: number } }[] }
+}
+
+let loading: Promise<Detector> | null = null
+
+async function sha256Hex(buf: ArrayBuffer): Promise<string> {
+ const d = await crypto.subtle.digest('SHA-256', buf)
+ return Array.from(new Uint8Array(d), (b) => b.toString(16).padStart(2, '0')).join('')
+}
+
+async function load(): Promise<Detector> {
+ const res = await fetch(FACE_MODEL_PATH)
+ if (!res.ok) throw new Error(`face model: HTTP ${res.status}`)
+ const model = await res.arrayBuffer()
+ if ((await sha256Hex(model)) !== FACE_MODEL_SHA256) throw new Error('face model: checksum mismatch')
+ const { FaceDetector } = await import('@mediapipe/tasks-vision')
+ // Nur die SIMD-Fassung liegt aus; jeder heutige Browser kann sie. Ohne
+ // SIMD scheitert das Laden, und das ganze Foto geht hoch.
+ return FaceDetector.createFromOptions(
+ { wasmLoaderPath: `${FACE_ASSET_BASE}/vision_wasm_internal.js`, wasmBinaryPath: `${FACE_ASSET_BASE}/vision_wasm_internal.wasm` },
+ { baseOptions: { modelAssetBuffer: new Uint8Array(model), delegate: 'CPU' }, runningMode: 'IMAGE', minDetectionConfidence: 0.5 },
+ ) as unknown as Promise<Detector>
+}
+
+/** Die Erkennung, einmal geladen. Scheitert das Laden, versucht der naechste
+ * Aufruf es neu. */
+function detector(): Promise<Detector> {
+ if (!loading) loading = load().catch((err) => { loading = null; throw err })
+ return loading
+}
+
+function canvasOf(width: number, height: number): OffscreenCanvas | HTMLCanvasElement {
+ if (typeof OffscreenCanvas !== 'undefined') return new OffscreenCanvas(width, height)
+ const c = document.createElement('canvas')
+ c.width = width
+ c.height = height
+ return c
+}
+
+function context2d(c: OffscreenCanvas | HTMLCanvasElement) {
+ const ctx = c.getContext('2d') as CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null
+ if (!ctx) throw new Error('no 2d canvas')
+ return ctx
+}
+
+/** Die Bereiche, in denen gesucht wird: erst das ganze Foto. BlazeFace short
+ * range sieht ein Bild mit 128 Pixeln Kantenlaenge; auf einem Ganzkoerperfoto
+ * ist das Gesicht darin zu klein. Dann das obere Quadrat (dort steht bei
+ * einem hohen Foto der Kopf) und dessen obere Haelften links, mittig, rechts. */
+export function searchRegions(width: number, height: number): CropBox[] {
+ const out: CropBox[] = [{ x: 0, y: 0, width, height }]
+ const side = Math.min(width, height)
+ if (height > width * 1.2) out.push({ x: 0, y: 0, width: side, height: side })
+ const half = Math.round(side / 2)
+ if (half >= 128) {
+ for (const x of [0, Math.round((width - half) / 2), width - half]) {
+ for (const y of [0, Math.round(half / 2)]) out.push({ x, y, width: half, height: half })
+ }
+ }
+ return out
+}
+
+function facesIn(det: Detector, source: ImageBitmap, region: CropBox, full: boolean): FaceBox[] {
+ let input: ImageBitmap | OffscreenCanvas | HTMLCanvasElement = source
+ if (!full) {
+ const c = canvasOf(region.width, region.height)
+ context2d(c).drawImage(source, region.x, region.y, region.width, region.height, 0, 0, region.width, region.height)
+ input = c
+ }
+ return det.detect(input).detections.flatMap((d) => d.boundingBox
+ ? [{ x: d.boundingBox.originX + region.x, y: d.boundingBox.originY + region.y, width: d.boundingBox.width, height: d.boundingBox.height, score: d.categories[0]?.score ?? 0 }]
+ : [])
+}
+
+/** Masse des Fotos und die Gesichter darin, in Pixeln des Fotos. */
+export async function detectFaces(photo: Blob): Promise<{ width: number; height: number; faces: FaceBox[] }> {
+ const bitmap = await createImageBitmap(photo)
+ try {
+ const det = await detector()
+ const { width, height } = bitmap
+ for (const [i, region] of searchRegions(width, height).entries()) {
+ const faces = facesIn(det, bitmap, region, i === 0)
+ if (faces.some((f) => f.score >= 0.5)) return { width, height, faces }
+ }
+ return { width, height, faces: [] }
+ } finally {
+ bitmap.close()
+ }
+}
+
+/** Schneidet den Ausschnitt aus dem Foto: JPEG bleibt JPEG, alles andere wird
+ * PNG (wie die Fotos bisher hochgingen). */
+export async function cutPhoto(photo: Blob, box: CropBox): Promise<Blob> {
+ const bitmap = await createImageBitmap(photo)
+ try {
+ const c = canvasOf(box.width, box.height)
+ context2d(c).drawImage(bitmap, box.x, box.y, box.width, box.height, 0, 0, box.width, box.height)
+ const type = photo.type === 'image/jpeg' ? 'image/jpeg' : 'image/png'
+ if ('convertToBlob' in c) return await c.convertToBlob({ type, quality: 0.92 })
+ return await new Promise<Blob>((resolve, reject) => {
+ c.toBlob((b) => (b ? resolve(b) : reject(new Error('canvas export failed'))), type, 0.92)
+ })
+ } finally {
+ bitmap.close()
+ }
+}
diff --git a/src/lib/create/head-crop.ts b/src/lib/create/head-crop.ts
new file mode 100644
index 00000000..16f283d8
--- /dev/null
+++ b/src/lib/create/head-crop.ts
@@ -0,0 +1,137 @@
+// Kopf-Zuschnitt der Figurfotos fuer den Bildschritt des Swaps (14.11.2026),
+// Port des Web-Stands (apps/web/lib/create/head-crop.ts, a582338f).
+//
+// Echttest vom 14.11.: Mit Ganzkoerperfotos uebernahm der offene Editor oft
+// Kleidung und Koerper der Fotos statt der Szene. Mit Fotos, die nur Kopf,
+// ganzes Haar und ein Stueck Hals zeigen, blieb die Szene erhalten. Darum
+// schneidet der Browser jedes Figurfoto vor dem Hochladen auf den Kopf zu,
+// mit einer Gesichtserkennung, die hier im Browser laeuft (face-detect.ts,
+// lazy geladen). Findet sie kein Gesicht oder laedt sie nicht, geht das ganze
+// Foto hoch wie bisher. Nur die Gesichtsvorlagen des Editors werden
+// beschnitten; der Videoschritt bekommt weiter, was er heute bekommt.
+//
+// Hier steht die Geometrie als reine Funktion und der Ablauf mit
+// austauschbaren Helfern, damit beides ohne Browser pruefbar ist.
+
+/** Ein gefundenes Gesicht in Pixeln des Fotos. */
+export interface FaceBox { x: number; y: number; width: number; height: number; score: number }
+
+/** Der Ausschnitt, ganzzahlig, in Pixeln des Fotos. */
+export interface CropBox { x: number; y: number; width: number; height: number }
+
+export const HEAD_CROP = {
+ /** Breite des Ausschnitts als Vielfaches der Gesichtsbreite. */
+ widen: 2.2,
+ /** Hoehe des Ausschnitts als Vielfaches der Gesichtshoehe. */
+ tall: 2.6,
+ /** Rand ueber dem Gesicht (Stirn, Haar) als Vielfaches der Gesichtshoehe.
+ * Der Rest der Hoehe liegt unter der Box (Hals): 2,6 = 1,2 + 1 + 0,4.
+ * BlazeFace legt die Box etwas unter das Kinn; mehr als 0,4 darunter
+ * zeigt im Echttest (14.11.) schon viel Kleidung. */
+ above: 1.2,
+ /** Kleinere Ausschnitte (Breite oder Hoehe) bleiben das ganze Foto. */
+ minSide: 256,
+ /** Deckt der Ausschnitt mindestens diesen Teil der Flaeche, bleibt es das
+ * ganze Foto (es ist schon ein Kopfbild). */
+ keepWhole: 0.9,
+ /** Gesichter unter dieser Sicherheit zaehlen nicht. */
+ minScore: 0.5,
+ /** Nur Gesichter, die hoechstens so viel unsicherer sind als das sicherste,
+ * kommen fuer die Wahl nach Groesse in Frage. */
+ scoreBand: 0.1,
+} as const
+
+/** Das sicherste Gesicht; unter fast gleich sicheren (scoreBand) das
+ * groesste, bei gleicher Groesse das sicherere.
+ *
+ * Echter Lauf am Desktop (14.11.2026, sam-altman.png, 1657 x 2629): BlazeFace
+ * fand das echte Gesicht (378 px, 0,83) und auf Pullover und Haenden ein
+ * groesseres Scheingesicht (443 px, 0,52). Nach Groesse allein wurde der
+ * Bauch ausgeschnitten. */
+export function pickFace(faces: readonly FaceBox[]): FaceBox | null {
+ const ok = faces.filter((f) => f.score >= HEAD_CROP.minScore && f.width > 0 && f.height > 0)
+ if (!ok.length) return null
+ const top = Math.max(...ok.map((f) => f.score))
+ let best: FaceBox | null = null
+ for (const f of ok) {
+ if (f.score < top - HEAD_CROP.scoreBand) continue
+ if (!best) { best = f; continue }
+ const a = f.width * f.height
+ const b = best.width * best.height
+ if (a > b || (a === b && f.score > best.score)) best = f
+ }
+ return best
+}
+
+/** Legt ein Stueck der Laenge `len` moeglichst bei `start` in [0, max]:
+ * erst verschieben, dann, wenn es nicht passt, kuerzen. Waagrecht, wo ein
+ * verschobener Rand nur Hintergrund oder Schulter zeigt. */
+function fit(start: number, len: number, max: number): [number, number] {
+ if (len >= max) return [0, max]
+ const s = Math.min(Math.max(start, 0), max - len)
+ return [s, len]
+}
+
+/** Der Kopfausschnitt fuer ein Foto, oder null fuer das ganze Foto (kein
+ * sicheres Gesicht, Ausschnitt zu klein oder fast so gross wie das Foto). */
+export function headCropBox(size: { width: number; height: number }, faces: readonly FaceBox[]): CropBox | null {
+ const W = Math.floor(size.width)
+ const H = Math.floor(size.height)
+ if (!(W > 0) || !(H > 0)) return null
+ const face = pickFace(faces)
+ if (!face) return null
+ const w = face.width * HEAD_CROP.widen
+ const h = face.height * HEAD_CROP.tall
+ const left = face.x + face.width / 2 - w / 2
+ const top = face.y - face.height * HEAD_CROP.above
+ const [x, cw] = fit(Math.round(left), Math.round(w), W)
+ // Senkrecht wird gekappt, nicht verschoben: Stoesst das Haar oben an den
+ // Rand, rutschte ein verschobener Ausschnitt unten in die Kleidung.
+ const y = Math.max(0, Math.round(top))
+ const ch = Math.min(H, Math.round(top + h)) - y
+ if (cw < HEAD_CROP.minSide || ch < HEAD_CROP.minSide) return null
+ // Fast das ganze Foto: Schneiden bringt nichts, das Foto bleibt, wie es ist.
+ if (cw * ch >= W * H * HEAD_CROP.keepWhole) return null
+ return { x, y, width: cw, height: ch }
+}
+
+/** Was der Ablauf vom Browser braucht. */
+export interface HeadCropDeps {
+ /** Masse des Fotos und die Gesichter darin. Wirft, wenn die Erkennung
+ * nicht laedt oder das Foto nicht lesbar ist. */
+ detect: (photo: Blob) => Promise<{ width: number; height: number; faces: FaceBox[] }>
+ /** Schneidet den Ausschnitt aus dem Foto, im Format des Fotos. */
+ cut: (photo: Blob, box: CropBox) => Promise<Blob>
+}
+
+/** Laenger wartet der Upload nicht auf die Erkennung (erstes Laden der
+ * Erkennung eingeschlossen); danach geht das ganze Foto hoch. */
+export const HEAD_CROP_TIMEOUT_MS = 20_000
+
+function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const t = setTimeout(() => reject(new Error('face detection timed out')), ms)
+ p.then((v) => { clearTimeout(t); resolve(v) }, (e) => { clearTimeout(t); reject(e) })
+ })
+}
+
+/** Schneidet ein Figurfoto auf den Kopf zu. Gibt bei jedem Fehler und ohne
+ * Gesicht das Foto unveraendert zurueck; wirft nie. */
+export async function headCropPhoto(photo: Blob, deps: HeadCropDeps = browserHeadCrop, timeoutMs = HEAD_CROP_TIMEOUT_MS): Promise<Blob> {
+ try {
+ const found = await withTimeout(deps.detect(photo), timeoutMs)
+ const box = headCropBox(found, found.faces)
+ if (!box) return photo
+ return await deps.cut(photo, box)
+ } catch (err) {
+ console.warn('head crop skipped, uploading the whole photo:', err instanceof Error ? err.message : err)
+ return photo
+ }
+}
+
+/** Der Weg im Browser: die Erkennung kommt erst beim ersten Bedarf, als
+ * eigener Teil des Bundles. */
+export const browserHeadCrop: HeadCropDeps = {
+ detect: async (photo) => (await import('./face-detect')).detectFaces(photo),
+ cut: async (photo, box) => (await import('./face-detect')).cutPhoto(photo, box),
+}
diff --git a/src/lib/create/swap-chain.ts b/src/lib/create/swap-chain.ts
index 35db6f19..291956d8 100644
--- a/src/lib/create/swap-chain.ts
+++ b/src/lib/create/swap-chain.ts
@@ -28,6 +28,7 @@ import {
SWAP_CONSENT_MISSING, SWAP_FRAME_MODEL, SWAP_FRAME_OPEN_MODEL, type SwapMark,
} from '../render/swap'
import { adoptResult, describeSubmitError, failedJobText, type RunDeps } from './engine'
+import { headCropPhoto } from './head-crop'
import { swapFrameCredits, swapFrameSubmit } from './swap-frame'
import { lipsyncFailedText } from './lipsync-chain'
@@ -127,6 +128,9 @@ export const SWAP_REFUSED_TEXT = 'The first-frame model refused this image. Noth
export interface SwapChainDeps extends RunDeps {
uploadInput: (file: Blob, role: UploadRole) => Promise<string>
+ /** Cuts a photo down to the head for the frame step (head-crop.ts). Left
+ * out, it is the face detection in the webview. */
+ cropFace?: (photo: Blob) => Promise<Blob>
adoptInput: (jobId: string, role: AdoptRole) => Promise<string>
/** A finished result (video, or video with the new voice) into the gallery. */
onResult?: (job: CloudJob) => void
@@ -190,7 +194,12 @@ export async function startSwapChain(start: SwapChainStart, deps: SwapChainDeps)
try {
const framePath = await deps.uploadInput(dataUrlToBlob(start.frame!.url), 'source')
const figurePaths: string[] = []
- for (const f of start.figures) figurePaths.push(await deps.uploadInput(dataUrlToBlob(f.image!.url), 'source'))
+ // The photos are only the editor's face references: head and hair, else it
+ // takes over clothes and body (head-crop.ts). The video step gets its image
+ // from the frame step and its job from outside (videoSubmit), neither
+ // touched by this.
+ const crop = deps.cropFace ?? headCropPhoto
+ for (const f of start.figures) figurePaths.push(await deps.uploadInput(await crop(dataUrlToBlob(f.image!.url)), 'source'))
const lipsync = start.lipsync
? {
model: start.lipsync.model,
diff --git a/src/lib/create/swap-frame.ts b/src/lib/create/swap-frame.ts
index 82f8b3c2..96371dee 100644
--- a/src/lib/create/swap-frame.ts
+++ b/src/lib/create/swap-frame.ts
@@ -21,6 +21,7 @@ import {
swapFigureRoles, swapFrameKey, swapFrameOptionsFor, swapFramePrompt, swapMaxPeople,
SWAP_CONSENT_MISSING, SWAP_FRAME_MODEL, type SwapMark,
} from '../render/swap'
+import { headCropPhoto } from './head-crop'
/** A person as the frame step reads it. */
export interface SwapFrameFigure { imageUrl: string | null; role: string; mark?: SwapMark | null }
@@ -109,6 +110,9 @@ export interface SwapFrameDeps {
pollJob: (id: string, opts: { signal?: AbortSignal; timeoutMs?: number }) => Promise<CloudJob>
cancelJob: (id: string) => Promise<unknown>
uploadInput: (file: Blob, role: UploadRole) => Promise<string>
+ /** Cuts a photo down to the head (head-crop.ts). Left out, it is the face
+ * detection in the webview. */
+ cropFace?: (photo: Blob) => Promise<Blob>
signal?: AbortSignal
onStep?: (text: string) => void
}
@@ -121,7 +125,10 @@ export async function runSwapFrame(req: SwapFrameRequest, deps: SwapFrameDeps):
deps.onStep?.('Uploading…')
const framePath = await deps.uploadInput(dataUrlToBlob(req.frame!.url), 'source')
const figurePaths: string[] = []
- for (const f of req.figures) figurePaths.push(await deps.uploadInput(dataUrlToBlob(f.imageUrl!), 'source'))
+ // Only head and hair as the editor's face reference, else it takes over the
+ // clothes and the body of the photos (head-crop.ts).
+ const crop = deps.cropFace ?? headCropPhoto
+ for (const f of req.figures) figurePaths.push(await deps.uploadInput(await crop(dataUrlToBlob(f.imageUrl!)), 'source'))
if (deps.signal?.aborted) throw new Error('Canceled.')
deps.onStep?.('Building the first frame…')
const { id } = await deps.submitCloudJob(swapFrameSubmit(framePath, figurePaths, req))
diff --git a/src/lib/render/__tests__/data-url-fetch-guard.test.ts b/src/lib/render/__tests__/data-url-fetch-guard.test.ts
index c3322399..f2648f2e 100644
--- a/src/lib/render/__tests__/data-url-fetch-guard.test.ts
+++ b/src/lib/render/__tests__/data-url-fetch-guard.test.ts
@@ -33,6 +33,9 @@ const SERVER_ONLY: Record<string, Record<string, string>> = {
// the last preview as /api/loras signs it (https). A saved photo character
// is read from its own blobs and never comes here.
'components/create/experimental/hub/hubCharacters.ts': { 'c.image': 'signed https picture of a cloud character from /api/loras' },
+ // The head crop of the swap photos: the face model the app serves itself
+ // from public/face/, a fixed path, never a photo.
+ 'lib/create/face-detect.ts': { FACE_MODEL_PATH: 'the face model under /face/, a fixed path of the app' },
// The phone. None of the seven reads media; each sends a request to a server address the app builds.
'lib/lu-native.ts': { 'request.url': 'the browser stand-in of the native request to a paired desktop: method, headers and body to its http(s) address' },
'mobile/remote/remoteClient.ts': { url: 'API routes of a paired desktop, built from its http(s) base address' },