feat: add browser talking avatar pipeline

This commit is contained in:
haixin.yang committed 2026-07-10 18:09:05 +08:00
1 parent ebcb6e880a
commit 16c0bf7f2e
21 files changed
+1746 -22

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
# LivePortrait browser ONNX port
## Pinned baseline
- Repository: `dyicnc/Live-Portrait-ONNX` (third-party mirror, not an official LivePortrait certification)
- Revision: `e6c5d2407593a39f29c92ffd5ea3eaf5e59d52a1`
- Runtime: `onnxruntime-web@1.27.0`
- Minimum split pipeline: appearance extractor, motion extractor, lip retargeter, stitching, warping, and SPADE generator
- Combined generator SHA-256: `44effc5f2129c03353feb56bb8db7828346c36e81ffbacb4ab0622b3d91d2c77`
## Graph audit
The opset-20 combined generator has 277 nodes, including 13 rank-5 Conv nodes and 2 rank-5 GridSample nodes. The repository's Linux `.so` plugin cannot run in a browser. The browser correctness path therefore uses the split models and ONNX Runtime Web WASM for the 3D warping stage.
## Acceptance result
- Test portrait: `老外戴眼镜中年人物肖像生成-modnet.png`, 819×1024 RGBA.
- Node smoke test: appearance, motion, lip retargeting, stitching, 3D warping, and 512×512 SPADE rendering passed.
- In-app browser test: model loading, real progress reporting, WASM inference, PNG creation, reusable media insertion, and visual-track replacement passed.
- Browser output: `liveportrait-browser-acceptance.png`, 512×512.
- Browser console errors after completion: 0.
The explicit bundled `ort-wasm-simd-threaded.wasm` path is required. Without it, Vite's HTML fallback produces the `expected magic word ... found 3c 21 64 6f` error.
## Remaining gates
- Replace or accelerate the slow 3D WASM path with WebGPU.
- Select and validate a real audio-to-motion ONNX model.
- Generate temporally consistent frames from audio, then encode and replace the visual track with a video.
- Keep full talking-video generation/export locked until these gates pass; do not substitute handcrafted visemes or simulated mouth motion.
+21
View File
@@ -16,6 +16,7 @@
"@vitejs/plugin-react": "5.0.4",
"fflate": "^0.8.3",
"kokoro-js": "^1.2.1",
"onnxruntime-web": "^1.27.0",
"react": "19.2.0",
"react-dom": "19.2.0",
"vite": "6.4.2"
@@ -2346,6 +2347,26 @@
"tar": "^7.0.1"
}
},
"node_modules/onnxruntime-web": {
"version": "1.27.0",
"resolved": "https://registry.npmmirror.com/onnxruntime-web/-/onnxruntime-web-1.27.0.tgz",
"integrity": "sha512-ogDLsqIozHZwifPuN37OproAo0byX6t43/bP8GzeZWBWD6MOGExswFAx3up4NS/vvWBOg2u2PXomDt3rMmdQSg==",
"license": "MIT",
"dependencies": {
"flatbuffers": "^25.1.24",
"guid-typescript": "^1.0.9",
"long": "^5.2.3",
"onnxruntime-common": "1.27.0",
"platform": "^1.3.6",
"protobufjs": "^7.2.4"
}
},
"node_modules/onnxruntime-web/node_modules/onnxruntime-common": {
"version": "1.27.0",
"resolved": "https://registry.npmmirror.com/onnxruntime-common/-/onnxruntime-common-1.27.0.tgz",
"integrity": "sha512-3KxL5wIVqa8Ex08jxSzncm9CMgw8CjOFyOQ7SxvG9o0cVLlhTNKXyIQuTbtX4tGPJEf73OER2xrjt4HJSBL4ow==",
"license": "MIT"
},
"node_modules/phonemizer": {
"version": "1.2.1",
"resolved": "https://registry.npmmirror.com/phonemizer/-/phonemizer-1.2.1.tgz",
+1
View File
@@ -17,6 +17,7 @@
"@vitejs/plugin-react": "5.0.4",
"fflate": "^0.8.3",
"kokoro-js": "^1.2.1",
"onnxruntime-web": "^1.27.0",
"react": "19.2.0",
"react-dom": "19.2.0",
"vite": "6.4.2"
+2 -1
View File
@@ -43,7 +43,8 @@ function isHuggingFaceModelRequest(url) {
function isRuntimeAssetRequest(url) {
if (url.origin === self.location.origin) {
return url.pathname.startsWith("/assets/") && hasCacheableExtension(url.pathname);
return url.pathname.startsWith("/models/")
|| (url.pathname.startsWith("/assets/") && hasCacheableExtension(url.pathname));
}
return CDN_HOSTS.has(url.hostname) && (
+143
View File
@@ -0,0 +1,143 @@
"""Export JoyVASA's pinned Chinese HuBERT audio path to ONNX.
The graph accepts one already padded four-second 16 kHz waveform (64,080
samples) and produces the 100 x 256 audio feature window consumed by the
diffusion denoiser. Padding is kept outside the graph so the browser can apply
JoyVASA's small reflect pad deterministically before inference.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from pathlib import Path
import numpy as np
import onnx
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import HubertConfig
EXPECTED_CHECKPOINT_SHA256 = "9dd869329725caedf5f0c13dd383abec1e385f566d8afe2047b141f604844e80"
EXPECTED_HUBERT_CONFIG_SHA256 = "f6bd1bdef239518d022edcef31243acf344a2afa33d5428e16f221cac09cbcd0"
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
class JoyVASAAudioFeatures(nn.Module):
def __init__(self, encoder: nn.Module, projection: nn.Module):
super().__init__()
self.encoder = encoder
self.projection = projection
def forward(self, audio_padded: torch.Tensor) -> torch.Tensor:
# JoyVASA first asks HuBERT for 200 frames, then back-resamples to the
# 100 motion frames used for a four-second, 25 fps diffusion window.
hidden = self.encoder(audio_padded, 25, frame_num=200).last_hidden_state
hidden = F.interpolate(
hidden.transpose(1, 2), size=100, align_corners=False, mode="linear"
).transpose(1, 2)
return self.projection(hidden)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--source", type=Path, required=True)
parser.add_argument("--checkpoint", type=Path, required=True)
parser.add_argument("--hubert-config", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
checkpoint_hash = sha256(args.checkpoint)
config_hash = sha256(args.hubert_config)
if checkpoint_hash != EXPECTED_CHECKPOINT_SHA256:
raise RuntimeError(f"Unexpected checkpoint SHA-256: {checkpoint_hash}")
if config_hash != EXPECTED_HUBERT_CONFIG_SHA256:
raise RuntimeError(f"Unexpected HuBERT config SHA-256: {config_hash}")
sys.path.insert(0, str(args.source))
from src.modules.hubert import HubertModel
payload = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
config = HubertConfig.from_json_file(str(args.hubert_config))
encoder = HubertModel(config).eval()
encoder_prefix = "audio_encoder."
encoder_state = {
key[len(encoder_prefix):]: value
for key, value in payload["model"].items()
if key.startswith(encoder_prefix)
}
missing, unexpected = encoder.load_state_dict(encoder_state, strict=True)
if missing or unexpected:
raise RuntimeError(f"Encoder state mismatch, missing={missing}, unexpected={unexpected}")
projection = nn.Linear(768, 256).eval()
projection.load_state_dict(
{
"weight": payload["model"]["audio_feature_map.weight"],
"bias": payload["model"]["audio_feature_map.bias"],
},
strict=True,
)
model = JoyVASAAudioFeatures(encoder, projection).eval()
torch.manual_seed(20260710)
audio = torch.randn(1, 64_080)
with torch.no_grad():
reference = model(audio).cpu().numpy()
args.output.parent.mkdir(parents=True, exist_ok=True)
torch.onnx.export(
model,
(audio,),
args.output,
input_names=["audio_padded"],
output_names=["audio_features"],
opset_version=17,
do_constant_folding=True,
export_params=True,
)
graph = onnx.load(args.output, load_external_data=False)
onnx.checker.check_model(graph)
np.savez_compressed(
args.output.with_suffix(".reference.npz"),
audio_padded=audio.numpy(),
audio_features=reference,
)
np.savez_compressed(
args.output.with_suffix(".conditioning.npz"),
start_audio_feat=payload["model"]["start_audio_feat"].numpy(),
start_motion_feat=payload["model"]["start_motion_feat"].numpy(),
null_audio_feat=payload["model"]["null_audio_feat"].numpy(),
)
metadata = {
"checkpoint_sha256": checkpoint_hash,
"hubert_config_sha256": config_hash,
"onnx_sha256": sha256(args.output),
"onnx_bytes": args.output.stat().st_size,
"opset": 17,
"sample_rate": 16_000,
"unpadded_samples": 64_000,
"padded_samples": 64_080,
"motion_fps": 25,
"motion_frames": 100,
"nodes": len(graph.graph.node),
"inputs": {item.name: [dim.dim_value for dim in item.type.tensor_type.shape.dim] for item in graph.graph.input},
"outputs": {item.name: [dim.dim_value for dim in item.type.tensor_type.shape.dim] for item in graph.graph.output},
}
args.output.with_suffix(".json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
print(json.dumps(metadata, indent=2))
if __name__ == "__main__":
main()
+150
View File
@@ -0,0 +1,150 @@
"""Export the pinned JoyVASA diffusion denoiser to a browser-oriented ONNX graph.
The checkpoint pickle global list must be audited before running this script. The
pinned checkpoint currently contains only argparse.Namespace, pathlib.PosixPath,
collections.OrderedDict, and PyTorch tensor rebuild/storage globals.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from pathlib import Path
import numpy as np
import onnx
import torch
EXPECTED_CHECKPOINT_SHA256 = "9dd869329725caedf5f0c13dd383abec1e385f566d8afe2047b141f604844e80"
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--source", type=Path, required=True)
parser.add_argument("--checkpoint", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
checkpoint_hash = sha256(args.checkpoint)
if checkpoint_hash != EXPECTED_CHECKPOINT_SHA256:
raise RuntimeError(f"Unexpected checkpoint SHA-256: {checkpoint_hash}")
sys.path.insert(0, str(args.source))
import src.modules.dit_talking_head as dit_module
# JoyVASA's helper defaults this mask to CUDA even when the network itself
# is constructed on CPU. Keep the upstream source untouched and make the
# export-only call follow the tensors' actual device.
upstream_enc_dec_mask = dit_module.enc_dec_mask
def cpu_enc_dec_mask(T, S, frame_width=2, expansion=0, device="cpu"):
return upstream_enc_dec_mask(T, S, frame_width, expansion, device="cpu")
dit_module.enc_dec_mask = cpu_enc_dec_mask
DenoisingNetwork = dit_module.DenoisingNetwork
payload = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
checkpoint_args = payload["args"]
checkpoint_expected = {
"n_diff_steps": 50,
"feature_dim": 256,
"n_heads": 8,
"n_layers": 6,
"n_motions": 100,
"n_prev_motions": 10,
"motion_feat_dim": 73,
"use_indicator": True,
}
checkpoint_actual = {key: getattr(checkpoint_args, key) for key in checkpoint_expected}
if checkpoint_actual != checkpoint_expected:
raise RuntimeError(f"Unexpected JoyVASA checkpoint config: {checkpoint_actual}")
# The pinned JoyVASA revision does not forward most training CLI fields into
# DenoisingNetwork. Reproduce DitTalkingHead's real constructor call exactly:
# checkpoint motion/feature dimensions plus DenoisingNetwork defaults. The
# resulting state is 8 layers, a 501-step sinusoidal embedding, and no
# indicator channel. Strict loading below is the final guard against drift.
effective_architecture = {
"motion_feat_dim": checkpoint_args.motion_feat_dim,
"feature_dim": checkpoint_args.feature_dim,
"n_heads": 8,
"n_layers": 8,
"n_motions": 100,
"n_prev_motions": 10,
"n_diff_steps_embedding": 500,
"use_indicator": False,
"learnable_pe": False,
}
model = DenoisingNetwork(
device="cpu",
motion_feat_dim=checkpoint_args.motion_feat_dim,
feature_dim=checkpoint_args.feature_dim,
).eval()
prefix = "denoising_net."
state = {key[len(prefix):]: value for key, value in payload["model"].items() if key.startswith(prefix)}
missing, unexpected = model.load_state_dict(state, strict=True)
if missing or unexpected:
raise RuntimeError(f"State mismatch, missing={missing}, unexpected={unexpected}")
torch.manual_seed(20260710)
inputs = (
torch.randn(2, 100, 73),
torch.randn(2, 100, 256),
torch.randn(2, 10, 73),
torch.randn(2, 10, 256),
torch.tensor([50, 50], dtype=torch.int64),
)
with torch.no_grad():
reference = model(*inputs).cpu().numpy()
args.output.parent.mkdir(parents=True, exist_ok=True)
torch.onnx.export(
model,
inputs,
args.output,
input_names=["motion", "audio", "previous_motion", "previous_audio", "step"],
output_names=["motion_prediction"],
opset_version=17,
do_constant_folding=True,
export_params=True,
)
graph = onnx.load(args.output, load_external_data=False)
onnx.checker.check_model(graph)
np.savez_compressed(
args.output.with_suffix(".reference.npz"),
motion=inputs[0].numpy(),
audio=inputs[1].numpy(),
previous_motion=inputs[2].numpy(),
previous_audio=inputs[3].numpy(),
step=inputs[4].numpy(),
motion_prediction=reference,
)
metadata = {
"checkpoint_sha256": checkpoint_hash,
"onnx_sha256": sha256(args.output),
"onnx_bytes": args.output.stat().st_size,
"opset": 17,
"checkpoint_config": checkpoint_actual,
"effective_architecture": effective_architecture,
"inputs": {item.name: [dim.dim_value for dim in item.type.tensor_type.shape.dim] for item in graph.graph.input},
"outputs": {item.name: [dim.dim_value for dim in item.type.tensor_type.shape.dim] for item in graph.graph.output},
"nodes": len(graph.graph.node),
}
args.output.with_suffix(".json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
print(json.dumps(metadata, indent=2))
if __name__ == "__main__":
main()
+86
View File
@@ -0,0 +1,86 @@
"""Create deterministic browser runtime data for the pinned JoyVASA model."""
from __future__ import annotations
import argparse
import hashlib
import json
import pickle
from pathlib import Path
import numpy as np
import torch
EXPECTED_CHECKPOINT_SHA256 = "9dd869329725caedf5f0c13dd383abec1e385f566d8afe2047b141f604844e80"
EXPECTED_TEMPLATE_SHA256 = "294ce67350b18031b375361756f654c76d5e14c8f1e319cf9ed07f759ef81a98"
def sha256(path: Path) -> str:
digest = hashlib.sha256(path.read_bytes()).hexdigest()
return digest
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint", type=Path, required=True)
parser.add_argument("--template", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
args = parser.parse_args()
if sha256(args.checkpoint) != EXPECTED_CHECKPOINT_SHA256:
raise RuntimeError("Unexpected JoyVASA checkpoint")
if sha256(args.template) != EXPECTED_TEMPLATE_SHA256:
raise RuntimeError("Unexpected JoyVASA motion template")
payload = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
# The pinned 3.6KB pickle was audited before use and contains only a dict,
# NumPy ndarray reconstruction, ndarray, and dtype globals.
with args.template.open("rb") as handle:
template = pickle.load(handle)
args.output_dir.mkdir(parents=True, exist_ok=True)
conditioning_parts = [
("start_audio_feat", payload["model"]["start_audio_feat"].numpy()),
("start_motion_feat", payload["model"]["start_motion_feat"].numpy()),
("null_audio_feat", payload["model"]["null_audio_feat"].numpy()),
]
conditioning = np.concatenate([value.reshape(-1) for _, value in conditioning_parts]).astype("<f4")
conditioning_path = args.output_dir / "joyvasa-conditioning.bin"
conditioning.tofile(conditioning_path)
steps = 51
x = torch.linspace(0, 50, steps)
alpha_bars_raw = torch.cos(((x / 50) + 0.008) / 1.008 * torch.pi * 0.5) ** 2
alpha_bars_raw = alpha_bars_raw / alpha_bars_raw[0]
betas = 1 - alpha_bars_raw[1:] / alpha_bars_raw[:-1]
betas = torch.clip(betas, 0.0001, 0.999)
betas = torch.cat([torch.zeros(1), betas])
alphas = 1 - betas
alpha_bars = torch.cumprod(alphas, dim=0)
schedule = torch.stack([alphas, alpha_bars], dim=1).numpy().astype("<f4")
schedule_path = args.output_dir / "joyvasa-schedule.bin"
schedule.tofile(schedule_path)
template_json = {
key: np.asarray(value, dtype=np.float32).reshape(-1).tolist()
for key, value in template.items()
}
template_path = args.output_dir / "joyvasa-motion-template.json"
template_path.write_text(json.dumps(template_json, separators=(",", ":")), encoding="utf-8")
offset = 0
layout = {}
for name, value in conditioning_parts:
layout[name] = {"offset": offset, "length": int(value.size), "shape": list(value.shape)}
offset += value.size
metadata = {
"conditioning": {"bytes": conditioning_path.stat().st_size, "sha256": sha256(conditioning_path), "layout": layout},
"schedule": {"bytes": schedule_path.stat().st_size, "sha256": sha256(schedule_path), "shape": [51, 2], "columns": ["alpha", "alpha_bar"]},
"template": {"bytes": template_path.stat().st_size, "sha256": sha256(template_path), "keys": sorted(template_json)},
}
(args.output_dir / "joyvasa-runtime.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
print(json.dumps(metadata, indent=2))
if __name__ == "__main__":
main()
+191
View File
@@ -0,0 +1,191 @@
import fs from "node:fs";
import path from "node:path";
import * as ort from "onnxruntime-web";
const modelDir = process.argv[2] ?? "/private/tmp";
const sourcePath = process.argv[3] ?? "/private/tmp/liveportrait-source-256.rgb";
const outputDir = process.argv[4] ?? "/private/tmp/liveportrait-smoke";
const renderSpecs = (process.argv[5] ?? "closed:0.05,open:0.35")
.split(",")
.map((entry) => {
const [name, ratio] = entry.split(":");
return [name, Number(ratio)];
});
ort.env.wasm.numThreads = 1;
ort.env.wasm.simd = true;
const modelPath = (name) => path.join(modelDir, `liveportrait-${name}.onnx`);
const tensor = (data, dims) => new ort.Tensor("float32", data, dims);
function log(stage, detail = "") {
process.stdout.write(`[liveportrait] ${stage}${detail ? `: ${detail}` : ""}\n`);
}
function imageTensorFromRgb(bytes) {
if (bytes.length !== 256 * 256 * 3) throw new Error(`Expected 256x256 RGB input, got ${bytes.length} bytes`);
const data = new Float32Array(bytes.length);
const plane = 256 * 256;
for (let i = 0; i < plane; i += 1) {
data[i] = bytes[i * 3] / 255;
data[plane + i] = bytes[i * 3 + 1] / 255;
data[plane * 2 + i] = bytes[i * 3 + 2] / 255;
}
return tensor(data, [1, 3, 256, 256]);
}
function headposeDegree(logits) {
let max = -Infinity;
for (const value of logits) max = Math.max(max, value);
let sum = 0;
let weighted = 0;
for (let i = 0; i < logits.length; i += 1) {
const value = Math.exp(logits[i] - max);
sum += value;
weighted += value * i;
}
return (weighted / sum) * 3 - 97.5;
}
function multiply3x3(a, b) {
const out = new Float32Array(9);
for (let row = 0; row < 3; row += 1) {
for (let col = 0; col < 3; col += 1) {
out[row * 3 + col] = a[row * 3] * b[col]
+ a[row * 3 + 1] * b[3 + col]
+ a[row * 3 + 2] * b[6 + col];
}
}
return out;
}
function rotationMatrix(pitchDegree, yawDegree, rollDegree) {
const pitch = pitchDegree * Math.PI / 180;
const yaw = yawDegree * Math.PI / 180;
const roll = rollDegree * Math.PI / 180;
const rx = new Float32Array([1, 0, 0, 0, Math.cos(pitch), -Math.sin(pitch), 0, Math.sin(pitch), Math.cos(pitch)]);
const ry = new Float32Array([Math.cos(yaw), 0, Math.sin(yaw), 0, 1, 0, -Math.sin(yaw), 0, Math.cos(yaw)]);
const rz = new Float32Array([Math.cos(roll), -Math.sin(roll), 0, Math.sin(roll), Math.cos(roll), 0, 0, 0, 1]);
const product = multiply3x3(rz, multiply3x3(ry, rx));
return new Float32Array([product[0], product[3], product[6], product[1], product[4], product[7], product[2], product[5], product[8]]);
}
function transformKeypoints(motion) {
const pitch = headposeDegree(motion.pitch.data);
const yaw = headposeDegree(motion.yaw.data);
const roll = headposeDegree(motion.roll.data);
const rotation = rotationMatrix(pitch, yaw, roll);
const kp = motion.kp.data;
const exp = motion.exp.data;
const translation = motion.t.data;
const scale = motion.scale.data[0];
const out = new Float32Array(63);
for (let point = 0; point < 21; point += 1) {
const offset = point * 3;
for (let axis = 0; axis < 3; axis += 1) {
out[offset + axis] = scale * (
kp[offset] * rotation[axis]
+ kp[offset + 1] * rotation[3 + axis]
+ kp[offset + 2] * rotation[6 + axis]
+ exp[offset + axis]
);
}
out[offset] += translation[0];
out[offset + 1] += translation[1];
}
return { data: out, pose: { pitch, yaw, roll, scale } };
}
async function createSession(name) {
const started = Date.now();
const session = await ort.InferenceSession.create(fs.readFileSync(modelPath(name)), {
executionProviders: ["wasm"],
graphOptimizationLevel: "all",
});
log(`loaded ${name}`, `${Date.now() - started} ms`);
return session;
}
async function retargetLip(session, sourceKeypoints, targetRatio) {
const input = new Float32Array(65);
input.set(sourceKeypoints, 0);
input[63] = 0.05;
input[64] = targetRatio;
const result = await session.run({ input: tensor(input, [1, 65]) });
const keypoints = new Float32Array(63);
for (let i = 0; i < 63; i += 1) keypoints[i] = sourceKeypoints[i] + result.output.data[i];
return keypoints;
}
async function stitch(session, source, driving) {
const input = new Float32Array(126);
input.set(source, 0);
input.set(driving, 63);
const result = await session.run({ input: tensor(input, [1, 126]) });
const output = new Float32Array(driving);
for (let i = 0; i < 63; i += 1) output[i] += result.output.data[i];
for (let point = 0; point < 21; point += 1) {
output[point * 3] += result.output.data[63];
output[point * 3 + 1] += result.output.data[64];
}
return output;
}
function writeRgbOutput(output, name) {
const [batch, channels, height, width] = output.dims;
if (batch !== 1 || channels !== 3) throw new Error(`Unexpected generator output ${output.dims.join("x")}`);
const plane = height * width;
const rgb = Buffer.alloc(plane * 3);
for (let i = 0; i < plane; i += 1) {
rgb[i * 3] = Math.round(Math.max(0, Math.min(1, output.data[i])) * 255);
rgb[i * 3 + 1] = Math.round(Math.max(0, Math.min(1, output.data[plane + i])) * 255);
rgb[i * 3 + 2] = Math.round(Math.max(0, Math.min(1, output.data[plane * 2 + i])) * 255);
}
fs.writeFileSync(path.join(outputDir, `${name}-${width}x${height}.rgb`), rgb);
return { width, height };
}
async function main() {
fs.mkdirSync(outputDir, { recursive: true });
const image = imageTensorFromRgb(fs.readFileSync(sourcePath));
const appearance = await createSession("appearance_feature_extractor");
const appearanceOutput = await appearance.run({ img: image });
const feature = appearanceOutput.output;
log("appearance inference complete", feature.dims.join("x"));
const motionExtractor = await createSession("motion_extractor");
const motion = await motionExtractor.run({ img: image });
const transformed = transformKeypoints(motion);
const source = transformed.data;
log("motion inference complete", JSON.stringify(transformed.pose));
const lip = await createSession("stitching_lip");
const stitching = await createSession("stitching");
const drivingKeypoints = [];
for (const [name, ratio] of renderSpecs) {
if (!name || !Number.isFinite(ratio)) throw new Error(`Invalid render spec ${name}:${ratio}`);
drivingKeypoints.push([name, await stitch(stitching, source, await retargetLip(lip, source, ratio))]);
}
const warping = await createSession("warping");
const spade = await createSession("spade_generator");
for (const [name, driving] of drivingKeypoints) {
const started = Date.now();
const warped = await warping.run({
feature_3d: feature,
kp_source: tensor(source, [1, 21, 3]),
kp_driving: tensor(driving, [1, 21, 3]),
});
log(`${name} warping complete`, `${Date.now() - started} ms`);
const generated = await spade.run({ input: warped["879"] });
const dimensions = writeRgbOutput(generated.output, name);
log(`${name} frame complete`, `${dimensions.width}x${dimensions.height}`);
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
+124
View File
@@ -0,0 +1,124 @@
"""Rewrite static 5D ONNX GridSample nodes into WebGPU-friendly 4D sampling.
For trilinear sampling, XY bilinear sampling is batched across every input depth
slice with one 4D GridSample. Linear Z weights are then applied and reduced.
This preserves align_corners=0 and zeros padding without native 5D GridSample.
"""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
import onnx
from onnx import TensorProto, helper, numpy_helper, shape_inference
def tensor_shapes(model: onnx.ModelProto) -> dict[str, list[int]]:
inferred = shape_inference.infer_shapes(model)
values = list(inferred.graph.input) + list(inferred.graph.value_info) + list(inferred.graph.output)
return {
value.name: [dimension.dim_value for dimension in value.type.tensor_type.shape.dim]
for value in values
}
def rewrite_node(node: onnx.NodeProto, input_shape: list[int], grid_shape: list[int], index: int):
n, channels, depth, height, width = input_shape
grid_n, out_depth, out_height, out_width, grid_coords = grid_shape
if n != grid_n or grid_coords != 3 or not all(input_shape + grid_shape):
raise RuntimeError(f"GridSample must have fully static 5D shapes: {input_shape}, {grid_shape}")
attrs = {attribute.name: helper.get_attribute_value(attribute) for attribute in node.attribute}
if attrs != {"align_corners": 0, "mode": b"linear", "padding_mode": b"zeros"}:
raise RuntimeError(f"Unsupported GridSample attributes: {attrs}")
prefix = f"webgpu_grid5d_{index}"
initializers = []
def const(name: str, values, dtype=np.int64):
full_name = f"{prefix}_{name}"
initializers.append(numpy_helper.from_array(np.asarray(values, dtype=dtype), full_name))
return full_name
shape_volume = const("shape_volume", [n * depth, channels, height, width])
slice_starts = const("slice_starts", [0])
slice_ends = const("slice_ends", [2])
slice_axes = const("slice_axes", [4])
slice_steps = const("slice_steps", [1])
unsqueeze_depth_axis = const("unsqueeze_depth_axis", [1])
tile_repeats = const("tile_repeats", [1, depth, 1, 1, 1, 1])
shape_grid2d = const("shape_grid2d", [n * depth, out_depth * out_height, out_width, 2])
shape_sampled = const("shape_sampled", [n, depth, channels, out_depth, out_height, out_width])
z_starts = const("z_starts", [2])
z_ends = const("z_ends", [3])
depth_values = const("depth_values", np.arange(depth).reshape(1, 1, 1, 1, depth), np.float32)
z_scale = const("z_scale", [depth / 2], np.float32)
z_offset = const("z_offset", [(depth - 1) / 2], np.float32)
one = const("one", [1], np.float32)
zero = const("zero", [0], np.float32)
channel_axis = const("channel_axis", [1])
reduce_axis = const("reduce_axis", [5])
names = {key: f"{prefix}_{key}" for key in [
"volume_ndchw", "volume_4d", "grid_xy", "grid_xy_depth", "grid_xy_tiled", "grid_2d",
"sampled_4d", "sampled_6d", "sampled_ordered", "grid_z", "z_scaled", "z_input",
"z_delta", "z_distance", "z_weight_raw", "z_weights", "z_weights_channel", "weighted",
]}
nodes = [
helper.make_node("Transpose", [node.input[0]], [names["volume_ndchw"]], perm=[0, 2, 1, 3, 4], name=f"{prefix}/volume_to_ndchw"),
helper.make_node("Reshape", [names["volume_ndchw"], shape_volume], [names["volume_4d"]], name=f"{prefix}/volume_to_4d"),
helper.make_node("Slice", [node.input[1], slice_starts, slice_ends, slice_axes, slice_steps], [names["grid_xy"]], name=f"{prefix}/slice_xy"),
helper.make_node("Unsqueeze", [names["grid_xy"], unsqueeze_depth_axis], [names["grid_xy_depth"]], name=f"{prefix}/add_input_depth"),
helper.make_node("Tile", [names["grid_xy_depth"], tile_repeats], [names["grid_xy_tiled"]], name=f"{prefix}/tile_xy"),
helper.make_node("Reshape", [names["grid_xy_tiled"], shape_grid2d], [names["grid_2d"]], name=f"{prefix}/grid_to_2d"),
helper.make_node("GridSample", [names["volume_4d"], names["grid_2d"]], [names["sampled_4d"]], align_corners=0, mode="linear", padding_mode="zeros", name=f"{prefix}/grid_sample_2d"),
helper.make_node("Reshape", [names["sampled_4d"], shape_sampled], [names["sampled_6d"]], name=f"{prefix}/sampled_to_6d"),
helper.make_node("Transpose", [names["sampled_6d"]], [names["sampled_ordered"]], perm=[0, 2, 3, 4, 5, 1], name=f"{prefix}/depth_last"),
helper.make_node("Slice", [node.input[1], z_starts, z_ends, slice_axes, slice_steps], [names["grid_z"]], name=f"{prefix}/slice_z"),
helper.make_node("Mul", [names["grid_z"], z_scale], [names["z_scaled"]], name=f"{prefix}/scale_z"),
helper.make_node("Add", [names["z_scaled"], z_offset], [names["z_input"]], name=f"{prefix}/offset_z"),
helper.make_node("Sub", [names["z_input"], depth_values], [names["z_delta"]], name=f"{prefix}/z_delta"),
helper.make_node("Abs", [names["z_delta"]], [names["z_distance"]], name=f"{prefix}/z_distance"),
helper.make_node("Sub", [one, names["z_distance"]], [names["z_weight_raw"]], name=f"{prefix}/z_weight_raw"),
helper.make_node("Clip", [names["z_weight_raw"], zero, one], [names["z_weights"]], name=f"{prefix}/z_weight_clip"),
helper.make_node("Unsqueeze", [names["z_weights"], channel_axis], [names["z_weights_channel"]], name=f"{prefix}/z_weight_channel"),
helper.make_node("Mul", [names["sampled_ordered"], names["z_weights_channel"]], [names["weighted"]], name=f"{prefix}/apply_z_weights"),
helper.make_node("ReduceSum", [names["weighted"], reduce_axis], [node.output[0]], keepdims=0, name=f"{prefix}/sum_z"),
]
return nodes, initializers
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("input", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
model = onnx.load(args.input, load_external_data=True)
shapes = tensor_shapes(model)
rewritten = []
initializers = []
count = 0
for node in model.graph.node:
if node.op_type == "GridSample" and len(shapes.get(node.input[0], [])) == 5:
nodes, constants = rewrite_node(node, shapes[node.input[0]], shapes[node.input[1]], count)
rewritten.extend(nodes)
initializers.extend(constants)
count += 1
else:
rewritten.append(node)
if count == 0:
raise RuntimeError("No static 5D GridSample nodes found")
del model.graph.node[:]
model.graph.node.extend(rewritten)
model.graph.initializer.extend(initializers)
model.producer_name = "Timeline Studio LivePortrait WebGPU rewrite"
model.producer_version = "1"
onnx.checker.check_model(model)
args.output.parent.mkdir(parents=True, exist_ok=True)
onnx.save(model, args.output)
print(f"rewritten={count} nodes={len(model.graph.node)} bytes={args.output.stat().st_size}")
if __name__ == "__main__":
main()
+36
View File
@@ -0,0 +1,36 @@
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
const root = process.argv[2] ?? "/private/tmp";
const port = Number(process.argv[3] ?? 8788);
const server = http.createServer((request, response) => {
const name = decodeURIComponent(new URL(request.url, `http://${request.headers.host}`).pathname).replace(/^\/+/, "");
if (!/^[a-z0-9_.-]+\.(onnx|png|bin|json)$/i.test(name)) {
response.writeHead(404, { "Access-Control-Allow-Origin": "*" });
response.end("Not found");
return;
}
const file = path.join(root, name.startsWith("joyvasa-") ? name : `liveportrait-${name}`);
fs.stat(file, (error, stat) => {
if (error || !stat.isFile()) {
response.writeHead(404, { "Access-Control-Allow-Origin": "*" });
response.end("Not found");
return;
}
response.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Cache-Control": "public, max-age=3600",
"Content-Length": stat.size,
"Content-Type": name.endsWith(".png")
? "image/png"
: name.endsWith(".json") ? "application/json" : "application/octet-stream",
});
fs.createReadStream(file).pipe(response);
});
});
server.listen(port, "127.0.0.1", () => {
process.stdout.write(`LivePortrait model server: http://127.0.0.1:${port}/\n`);
});
+199
View File
@@ -82,6 +82,7 @@ import {
getSmartCropRect,
mapNormalizedBoxToFrame,
} from "./lib/visualGeometry.js";
import { JOYVASA_PROJECT_MODEL_BASE_URL } from "./config/joyVasa.js";
const PLAYBACK_UI_FRAME_MS = 50;
const DEFAULT_VISION_OPTIONS = Object.freeze({
@@ -97,6 +98,59 @@ const EMPTY_VISION_OPTIONS = Object.freeze({
smartCrop: false,
});
async function decodeAvatarAudio16k(blob) {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
if (!AudioContextClass) throw new Error("当前浏览器不支持音频解码");
const context = new AudioContextClass();
try {
const decoded = await context.decodeAudioData((await blob.arrayBuffer()).slice(0));
const mono = new Float32Array(decoded.length);
for (let channel = 0; channel < decoded.numberOfChannels; channel += 1) {
const values = decoded.getChannelData(channel);
for (let i = 0; i < mono.length; i += 1) mono[i] += values[i] / decoded.numberOfChannels;
}
const outputLength = Math.min(64_000, Math.ceil(decoded.duration * 16_000));
const resampled = new Float32Array(64_000);
for (let i = 0; i < outputLength; i += 1) {
const position = (i * decoded.sampleRate) / 16_000;
const left = Math.min(mono.length - 1, Math.floor(position));
const right = Math.min(mono.length - 1, left + 1);
const ratio = position - left;
resampled[i] = mono[left] * (1 - ratio) + mono[right] * ratio;
}
return resampled;
} finally {
await context.close().catch(() => {});
}
}
async function encodeAvatarFrames(blobs, width, height, fps) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d", { alpha: false });
const stream = canvas.captureStream(fps);
const mimeType = ["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"]
.find((type) => MediaRecorder.isTypeSupported(type));
const recorder = mimeType ? new MediaRecorder(stream, { mimeType }) : new MediaRecorder(stream);
const chunks = [];
recorder.ondataavailable = (event) => { if (event.data.size) chunks.push(event.data); };
const stopped = new Promise((resolve, reject) => {
recorder.onstop = () => resolve(new Blob(chunks, { type: recorder.mimeType || "video/webm" }));
recorder.onerror = () => reject(recorder.error || new Error("数字人视频编码失败"));
});
recorder.start();
for (const blob of blobs) {
const bitmap = await createImageBitmap(blob);
context.drawImage(bitmap, 0, 0, width, height);
bitmap.close();
await new Promise((resolve) => window.setTimeout(resolve, 1000 / fps));
}
recorder.stop();
stream.getTracks().forEach((track) => track.stop());
return stopped;
}
function getNearestRatioIdForSize(width, height) {
const mediaWidth = Number(width);
const mediaHeight = Number(height);
@@ -270,6 +324,7 @@ export function App() {
phase: "",
});
const [avatarPanelOpen, setAvatarPanelOpen] = useState(false);
const [avatarJob, setAvatarJob] = useState({ running: false, progress: 0, phase: "" });
const fileInputRef = useRef(null);
const projectFileInputRef = useRef(null);
@@ -307,6 +362,8 @@ export function App() {
const visionObjectUrlsRef = useRef(new Map());
const visionAbortControllerRef = useRef(null);
const visionJobGenerationRef = useRef(0);
const avatarWorkerRef = useRef(null);
const avatarTestImportedRef = useRef(false);
const activeLanguage = uiLanguage || "zh";
const t = useMemo(() => createTranslator(activeLanguage), [activeLanguage]);
const trOption = (name, option) => {
@@ -327,6 +384,112 @@ export function App() {
setAvatarPanelOpen(true);
}
async function generateAvatarAcceptanceFrame() {
if (avatarJob.running) return;
if (!previewVisualSrc || previewVisualType !== "image") {
notify(t("avatarNeedsPortrait"));
return;
}
if (!audioBlob) {
notify(t("avatarNeedsAudio"));
return;
}
setAvatarJob({ running: true, progress: 1, phase: t("avatarPreparing") });
try {
const sourceBlob = previewVisualSegment?.blob instanceof Blob
? previewVisualSegment.blob
: await fetch(previewVisualSrc).then((response) => {
if (!response.ok) throw new Error(`读取肖像失败(HTTP ${response.status})`);
return response.blob();
});
const sourceDuration = Math.max(MIN_VISUAL_SEGMENT_SECONDS, Math.min(4, audioDuration || imageDuration || 4));
const audioSamples = await decodeAvatarAudio16k(audioBlob);
const motionWorker = new Worker(new URL("./workers/joyvasa.worker.js", import.meta.url), { type: "module" });
avatarWorkerRef.current?.terminate();
avatarWorkerRef.current = motionWorker;
motionWorker.onmessage = (event) => {
if (event.data?.type === "progress") {
setAvatarJob({ running: true, progress: event.data.progress, phase: event.data.phase });
return;
}
if (event.data?.type === "error") {
console.error("LivePortrait worker error", event.data.message);
setAvatarJob({ running: false, progress: 0, phase: `${t("avatarGenerationFailed")}:${event.data.message}` });
notify(`${t("avatarGenerationFailed")}:${event.data.message}`);
motionWorker.terminate();
if (avatarWorkerRef.current === motionWorker) avatarWorkerRef.current = null;
return;
}
if (event.data?.type !== "motion") return;
motionWorker.terminate();
const renderWorker = new Worker(new URL("./workers/liveportrait.worker.js", import.meta.url), { type: "module" });
avatarWorkerRef.current = renderWorker;
renderWorker.onmessage = async (renderEvent) => {
if (renderEvent.data?.type === "progress") {
setAvatarJob({ running: true, progress: renderEvent.data.progress, phase: renderEvent.data.phase });
return;
}
if (renderEvent.data?.type === "error") {
setAvatarJob({ running: false, progress: 0, phase: `${t("avatarGenerationFailed")}:${renderEvent.data.message}` });
notify(`${t("avatarGenerationFailed")}:${renderEvent.data.message}`);
renderWorker.terminate();
if (avatarWorkerRef.current === renderWorker) avatarWorkerRef.current = null;
return;
}
if (renderEvent.data?.type !== "videoFrames") return;
try {
setAvatarJob({ running: true, progress: 99, phase: "编码数字人视频" });
const blob = await encodeAvatarFrames(renderEvent.data.blobs, renderEvent.data.width, renderEvent.data.height, renderEvent.data.fps);
const url = URL.createObjectURL(blob);
imageUrlRefs.current.add(url);
const asset = {
id: crypto.randomUUID(), type: "video", src: url, name: "liveportrait-joyvasa.webm",
meta: `${renderEvent.data.width} x ${renderEvent.data.height} · JoyVASA + LivePortrait Web`, blob,
duration: sourceDuration, width: renderEvent.data.width, height: renderEvent.data.height, trackFrames: [],
};
setUserAssets((assets) => [asset, ...assets]);
replaceVisualTimeline(asset, sourceDuration);
setCurrentTime(0);
setAvatarJob({ running: false, progress: 100, phase: t("avatarAcceptanceDone") });
notify(t("avatarTrackReplaced"));
} catch (error) {
setAvatarJob({ running: false, progress: 0, phase: `${t("avatarGenerationFailed")}:${error.message}` });
notify(`${t("avatarGenerationFailed")}:${error.message}`);
} finally {
renderWorker.terminate();
if (avatarWorkerRef.current === renderWorker) avatarWorkerRef.current = null;
}
};
renderWorker.postMessage({
type: "generateVideo", portraitBlob: sourceBlob, motionBuffer: event.data.motion,
modelBaseUrl: import.meta.env.VITE_LIVE_PORTRAIT_MODEL_BASE_URL || "",
joyVasaModelBaseUrl: JOYVASA_PROJECT_MODEL_BASE_URL,
renderFps: 8,
}, [event.data.motion]);
};
motionWorker.onerror = (event) => {
console.error("LivePortrait worker module error", event.message, event);
setAvatarJob({ running: false, progress: 0, phase: `${t("avatarGenerationFailed")}:${event.message || "Worker error"}` });
notify(`${t("avatarGenerationFailed")}:${event.message || "Worker error"}`);
motionWorker.terminate();
if (avatarWorkerRef.current === motionWorker) avatarWorkerRef.current = null;
};
motionWorker.postMessage({
type: "generate",
audioSamples: audioSamples.buffer,
modelBaseUrl: JOYVASA_PROJECT_MODEL_BASE_URL,
}, [audioSamples.buffer]);
} catch (error) {
setAvatarJob({ running: false, progress: 0, phase: "" });
notify(`${t("avatarGenerationFailed")}:${error instanceof Error ? error.message : String(error)}`);
}
}
const ratio = useMemo(
() => RATIO_OPTIONS.find((option) => option.id === ratioId) ?? RATIO_OPTIONS[0],
[ratioId],
@@ -658,6 +821,40 @@ export function App() {
setFitMode("contain");
}, [ratioId]);
useEffect(() => {
const testImageUrl = import.meta.env.DEV ? import.meta.env.VITE_AVATAR_TEST_IMAGE_URL : "";
if (!testImageUrl || avatarTestImportedRef.current) return;
avatarTestImportedRef.current = true;
fetch(testImageUrl)
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.blob();
})
.then((blob) => {
const url = URL.createObjectURL(blob);
imageUrlRefs.current.add(url);
const asset = {
id: crypto.randomUUID(),
type: "image",
src: url,
name: "老外戴眼镜中年人物肖像生成-modnet.png",
meta: "819 x 1024 · E2E test",
blob,
duration: 4,
width: 819,
height: 1024,
trackFrames: [],
};
setUserAssets((assets) => [asset, ...assets]);
replaceVisualTimeline(asset, 4);
notify("端到端测试肖像已载入画面轨");
})
.catch((error) => {
avatarTestImportedRef.current = false;
console.error("Avatar E2E test image import failed", error);
});
}, []);
useEffect(() => {
const ratioSource = visualSegments.find((segment) => segment.width > 0 && segment.height > 0);
if (!ratioSource) {
@@ -4585,6 +4782,8 @@ export function App() {
hasVisual={Boolean(previewVisualSrc)}
visualType={previewVisualType}
audioDuration={audioDuration}
avatarJob={avatarJob}
generateAvatarAcceptanceFrame={generateAvatarAcceptanceFrame}
/>
</section>
Binary file not shown.
+52 -5
View File
@@ -8,8 +8,11 @@ import {
Trash,
Waveform,
} from "@phosphor-icons/react";
import { useState } from "react";
import { formatTime, getSegmentStartTime } from "../lib/timeline.js";
import { LIVE_PORTRAIT_WEB_MODEL } from "../config/livePortrait.js";
import { probeLivePortraitWebEnvironment } from "../lib/livePortraitWeb.js";
import { HistoryPanel, MyVoicesPanel, VoiceSynthesisPanel } from "./panels.jsx";
function CaptionContextPanel({
@@ -136,8 +139,22 @@ function CaptionContextPanel({
);
}
function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration, captionSegments, selectedVoice }) {
function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration, captionSegments, selectedVoice, avatarJob, generateAvatarAcceptanceFrame }) {
const hasPortrait = hasVisual && visualType === "image";
const [probeState, setProbeState] = useState("idle");
const [probeResult, setProbeResult] = useState(null);
const runProbe = async () => {
setProbeState("running");
try {
setProbeResult(await probeLivePortraitWebEnvironment());
setProbeState("done");
} catch (error) {
setProbeResult({ readyForPorting: false, checks: [{ id: "runtime", state: "failed", detail: error instanceof Error ? error.message : String(error) }] });
setProbeState("done");
}
};
return (
<div className="avatar-context-panel">
<div className="avatar-context-hero">
@@ -149,9 +166,37 @@ function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration
<div className={audioBlob ? "is-ready" : ""}><Waveform size={17} weight="duotone" /><span><strong>{t("avatarAudio")}</strong><em>{audioBlob ? `${selectedVoice?.name ?? "AI"} · ${audioDuration.toFixed(1)}s` : t("avatarNeedsAudio")}</em></span></div>
<div className={captionSegments.length ? "is-ready" : ""}><ClosedCaptioning size={17} weight="duotone" /><span><strong>{t("avatarLipSyncSource")}</strong><em>{captionSegments.length ? `${captionSegments.length} ${t("captionSegmentsUnit")} · ${t("avatarCaptionSync")}` : t("avatarNeedsCaptions")}</em></span></div>
</div>
<div className="avatar-sync-mode"><span>{t("avatarSyncMode")}</span><strong>{t("avatarSyncModeCaption")}</strong></div>
<div className="avatar-sync-mode"><span>{t("avatarModelSource")}</span><strong>{LIVE_PORTRAIT_WEB_MODEL.id}</strong></div>
<p className="avatar-context-note">{t("avatarGenerationNote")}</p>
<div className="avatar-official-notice"><PersonSimpleRun size={17} weight="duotone" /><span><strong>{t("avatarServiceNeeded")}</strong><em>{t("avatarServiceHint")}</em></span></div>
<div className="avatar-porting-stages" aria-label={t("avatarPortingStatus")}>
<div className="is-done"><span>1</span><strong>{t("avatarStagePinned")}</strong></div>
<div className="is-done"><span>2</span><strong>{t("avatarStageGrid")}</strong></div>
<div className="is-active"><span>3</span><strong>{t("avatarStageAudio")}</strong></div>
</div>
{probeResult ? (
<div className="avatar-probe-results">
{probeResult.checks.map((check) => <div className={`is-${check.state}`} key={check.id}><span />{check.detail}</div>)}
</div>
) : null}
<button className="panel-secondary avatar-probe-button" type="button" disabled={probeState === "running"} onClick={runProbe}>
{probeState === "running" ? t("avatarChecking") : t("avatarCheck")}
</button>
{avatarJob?.running || avatarJob?.progress > 0 || avatarJob?.phase ? (
<div className="avatar-generation-progress" aria-live="polite">
<div><span>{avatarJob.phase || t("avatarGenerating")}</span><strong>{avatarJob.progress}%</strong></div>
<i><b style={{ width: `${avatarJob.progress}%` }} /></i>
</div>
) : null}
<button
className="panel-primary avatar-generate-button"
type="button"
disabled={!hasPortrait || avatarJob?.running}
onClick={generateAvatarAcceptanceFrame}
>
<PersonSimpleRun size={17} weight="duotone" />
{avatarJob?.running ? t("avatarGenerating") : t("avatarGenerate")}
</button>
<div className="avatar-official-notice"><PersonSimpleRun size={17} weight="duotone" /><span><strong>{t("avatarPortingStatus")}</strong><em>{t("avatarServiceHint")}</em></span></div>
</div>
);
}
@@ -217,6 +262,8 @@ export function VoicePanel({
hasVisual,
visualType,
audioDuration,
avatarJob,
generateAvatarAcceptanceFrame,
}) {
const isCaptionContext = activeTool === "caption";
const isAvatarContext = activeTool === "smart" && avatarPanelOpen;
@@ -226,7 +273,7 @@ export function VoicePanel({
? `${captionSegments.length} ${t("captionSegmentsUnit", "条字幕")}`
: t("noCaptionSegments")
: isAvatarContext
? t("avatarServiceNeeded")
? t("avatarPortingStatus")
: statusText === "模型待命"
? t("modelReady")
: statusText;
@@ -280,7 +327,7 @@ export function VoicePanel({
/>
) : null}
{isAvatarContext ? <AvatarContextPanel t={t} hasVisual={hasVisual} visualType={visualType} audioBlob={audioBlob} audioDuration={audioDuration} captionSegments={captionSegments} selectedVoice={selectedVoice} /> : null}
{isAvatarContext ? <AvatarContextPanel t={t} hasVisual={hasVisual} visualType={visualType} audioBlob={audioBlob} audioDuration={audioDuration} captionSegments={captionSegments} selectedVoice={selectedVoice} avatarJob={avatarJob} generateAvatarAcceptanceFrame={generateAvatarAcceptanceFrame} /> : null}
{!isCaptionContext && !isAvatarContext && voiceTab === "synthesis" ? (
<VoiceSynthesisPanel
+2 -2
View File
@@ -776,12 +776,12 @@ function SmartVisionPanel({
<div className="avatar-lab-heading">
<span className="avatar-lab-icon"><PersonSimpleRun size={18} weight="duotone" /></span>
<div><span>{t("avatarKicker")}</span><strong>{t("avatarTitle")}</strong></div>
<em className="is-ready">{t("avatarOfficial")}</em>
<em className="is-ready">{t("avatarWebPort")}</em>
</div>
<p>{t("avatarDescription")}</p>
<div className="avatar-lab-requirements">
<span className={hasVisual && visualType === "image" ? "is-ready" : ""}>{t("avatarPortrait")}</span>
<span className="is-ready">{t("avatarService")}</span>
<span className="is-ready">{t("avatarWebgpu")}</span>
<span>{t("avatarAudio")}</span>
</div>
<button className="panel-primary avatar-open-button" type="button" onClick={onOpenAvatarPanel}>
+34
View File
@@ -0,0 +1,34 @@
const JOYVASA_REVISION = "b8f13fe9c23679c56f21b1baafb92ed00dc087c3";
export const JOYVASA_WEB_MODEL = Object.freeze({
id: "jdh-algo/JoyVASA",
sourceRevision: "916a90f8de490e8648fee460c1200bd5d9a795af",
revision: JOYVASA_REVISION,
license: "MIT",
files: Object.freeze({
audio: Object.freeze([
"joyvasa-audio.onnx.part-aa",
"joyvasa-audio.onnx.part-ab",
"joyvasa-audio.onnx.part-ac",
"joyvasa-audio.onnx.part-ad",
"joyvasa-audio.onnx.part-ae",
"joyvasa-audio.onnx.part-af",
"joyvasa-audio.onnx.part-ag",
"joyvasa-audio.onnx.part-ah",
]),
denoiser: "joyvasa-denoiser.onnx",
conditioning: "joyvasa-conditioning.bin",
schedule: "joyvasa-schedule.bin",
template: "joyvasa-motion-template.json",
}),
knownArtifacts: Object.freeze({
audio: Object.freeze({ bytes: 378_452_736, sha256: "51629927a44e13b117c163f8466b7eaa6653ffba71b0d26b8091610497ebf7d8" }),
denoiser: Object.freeze({ bytes: 33_558_033, sha256: "6e0ea70203df8db5cdd663c75c1764134b207b87f2897ff4e53d279aa3f54928" }),
conditioning: Object.freeze({ bytes: 14_184, sha256: "89e571e6b1491a88eeedfa7f17ba3ff43e70800e1daa6f544c1366c195dbd6ba" }),
schedule: Object.freeze({ bytes: 408, sha256: "8ef96b44a0673a6f699b0fa4c6259d89db183cd6d0f8b483203bd84ca8baa828" }),
template: Object.freeze({ bytes: 9_014, sha256: "f321337873a5b646ca26f80e97edd0efdc9d3c0f63d3a9d09ad7fb72d7d7f828" }),
}),
runtime: Object.freeze({ sampleRate: 16_000, windowSamples: 64_000, paddedSamples: 64_080, fps: 25, frames: 100, diffusionSteps: 50 }),
});
export const JOYVASA_PROJECT_MODEL_BASE_URL = "/models/joyvasa/";
+58
View File
@@ -0,0 +1,58 @@
const LIVE_PORTRAIT_REVISION = "e6c5d2407593a39f29c92ffd5ea3eaf5e59d52a1";
export const LIVE_PORTRAIT_WEB_MODEL = Object.freeze({
id: "dyicnc/Live-Portrait-ONNX",
upstream: "myn0908/Live-Portrait-ONNX",
revision: LIVE_PORTRAIT_REVISION,
license: "MIT",
status: "research",
files: Object.freeze({
appearanceFeatureExtractor: "appearance_feature_extractor.onnx",
motionExtractor: "motion_extractor.onnx",
generator: "generator_fix_grid.onnx",
landmark: "landmark.onnx",
warping: "warping.onnx",
spadeGenerator: "spade_generator.onnx",
stitching: "stitching.onnx",
stitchingLip: "stitching_lip.onnx",
stitchingRetargeting: "stitching_retargeting.onnx",
}),
knownArtifacts: Object.freeze({
appearanceFeatureExtractor: Object.freeze({
bytes: 3_355_896,
sha256: "e9cd2bd864a970f25bbe660e132778fc7f81a4f32945a97940a6225c8b2dafb0",
}),
motionExtractor: Object.freeze({
bytes: 112_593_241,
sha256: "6be4dcb59827a5c9af587c8d7eb07bc9f5128ea01856e9b78cf7db316787cf86",
}),
generator: Object.freeze({
bytes: 421_238_874,
sha256: "44effc5f2129c03353feb56bb8db7828346c36e81ffbacb4ab0622b3d91d2c77",
}),
landmark: Object.freeze({
bytes: 114_666_491,
sha256: "31d22a5041326c31f19b78886939a634a5aedcaa5ab8b9b951a1167595d147db",
}),
warping: Object.freeze({
bytes: 182_274_422,
sha256: "3dbdccbd99417da27d8280111f18990bbaaebf54d08435e25bb48ef6ecf0bbf7",
}),
spadeGenerator: Object.freeze({
bytes: 221_924_849,
sha256: "16c815413f4b56537af1eca6cf92b83221d6ee8f5f9f65212c533a4dc8ae155d",
}),
stitching: Object.freeze({
bytes: 182_363,
sha256: "28b5fd0b97f3cee29b37b24937f2fa294d1548799b8a16d3cfe70fab1f49c785",
}),
stitchingLip: Object.freeze({
bytes: 150_609,
sha256: "33489d795915b78a8e96787c42c367cac23a0d5d3d2bd3efbb4af5ee758d42bb",
}),
}),
});
export function getLivePortraitModelUrl(file) {
return `https://huggingface.co/${LIVE_PORTRAIT_WEB_MODEL.id}/resolve/${LIVE_PORTRAIT_WEB_MODEL.revision}/${file}`;
}
+38 -14
View File
@@ -139,20 +139,32 @@ export const UI_COPY = {
smartVisionClear: "清除当前分析",
smartVisionCutoutDownload: "下载透明 PNG",
smartVisionNoSubject: "没有找到高置信度主体,可换一帧后重试。",
avatarKicker: "Avatar lab · WebGPU",
avatarKicker: "Avatar lab · Browser ONNX",
avatarTitle: "数字人(实验室)",
avatarExperimental: "实验功能",
avatarSupported: "浏览器已就绪",
avatarDescription: "使用正脸照片与当前 AI 配音生成会说话的人像。首版采用浏览器端 ONNX 路径,模型将在首次生成时按需下载。",
avatarPortrait: "正脸照片",
avatarWebgpu: "WebGPU",
avatarWebgpu: "WASM 稳定路径",
avatarAudio: "当前配音",
avatarCheck: "检查浏览器支持",
avatarRecheck: "重新检查 WebGPU",
avatarOfficial: "官方服务路线",
avatarRecheck: "重新检查浏览器",
avatarOfficial: "完整模型路线",
avatarWebPort: "Web 移植中",
avatarService: "官方推理服务",
avatarServiceNeeded: "待配置官方 LivePortrait 服务",
avatarServiceHint: "官方 LivePortrait 通过服务端完整模型运行:头像 + 音频驱动视频 → 正式人像动画。浏览器不会再生成伪口型结果。",
avatarServiceNeeded: "LivePortrait Web 移植中",
avatarServiceHint: "浏览器单帧与画面轨替换已通过验收;3D 形变当前使用较慢的 WASM 正确性路径,下一阶段接入音频驱动 ONNX 并进行 WebGPU 加速。",
avatarPortingStatus: "模型工程 · 阶段 2/3",
avatarModelSource: "锁定模型",
avatarStagePinned: "模型版本已锁定",
avatarStageGrid: "3D 形变单帧已跑通",
avatarStageAudio: "音频驱动 ONNX",
avatarChecking: "正在检测浏览器…",
avatarPreparing: "准备肖像",
avatarGenerateAcceptance: "生成单帧并替换画面轨",
avatarAcceptanceDone: "单帧验收完成",
avatarTrackReplaced: "LivePortrait 单帧已替换到画面轨",
avatarGenerationFailed: "数字人生成失败",
avatarOpen: "打开数字人控制台",
avatarLipSyncTitle: "字幕口型同步",
avatarLipSyncDescription: "将字幕时间轴和当前 AI 配音映射为人物嘴型与表情节奏。",
@@ -164,7 +176,7 @@ export const UI_COPY = {
avatarNeedsCaptions: "请先生成或添加字幕",
avatarSyncMode: "同步方式",
avatarSyncModeCaption: "字幕 + 配音精确对齐",
avatarGenerationNote: "生成时会按需下载浏览器 ONNX 模型;首次运行需要 WebGPU,并可能耗时较长。",
avatarGenerationNote: "已锁定 Hugging Face 模型提交与生成器校验值;兼容性验证不会下载 421MB 生成器。",
avatarGenerate: "生成口型视频",
avatarGenerating: "正在生成数字人视频",
avatarGenerationHint: "首次运行会下载模型;请保持此页面打开。",
@@ -371,20 +383,32 @@ export const UI_COPY = {
smartVisionClear: "Clear current analysis",
smartVisionCutoutDownload: "Download transparent PNG",
smartVisionNoSubject: "No high-confidence subject found. Seek to another frame and retry.",
avatarKicker: "Avatar lab · WebGPU",
avatarKicker: "Avatar lab · Browser ONNX",
avatarTitle: "Talking avatar (Lab)",
avatarExperimental: "Experimental",
avatarSupported: "Browser ready",
avatarDescription: "Generate a talking portrait from a front-facing photo and the current AI voiceover. The browser ONNX model will download on first use.",
avatarPortrait: "Front-facing photo",
avatarWebgpu: "WebGPU",
avatarWebgpu: "Stable WASM path",
avatarAudio: "Current voiceover",
avatarCheck: "Check browser support",
avatarRecheck: "Recheck WebGPU",
avatarOfficial: "Official service path",
avatarRecheck: "Recheck browser",
avatarOfficial: "Full-model path",
avatarWebPort: "Web port in progress",
avatarService: "Official inference service",
avatarServiceNeeded: "Official LivePortrait service required",
avatarServiceHint: "Official LivePortrait runs as a full server-side pipeline: portrait + audio-driven video → portrait animation. The browser will no longer produce simulated lip-sync output.",
avatarServiceNeeded: "LivePortrait Web port in progress",
avatarServiceHint: "Browser single-frame inference and visual-track replacement have passed. The 3D warping path currently uses the slower WASM correctness path; audio-driver ONNX and WebGPU acceleration are next.",
avatarPortingStatus: "Model engineering · Stage 2/3",
avatarModelSource: "Pinned model",
avatarStagePinned: "Model revision pinned",
avatarStageGrid: "3D browser frame passed",
avatarStageAudio: "Audio driver ONNX",
avatarChecking: "Checking browser…",
avatarPreparing: "Preparing portrait",
avatarGenerateAcceptance: "Generate frame and replace visual track",
avatarAcceptanceDone: "Single-frame acceptance complete",
avatarTrackReplaced: "LivePortrait frame replaced the visual track",
avatarGenerationFailed: "Avatar generation failed",
avatarOpen: "Open avatar controls",
avatarLipSyncTitle: "Caption lip sync",
avatarLipSyncDescription: "Map caption timing and the current voiceover into mouth and expression timing.",
@@ -396,7 +420,7 @@ export const UI_COPY = {
avatarNeedsCaptions: "Generate or add captions first",
avatarSyncMode: "Sync method",
avatarSyncModeCaption: "Captions + voiceover alignment",
avatarGenerationNote: "The browser ONNX model downloads on demand. First use requires WebGPU and can take a while.",
avatarGenerationNote: "The Hugging Face revision and generator checksum are pinned. Compatibility diagnostics do not download the 421 MB generator.",
avatarGenerate: "Generate lip-sync video",
avatarGenerating: "Generating avatar video",
avatarGenerationHint: "First use downloads models. Keep this page open.",
+66
View File
@@ -0,0 +1,66 @@
import { LIVE_PORTRAIT_WEB_MODEL } from "../config/livePortrait.js";
const REQUIRED_GENERATOR_BYTES = LIVE_PORTRAIT_WEB_MODEL.knownArtifacts.generator.bytes;
function makeCheck(id, state, detail) {
return { id, state, detail };
}
export async function probeLivePortraitWebEnvironment() {
const checks = [];
const gpu = globalThis.navigator?.gpu;
if (!gpu) {
checks.push(makeCheck("webgpu", "failed", "WebGPU unavailable"));
return { readyForPorting: false, checks };
}
let adapter;
try {
adapter = await gpu.requestAdapter({ powerPreference: "high-performance" });
} catch (error) {
checks.push(makeCheck("webgpu", "failed", error instanceof Error ? error.message : String(error)));
return { readyForPorting: false, checks };
}
if (!adapter) {
checks.push(makeCheck("webgpu", "failed", "No WebGPU adapter"));
return { readyForPorting: false, checks };
}
checks.push(makeCheck("webgpu", "passed", "WebGPU adapter ready"));
checks.push(makeCheck(
"buffer",
adapter.limits.maxBufferSize >= REQUIRED_GENERATOR_BYTES ? "passed" : "warning",
`${Math.round(adapter.limits.maxBufferSize / 1024 / 1024)} MB max GPU buffer`,
));
if (globalThis.crossOriginIsolated) {
checks.push(makeCheck("isolation", "passed", "Cross-origin isolated"));
} else {
checks.push(makeCheck("isolation", "warning", "Single-thread fallback; COOP/COEP not enabled"));
}
try {
const estimate = await globalThis.navigator?.storage?.estimate?.();
const available = Math.max(0, (estimate?.quota ?? 0) - (estimate?.usage ?? 0));
checks.push(makeCheck(
"storage",
available >= 1_200_000_000 ? "passed" : "warning",
estimate?.quota ? `${(available / 1024 / 1024 / 1024).toFixed(1)} GB cache available` : "Storage quota unavailable",
));
} catch {
checks.push(makeCheck("storage", "warning", "Storage quota unavailable"));
}
checks.push(makeCheck(
"gridSample5d",
"warning",
"3D Conv / 5D GridSample use the verified WASM fallback; WebGPU acceleration pending",
));
return {
readyForPorting: checks.every((check) => check.state !== "failed"),
checks,
};
}
+13
View File
@@ -1494,6 +1494,19 @@ button:disabled {
.avatar-input-list span { display: grid; gap: 3px; }.avatar-input-list strong { color: #dfe9ef; font-size: 11px; }.avatar-input-list em { color: #778592; font-size: 9px; font-style: normal; }
.avatar-sync-mode { display: flex; justify-content: space-between; align-items: center; border-radius: 8px; padding: 10px; color: #93a2b0; background: rgba(255,255,255,.035); font-size: 10px; }.avatar-sync-mode strong { color: #77e5da; font-size: 10px; }.avatar-context-note { margin: 0; color: #778592; font-size: 10px; line-height: 1.55; }.avatar-generate-button { display: flex; align-items: center; justify-content: center; gap: 7px; min-height: 42px; width: 100%; }
.avatar-official-notice { display: grid; grid-template-columns: 26px minmax(0, 1fr); gap: 8px; align-items: start; border: 1px solid rgba(108, 137, 255, .24); border-radius: 8px; padding: 10px; color: #9bb6ff; background: rgba(93, 122, 240, .08); }.avatar-official-notice > span { display: grid; gap: 3px; }.avatar-official-notice strong { color: #dce7ff; font-size: 11px; }.avatar-official-notice em { color: #94a2b4; font-size: 9px; font-style: normal; line-height: 1.45; }
.avatar-porting-stages { display: grid; gap: 7px; }
.avatar-porting-stages > div { display: grid; grid-template-columns: 22px minmax(0, 1fr); align-items: center; gap: 8px; color: #6f7c8a; font-size: 10px; }
.avatar-porting-stages span { display: grid; place-items: center; width: 22px; height: 22px; border: 1px solid rgba(255,255,255,.08); border-radius: 50%; font-size: 9px; }
.avatar-porting-stages .is-done { color: #70ded3; }.avatar-porting-stages .is-done span { border-color: rgba(53,234,217,.3); background: rgba(53,234,217,.08); }
.avatar-porting-stages .is-active { color: #b9c8ff; }.avatar-porting-stages .is-active span { border-color: rgba(112,139,255,.38); background: rgba(112,139,255,.12); }
.avatar-probe-results { display: grid; gap: 5px; border-radius: 8px; padding: 9px; background: rgba(255,255,255,.025); }
.avatar-probe-results > div { display: grid; grid-template-columns: 7px minmax(0,1fr); align-items: center; gap: 7px; color: #91a0af; font-size: 9px; line-height: 1.4; }
.avatar-probe-results > div > span { width: 6px; height: 6px; border-radius: 50%; background: #7e8b98; }
.avatar-probe-results .is-passed > span { background: #35ead9; }.avatar-probe-results .is-warning > span { background: #f0b75c; }.avatar-probe-results .is-blocked > span,.avatar-probe-results .is-failed > span { background: #ff7f86; }
.avatar-probe-button { display: flex; align-items: center; justify-content: center; width: 100%; min-height: 36px; }
.avatar-generation-progress { display: grid; gap: 7px; border-radius: 8px; padding: 9px 10px; background: rgba(53,234,217,.045); }
.avatar-generation-progress > div { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: #91a4b2; font-size: 9px; }.avatar-generation-progress strong { color: #70ded3; font-size: 10px; }
.avatar-generation-progress > i { display: block; overflow: hidden; height: 4px; border-radius: 999px; background: rgba(255,255,255,.07); }.avatar-generation-progress b { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg,#6ea6ff,#35ead9); transition: width .25s ease; }
.vision-result-actions {
display: grid;
+206
View File
@@ -0,0 +1,206 @@
import * as ort from "onnxruntime-web/wasm";
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.mjs?url";
import ortWasmUrl from "../assets/ort-wasm-simd-threaded.wasm?url";
import { JOYVASA_WEB_MODEL } from "../config/joyVasa.js";
ort.env.wasm.numThreads = 1;
ort.env.wasm.simd = true;
ort.env.wasm.wasmPaths = { mjs: ortWasmMjsUrl, wasm: ortWasmUrl };
const tensor = (data, dims) => new ort.Tensor("float32", data, dims);
function progress(value, phase) {
self.postMessage({ type: "progress", progress: Math.round(value), phase });
}
function modelUrl(file, baseUrl) {
if (!baseUrl) throw new Error("JoyVASA 浏览器模型包尚未配置托管地址");
return new URL(file, new URL(baseUrl, self.location.origin)).href;
}
async function fetchArtifact(key, baseUrl, start, span) {
const configuredFiles = JOYVASA_WEB_MODEL.files[key];
const files = Array.isArray(configuredFiles) ? configuredFiles : [configuredFiles];
const total = JOYVASA_WEB_MODEL.knownArtifacts[key].bytes;
let loaded = 0;
const parts = [];
for (const file of files) {
const response = await fetch(modelUrl(file, baseUrl));
if (!response.ok) throw new Error(`${file} 下载失败(HTTP ${response.status})`);
const reader = response.body?.getReader();
if (!reader) {
const part = new Uint8Array(await response.arrayBuffer());
parts.push(part);
loaded += part.byteLength;
continue;
}
const chunks = [];
let partBytes = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
partBytes += value.byteLength;
loaded += value.byteLength;
progress(start + Math.min(1, loaded / total) * span, `下载 ${file}`);
}
const part = new Uint8Array(partBytes);
let offset = 0;
for (const chunk of chunks) {
part.set(chunk, offset);
offset += chunk.byteLength;
}
parts.push(part);
}
const combined = new Uint8Array(loaded);
let offset = 0;
for (const part of parts) {
combined.set(part, offset);
offset += part.byteLength;
}
return combined.buffer;
}
async function createSession(key, bytes) {
// Use the deterministic WASM backend for the audio driver as well. The ORT
// WebGPU bundle currently fails during module initialization in some browsers,
// outside this session-level error boundary.
return ort.InferenceSession.create(bytes, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
}
function reflectPadOnce(input, amount) {
const output = new Float32Array(input.length + amount * 2);
output.set(input, amount);
for (let i = 0; i < amount; i += 1) {
output[amount - 1 - i] = input[i + 1];
output[amount + input.length + i] = input[input.length - 2 - i];
}
return output;
}
function prepareWindow(samples) {
const source = new Float32Array(64_000);
source.set(samples.subarray(0, Math.min(samples.length, source.length)));
// Exact equivalent of JoyVASA pad_audio for a 64,000-sample window:
// reflect-pad 20 samples twice, producing 64,080 samples.
return reflectPadOnce(reflectPadOnce(source, 20), 20);
}
function makeGaussian(seed = 0x6a09e667) {
let state = seed >>> 0;
let spare = null;
const uniform = () => {
state ^= state << 13;
state ^= state >>> 17;
state ^= state << 5;
return ((state >>> 0) + 1) / 4294967297;
};
return () => {
if (spare !== null) {
const value = spare;
spare = null;
return value;
}
const radius = Math.sqrt(-2 * Math.log(uniform()));
const angle = Math.PI * 2 * uniform();
spare = radius * Math.sin(angle);
return radius * Math.cos(angle);
};
}
function randomNormal(length, gaussian) {
const values = new Float32Array(length);
for (let i = 0; i < length; i += 1) values[i] = gaussian();
return values;
}
function repeatRows(values, rows, width) {
const output = new Float32Array(rows * width);
for (let row = 0; row < rows; row += 1) output.set(values, row * width);
return output;
}
async function sampleMotion(denoiser, audioFeatures, conditioning, schedule) {
const startAudio = conditioning.subarray(0, 2560);
const startMotion = conditioning.subarray(2560, 3290);
const nullAudio = conditioning.subarray(3290, 3546);
const audioBatch = new Float32Array(2 * 100 * 256);
audioBatch.set(repeatRows(nullAudio, 100, 256), 0);
audioBatch.set(audioFeatures, 100 * 256);
const previousMotion = new Float32Array(2 * 10 * 73);
previousMotion.set(startMotion, 0);
previousMotion.set(startMotion, startMotion.length);
const previousAudio = new Float32Array(2 * 10 * 256);
previousAudio.set(startAudio, 0);
previousAudio.set(startAudio, startAudio.length);
const gaussian = makeGaussian();
let motion = randomNormal(100 * 73, gaussian);
for (let step = 50; step >= 1; step -= 1) {
const motionBatch = new Float32Array(motion.length * 2);
motionBatch.set(motion, 0);
motionBatch.set(motion, motion.length);
const result = await denoiser.run({
motion: tensor(motionBatch, [2, 100, 73]),
audio: tensor(audioBatch, [2, 100, 256]),
previous_motion: tensor(previousMotion, [2, 10, 73]),
previous_audio: tensor(previousAudio, [2, 10, 256]),
step: new ort.Tensor("int64", BigInt64Array.from([BigInt(step), BigInt(step)]), [2]),
});
const prediction = result.motion_prediction.data;
const target = new Float32Array(motion.length);
const unconditionalOffset = 10 * 73;
const conditionalOffset = 110 * 73 + unconditionalOffset;
for (let i = 0; i < target.length; i += 1) {
const base = prediction[unconditionalOffset + i];
target[i] = base + 1.15 * (prediction[conditionalOffset + i] - base);
}
const alpha = schedule[step * 2];
const alphaBar = schedule[step * 2 + 1];
const alphaBarPrevious = schedule[(step - 1) * 2 + 1];
const beta = 1 - alpha;
const c0 = ((1 - alphaBarPrevious) * Math.sqrt(alpha)) / (1 - alphaBar);
const c1 = (beta * Math.sqrt(alphaBarPrevious)) / (1 - alphaBar);
const sigma = Math.sqrt(((1 - alphaBarPrevious) / (1 - alphaBar)) * beta);
const noise = step > 1 ? randomNormal(motion.length, gaussian) : null;
const next = new Float32Array(motion.length);
for (let i = 0; i < next.length; i += 1) next[i] = c0 * motion[i] + c1 * target[i] + (noise ? sigma * noise[i] : 0);
motion = next;
progress(66 + ((51 - step) / 50) * 32, `生成口型运动 ${51 - step}/50`);
}
return motion;
}
async function generate({ audioSamples, modelBaseUrl }) {
progress(1, "准备真实音频驱动");
const [audioBytes, denoiserBytes, conditioningBytes, scheduleBytes] = await Promise.all([
fetchArtifact("audio", modelBaseUrl, 2, 47),
fetchArtifact("denoiser", modelBaseUrl, 49, 12),
fetchArtifact("conditioning", modelBaseUrl, 61, 1),
fetchArtifact("schedule", modelBaseUrl, 62, 1),
]);
progress(63, "初始化 JoyVASA ONNX");
const [audioSession, denoiserSession] = await Promise.all([
createSession("audio", audioBytes),
createSession("denoiser", denoiserBytes),
]);
const window = prepareWindow(new Float32Array(audioSamples));
const audioResult = await audioSession.run({ audio_padded: tensor(window, [1, 64_080]) });
progress(66, "音频特征完成");
const motion = await sampleMotion(
denoiserSession,
audioResult.audio_features.data,
new Float32Array(conditioningBytes),
new Float32Array(scheduleBytes),
);
progress(100, "真实音频运动生成完成");
self.postMessage({ type: "motion", motion: motion.buffer, frames: 100, fps: 25 }, [motion.buffer]);
}
self.onmessage = (event) => {
if (event.data?.type !== "generate") return;
generate(event.data).catch((error) => {
self.postMessage({ type: "error", message: error instanceof Error ? error.message : String(error) });
});
};
+294
View File
@@ -0,0 +1,294 @@
import * as ort from "onnxruntime-web/wasm";
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.mjs?url";
import ortWasmUrl from "../assets/ort-wasm-simd-threaded.wasm?url";
import { LIVE_PORTRAIT_WEB_MODEL, getLivePortraitModelUrl } from "../config/livePortrait.js";
ort.env.wasm.numThreads = 1;
ort.env.wasm.simd = true;
ort.env.wasm.wasmPaths = { mjs: ortWasmMjsUrl, wasm: ortWasmUrl };
const tensor = (data, dims) => new ort.Tensor("float32", data, dims);
function postProgress(progress, phase) {
self.postMessage({ type: "progress", progress: Math.max(0, Math.min(100, Math.round(progress))), phase });
}
function resolveModelUrl(file, modelBaseUrl) {
return modelBaseUrl ? new URL(file, modelBaseUrl).href : getLivePortraitModelUrl(file);
}
async function fetchModel(key, file, modelBaseUrl, completedBytes, totalBytes) {
const response = await fetch(resolveModelUrl(file, modelBaseUrl));
if (!response.ok) throw new Error(`${file} 下载失败(HTTP ${response.status})`);
if (!response.body) return response.arrayBuffer();
let loaded = 0;
const stream = response.body.pipeThrough(new TransformStream({
transform(chunk, controller) {
loaded += chunk.byteLength;
postProgress(5 + ((completedBytes + loaded) / totalBytes) * 55, `下载 ${key}`);
controller.enqueue(chunk);
},
}));
return new Response(stream).arrayBuffer();
}
async function loadSession(key, modelBaseUrl, downloadState) {
const file = LIVE_PORTRAIT_WEB_MODEL.files[key];
const bytes = LIVE_PORTRAIT_WEB_MODEL.knownArtifacts[key]?.bytes ?? 0;
const model = await fetchModel(key, file, modelBaseUrl, downloadState.completed, downloadState.total);
downloadState.completed += bytes;
postProgress(5 + (downloadState.completed / downloadState.total) * 55, `初始化 ${key}`);
// Keep the accepted browser pipeline on WASM until the complete LivePortrait
// graph has been validated on WebGPU. Importing the WebGPU bundle can throw an
// asynchronous ORT-internal error before session fallback gets a chance to run.
return ort.InferenceSession.create(model, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
}
function preprocessPortrait(blob) {
return createImageBitmap(blob).then((bitmap) => {
const size = Math.min(bitmap.width, bitmap.height);
const sx = Math.max(0, (bitmap.width - size) / 2);
const sy = Math.max(0, (bitmap.height - size) / 2 - size * 0.125);
const canvas = new OffscreenCanvas(256, 256);
const context = canvas.getContext("2d", { willReadFrequently: true });
context.clearRect(0, 0, 256, 256);
context.drawImage(bitmap, sx, sy, size, size, 0, 0, 256, 256);
bitmap.close();
const rgba = context.getImageData(0, 0, 256, 256).data;
const plane = 256 * 256;
const chw = new Float32Array(plane * 3);
for (let i = 0; i < plane; i += 1) {
const alpha = rgba[i * 4 + 3] / 255;
chw[i] = (rgba[i * 4] / 255) * alpha;
chw[plane + i] = (rgba[i * 4 + 1] / 255) * alpha;
chw[plane * 2 + i] = (rgba[i * 4 + 2] / 255) * alpha;
}
return tensor(chw, [1, 3, 256, 256]);
});
}
function headposeDegree(logits) {
let max = -Infinity;
for (const value of logits) max = Math.max(max, value);
let sum = 0;
let weighted = 0;
for (let i = 0; i < logits.length; i += 1) {
const value = Math.exp(logits[i] - max);
sum += value;
weighted += value * i;
}
return (weighted / sum) * 3 - 97.5;
}
function multiply3x3(a, b) {
const out = new Float32Array(9);
for (let row = 0; row < 3; row += 1) for (let col = 0; col < 3; col += 1) {
out[row * 3 + col] = a[row * 3] * b[col] + a[row * 3 + 1] * b[3 + col] + a[row * 3 + 2] * b[6 + col];
}
return out;
}
function transpose3x3(value) {
return new Float32Array([value[0], value[3], value[6], value[1], value[4], value[7], value[2], value[5], value[8]]);
}
function rotationMatrix(pitchDegree, yawDegree, rollDegree) {
const x = pitchDegree * Math.PI / 180;
const y = yawDegree * Math.PI / 180;
const z = rollDegree * Math.PI / 180;
const rx = new Float32Array([1, 0, 0, 0, Math.cos(x), -Math.sin(x), 0, Math.sin(x), Math.cos(x)]);
const ry = new Float32Array([Math.cos(y), 0, Math.sin(y), 0, 1, 0, -Math.sin(y), 0, Math.cos(y)]);
const rz = new Float32Array([Math.cos(z), -Math.sin(z), 0, Math.sin(z), Math.cos(z), 0, 0, 0, 1]);
const value = multiply3x3(rz, multiply3x3(ry, rx));
return new Float32Array([value[0], value[3], value[6], value[1], value[4], value[7], value[2], value[5], value[8]]);
}
function transformKeypoints(motion) {
const rotation = rotationMatrix(headposeDegree(motion.pitch.data), headposeDegree(motion.yaw.data), headposeDegree(motion.roll.data));
const out = new Float32Array(63);
for (let point = 0; point < 21; point += 1) {
const offset = point * 3;
for (let axis = 0; axis < 3; axis += 1) {
out[offset + axis] = motion.scale.data[0] * (
motion.kp.data[offset] * rotation[axis]
+ motion.kp.data[offset + 1] * rotation[3 + axis]
+ motion.kp.data[offset + 2] * rotation[6 + axis]
+ motion.exp.data[offset + axis]
);
}
out[offset] += motion.t.data[0];
out[offset + 1] += motion.t.data[1];
}
return out;
}
async function retargetAndStitch(lipSession, stitchingSession, source, targetRatio) {
const lipInput = new Float32Array(65);
lipInput.set(source);
lipInput[63] = 0.05;
lipInput[64] = targetRatio;
const lipResult = await lipSession.run({ input: tensor(lipInput, [1, 65]) });
const driving = new Float32Array(63);
for (let i = 0; i < 63; i += 1) driving[i] = source[i] + lipResult.output.data[i];
const stitchInput = new Float32Array(126);
stitchInput.set(source);
stitchInput.set(driving, 63);
const stitchResult = await stitchingSession.run({ input: tensor(stitchInput, [1, 126]) });
for (let i = 0; i < 63; i += 1) driving[i] += stitchResult.output.data[i];
for (let point = 0; point < 21; point += 1) {
driving[point * 3] += stitchResult.output.data[63];
driving[point * 3 + 1] += stitchResult.output.data[64];
}
return driving;
}
async function outputToBlob(output) {
const [, , height, width] = output.dims;
const plane = width * height;
const rgba = new Uint8ClampedArray(plane * 4);
for (let i = 0; i < plane; i += 1) {
rgba[i * 4] = Math.round(Math.max(0, Math.min(1, output.data[i])) * 255);
rgba[i * 4 + 1] = Math.round(Math.max(0, Math.min(1, output.data[plane + i])) * 255);
rgba[i * 4 + 2] = Math.round(Math.max(0, Math.min(1, output.data[plane * 2 + i])) * 255);
rgba[i * 4 + 3] = 255;
}
const canvas = new OffscreenCanvas(width, height);
canvas.getContext("2d").putImageData(new ImageData(rgba, width, height), 0, 0);
return canvas.convertToBlob({ type: "image/png" });
}
function templateValue(template, key, index = 0) {
return Array.isArray(template[key]) ? template[key][index] : template[key];
}
function decodeJoyVasaFrame(coefficients, frame, template) {
const offset = frame * 73;
const exp = new Float32Array(63);
for (let i = 0; i < 63; i += 1) exp[i] = coefficients[offset + i] * template.std_exp[i] + template.mean_exp[i];
const interpolate = (key, value, index = 0) => value * (templateValue(template, `max_${key}`, index) - templateValue(template, `min_${key}`, index)) + templateValue(template, `min_${key}`, index);
const scale = interpolate("scale", coefficients[offset + 63]);
const translation = new Float32Array(3);
for (let i = 0; i < 3; i += 1) translation[i] = interpolate("t", coefficients[offset + 64 + i], i);
const pitch = interpolate("pitch", coefficients[offset + 67]);
const yaw = interpolate("yaw", coefficients[offset + 68]);
const roll = interpolate("roll", coefficients[offset + 69]);
return { exp, scale, translation, rotation: rotationMatrix(pitch, yaw, roll) };
}
function buildDrivingKeypoints(motion, source, driving, initialDriving) {
const sourceRotation = rotationMatrix(headposeDegree(motion.pitch.data), headposeDegree(motion.yaw.data), headposeDegree(motion.roll.data));
const relativeRotation = multiply3x3(multiply3x3(driving.rotation, transpose3x3(initialDriving.rotation)), sourceRotation);
const lipPoints = new Set([6, 12, 14, 17, 19, 20]);
const output = new Float32Array(63);
for (let point = 0; point < 21; point += 1) {
const base = point * 3;
for (let axis = 0; axis < 3; axis += 1) {
const relativeExpression = motion.exp.data[base + axis] + driving.exp[base + axis] - initialDriving.exp[base + axis];
const expression = lipPoints.has(point) ? driving.exp[base + axis] : relativeExpression;
const canonical = motion.kp.data[base] * relativeRotation[axis]
+ motion.kp.data[base + 1] * relativeRotation[3 + axis]
+ motion.kp.data[base + 2] * relativeRotation[6 + axis];
output[base + axis] = motion.scale.data[0] * (driving.scale / initialDriving.scale) * (canonical + expression);
}
output[base] += motion.t.data[0] + driving.translation[0] - initialDriving.translation[0];
output[base + 1] += motion.t.data[1] + driving.translation[1] - initialDriving.translation[1];
}
return output;
}
async function generateVideo({ portraitBlob, motionBuffer, modelBaseUrl, joyVasaModelBaseUrl, renderFps = 8 }) {
postProgress(2, "准备肖像与真实口型运动");
const image = await preprocessPortrait(portraitBlob);
const keys = ["appearanceFeatureExtractor", "motionExtractor", "stitching", "warping", "spadeGenerator"];
const downloadState = { completed: 0, total: keys.reduce((sum, key) => sum + (LIVE_PORTRAIT_WEB_MODEL.knownArtifacts[key]?.bytes ?? 0), 0) };
const sessions = {};
for (const key of keys) sessions[key] = await loadSession(key, modelBaseUrl, downloadState);
const templateResponse = await fetch(new URL("joyvasa-motion-template.json", new URL(joyVasaModelBaseUrl, self.location.origin)));
if (!templateResponse.ok) throw new Error(`JoyVASA 运动模板下载失败(HTTP ${templateResponse.status})`);
const template = await templateResponse.json();
const coefficients = new Float32Array(motionBuffer);
postProgress(63, "提取人物 3D 特征");
const feature = (await sessions.appearanceFeatureExtractor.run({ img: image })).output;
const sourceMotion = await sessions.motionExtractor.run({ img: image });
const source = transformKeypoints(sourceMotion);
const initialDriving = decodeJoyVasaFrame(coefficients, 0, template);
const frameCount = Math.ceil(4 * renderFps);
const blobs = [];
for (let outputFrame = 0; outputFrame < frameCount; outputFrame += 1) {
const motionFrame = Math.min(99, Math.round((outputFrame / renderFps) * 25));
const driving = decodeJoyVasaFrame(coefficients, motionFrame, template);
const rawDriving = buildDrivingKeypoints(sourceMotion, source, driving, initialDriving);
const stitched = await (async () => {
const input = new Float32Array(126);
input.set(source);
input.set(rawDriving, 63);
const result = await sessions.stitching.run({ input: tensor(input, [1, 126]) });
const value = new Float32Array(rawDriving);
for (let i = 0; i < 63; i += 1) value[i] += result.output.data[i];
for (let point = 0; point < 21; point += 1) {
value[point * 3] += result.output.data[63];
value[point * 3 + 1] += result.output.data[64];
}
return value;
})();
const warped = await sessions.warping.run({ feature_3d: feature, kp_source: tensor(source, [1, 21, 3]), kp_driving: tensor(stitched, [1, 21, 3]) });
const generated = await sessions.spadeGenerator.run({ input: warped["879"] });
blobs.push(await outputToBlob(generated.output));
postProgress(68 + ((outputFrame + 1) / frameCount) * 31, `渲染口型帧 ${outputFrame + 1}/${frameCount}`);
}
postProgress(100, "真实口型帧生成完成");
self.postMessage({ type: "videoFrames", blobs, width: 512, height: 512, fps: renderFps, duration: 4 });
}
async function generate({ portraitBlob, modelBaseUrl }) {
postProgress(2, "准备肖像");
const image = await preprocessPortrait(portraitBlob);
const keys = ["appearanceFeatureExtractor", "motionExtractor", "stitchingLip", "stitching", "warping", "spadeGenerator"];
const downloadState = {
completed: 0,
total: keys.reduce((sum, key) => sum + (LIVE_PORTRAIT_WEB_MODEL.knownArtifacts[key]?.bytes ?? 0), 0),
};
const sessions = {};
for (const key of keys) sessions[key] = await loadSession(key, modelBaseUrl, downloadState);
postProgress(63, "提取人物特征");
const feature = (await sessions.appearanceFeatureExtractor.run({ img: image })).output;
const motion = await sessions.motionExtractor.run({ img: image });
const source = transformKeypoints(motion);
const driving = await retargetAndStitch(sessions.stitchingLip, sessions.stitching, source, 0.35);
postProgress(70, "计算 3D 形变(可能需要约 1 分钟)");
const warped = await sessions.warping.run({
feature_3d: feature,
kp_source: tensor(source, [1, 21, 3]),
kp_driving: tensor(driving, [1, 21, 3]),
});
postProgress(86, "渲染 512×512 人像");
const generated = await sessions.spadeGenerator.run({ input: warped["879"] });
const blob = await outputToBlob(generated.output);
postProgress(100, "单帧验收完成");
self.postMessage({ type: "result", blob, width: 512, height: 512 });
}
async function probe({ modelBaseUrl }) {
const bytes = LIVE_PORTRAIT_WEB_MODEL.knownArtifacts.stitching.bytes;
const session = await loadSession("stitching", modelBaseUrl, { completed: 0, total: bytes });
session.release();
self.postMessage({ type: "ready", backend: "wasm" });
}
self.onmessage = (event) => {
const task = event.data?.type === "generateVideo"
? generateVideo
: event.data?.type === "generate"
? generate
: event.data?.type === "probe"
? probe
: null;
if (!task) return;
task(event.data).catch((error) => {
self.postMessage({ type: "error", message: error instanceof Error ? error.message : String(error) });
});
};