lipsync-2d 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,153 @@
1
+ """Verify exported Blender .py scripts in real headless Blender and Godot .tres in real headless Godot 4."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+ from pathlib import Path
10
+
11
+ from lipsync_2d.cli import main as cli_main
12
+
13
+
14
+ def verify_blender_and_godot(wav_path: Path, onnx_path: Path) -> dict[str, object]:
15
+ blender_bin = shutil.which("blender")
16
+ godot_bin = shutil.which("godot")
17
+ if not blender_bin or not godot_bin:
18
+ raise RuntimeError(f"Missing DCC binary: blender={blender_bin}, godot={godot_bin}")
19
+
20
+ root = Path(__file__).resolve().parents[1]
21
+ pkg_dir = root / "packages" / "lipsync-2d-web"
22
+
23
+ with tempfile.TemporaryDirectory() as td:
24
+ td_p = Path(td)
25
+ py_blender = td_p / "py_mouth.py"
26
+ py_godot = td_p / "py_mouth.tres"
27
+ py_json = td_p / "py_cues.json"
28
+ assert cli_main([str(wav_path), "-m", str(onnx_path), "-f", "blender", "-o", str(py_blender)]) == 0
29
+ assert cli_main([str(wav_path), "-m", str(onnx_path), "-f", "godot", "-o", str(py_godot)]) == 0
30
+ assert cli_main([str(wav_path), "-m", str(onnx_path), "-f", "json", "-o", str(py_json)]) == 0
31
+
32
+ # Also generate TypeScript Blender & Godot exports from the exact same cues
33
+ ts_blender = td_p / "ts_mouth.py"
34
+ ts_godot = td_p / "ts_mouth.tres"
35
+ ts_gen = td_p / "gen_ts.mjs"
36
+ ts_gen.write_text(
37
+ f"""
38
+ import fs from "node:fs";
39
+ import {{ toBlenderPython, toGodotTres }} from "{(pkg_dir / 'dist' / 'index.js').as_posix()}";
40
+ const data = JSON.parse(fs.readFileSync({json.dumps(str(py_json))}, "utf8"));
41
+ const cues = data.mouthCues.map(c => ({{ ...c, confidence: 1.0 }}));
42
+ fs.writeFileSync({json.dumps(str(ts_blender))}, toBlenderPython(cues, 24));
43
+ fs.writeFileSync({json.dumps(str(ts_godot))}, toGodotTres(cues, data.metadata.duration));
44
+ """,
45
+ encoding="utf-8",
46
+ )
47
+ subprocess.run(["node", str(ts_gen)], check=True, cwd=str(pkg_dir))
48
+
49
+ # 1. Execute BOTH Python and TS Blender scripts in real headless Blender
50
+ blender_harness = td_p / "run_blender_check.py"
51
+ blender_harness.write_text(
52
+ f"""
53
+ import bpy, runpy
54
+
55
+ def iter_fcurves(action):
56
+ if hasattr(action, "fcurves"):
57
+ return list(action.fcurves)
58
+ out = []
59
+ for layer in getattr(action, "layers", ()):
60
+ for strip in getattr(layer, "strips", ()):
61
+ for bag in getattr(strip, "channelbags", ()):
62
+ out.extend(getattr(bag, "fcurves", ()))
63
+ return out
64
+
65
+ # Test Python CLI export on CharacterHead
66
+ bpy.ops.mesh.primitive_cube_add()
67
+ head = bpy.context.active_object
68
+ head.name = "CharacterHead"
69
+ runpy.run_path({json.dumps(str(py_blender))}, run_name="__main__")
70
+ fcs_py = iter_fcurves(head.animation_data.action)
71
+ paths_py = {{fc.data_path: len(fc.keyframe_points) for fc in fcs_py}}
72
+ assert '["rhubarb_viseme"]' in paths_py and paths_py['["rhubarb_viseme"]'] >= 2, f"Missing py keyframes: {{paths_py}}"
73
+ assert '["jaw_open"]' in paths_py, f"Missing jaw_open keyframes: {{paths_py}}"
74
+ for fc in fcs_py:
75
+ if fc.data_path == '["rhubarb_viseme"]':
76
+ assert all(kp.interpolation == "CONSTANT" for kp in fc.keyframe_points)
77
+
78
+ # Test TypeScript export on MouthRig
79
+ bpy.ops.mesh.primitive_cube_add()
80
+ rig = bpy.context.active_object
81
+ rig.name = "MouthRig"
82
+ runpy.run_path({json.dumps(str(ts_blender))}, run_name="__main__")
83
+ fcs_ts = iter_fcurves(rig.animation_data.action)
84
+ paths_ts = {{fc.data_path: len(fc.keyframe_points) for fc in fcs_ts}}
85
+ assert '["mouth_shape"]' in paths_ts and paths_ts['["mouth_shape"]'] >= 2, f"Missing ts keyframes: {{paths_ts}}"
86
+ for fc in fcs_ts:
87
+ if fc.data_path == '["mouth_shape"]':
88
+ assert all(kp.interpolation == "CONSTANT" for kp in fc.keyframe_points)
89
+
90
+ print("BLENDER_OK", paths_py, paths_ts)
91
+ """,
92
+ encoding="utf-8",
93
+ )
94
+ b_res = subprocess.run(
95
+ [blender_bin, "--background", "--factory-startup", "--python-exit-code", "1", "--python", str(blender_harness)],
96
+ capture_output=True,
97
+ text=True,
98
+ check=True,
99
+ )
100
+ assert "BLENDER_OK" in b_res.stdout, b_res.stdout + b_res.stderr
101
+
102
+ # 2. Load BOTH Python and TS Godot .tres animations in real headless Godot 4
103
+ gd_dir = td_p / "godot_proj"
104
+ gd_dir.mkdir()
105
+ (gd_dir / "project.godot").write_text(
106
+ 'config_version=5\n\n[application]\nconfig/name="LipSyncCheck"\n',
107
+ encoding="utf-8",
108
+ )
109
+ shutil.copy(py_godot, gd_dir / "py_mouth.tres")
110
+ shutil.copy(ts_godot, gd_dir / "ts_mouth.tres")
111
+ (gd_dir / "check.gd").write_text(
112
+ """extends SceneTree
113
+ func _init():
114
+ var a1 = ResourceLoader.load("res://py_mouth.tres")
115
+ var a2 = ResourceLoader.load("res://ts_mouth.tres")
116
+ if not (a1 is Animation) or not (a2 is Animation):
117
+ push_error("Failed to load Animation .tres")
118
+ quit(1)
119
+ return
120
+ if a1.get_track_count() < 4 or a1.track_get_key_count(0) < 2:
121
+ push_error("Unexpected py Animation track/key counts")
122
+ quit(1)
123
+ return
124
+ if a2.get_track_count() < 1 or a2.track_get_key_count(0) < 2:
125
+ push_error("Unexpected ts Animation track/key counts")
126
+ quit(1)
127
+ return
128
+ print("GODOT_OK py_tracks=", a1.get_track_count(), " py_keys=", a1.track_get_key_count(0), " ts_tracks=", a2.get_track_count(), " ts_keys=", a2.track_get_key_count(0))
129
+ quit(0)
130
+ """,
131
+ encoding="utf-8",
132
+ )
133
+ g_res = subprocess.run(
134
+ [godot_bin, "--headless", "--path", str(gd_dir), "--script", "res://check.gd"],
135
+ capture_output=True,
136
+ text=True,
137
+ check=True,
138
+ )
139
+ assert "GODOT_OK" in g_res.stdout, g_res.stdout + g_res.stderr
140
+
141
+ return {
142
+ "blender": [ln for ln in b_res.stdout.splitlines() if "BLENDER_OK" in ln][-1],
143
+ "godot": [ln for ln in g_res.stdout.splitlines() if "GODOT_OK" in ln][-1],
144
+ }
145
+
146
+
147
+ if __name__ == "__main__":
148
+ root = Path(__file__).resolve().parents[1]
149
+ out = verify_blender_and_godot(
150
+ root / "web" / "public" / "samples" / "hello_studio.wav",
151
+ root / "web" / "public" / "models" / "lipsync2d.onnx",
152
+ )
153
+ print(json.dumps(out, indent=2))
@@ -0,0 +1,182 @@
1
+ """Verify end-to-end Python <-> TypeScript Mel + ONNX inference parity."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import subprocess
8
+ import tempfile
9
+ import wave
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+ import onnxruntime as ort
14
+
15
+ from lipsync_2d.features import extract_log_mel_np, normalize_speech_rms
16
+
17
+
18
+ def load_wav_mono_16k(path: Path) -> np.ndarray:
19
+ with wave.open(str(path), "rb") as wf:
20
+ sr = wf.getframerate()
21
+ ch = wf.getnchannels()
22
+ sw = wf.getsampwidth()
23
+ raw = wf.readframes(wf.getnframes())
24
+ if sw != 2:
25
+ raise ValueError(f"Expected 16-bit PCM WAV, got sample width {sw}")
26
+ data = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0
27
+ if ch > 1:
28
+ data = data.reshape(-1, ch).mean(axis=1)
29
+ if sr != 16000:
30
+ n_out = int(round(len(data) * 16000 / sr))
31
+ x_old = np.linspace(0.0, 1.0, len(data), endpoint=False)
32
+ x_new = np.linspace(0.0, 1.0, n_out, endpoint=False)
33
+ data = np.interp(x_new, x_old, data).astype(np.float32)
34
+ return data.astype(np.float32)
35
+
36
+
37
+ def run_parity_check(wav_path: Path, offline_onnx: Path, streaming_onnx: Path | None = None) -> dict[str, float]:
38
+ root = Path(__file__).resolve().parents[1]
39
+ pkg_dir = root / "packages" / "lipsync-2d-web"
40
+ pcm = load_wav_mono_16k(wav_path)
41
+ py_pcm_norm = normalize_speech_rms(pcm)
42
+ py_quiet_norm = normalize_speech_rms((pcm * 0.05).astype(np.float32))
43
+ py_mel = extract_log_mel_np(py_pcm_norm, norm="fixed", causal=True)
44
+
45
+ sess_off = ort.InferenceSession(str(offline_onnx), providers=["CPUExecutionProvider"])
46
+ py_v15, py_r9, py_curves = sess_off.run(None, {"mel": py_mel[None, :, :].astype(np.float32)})
47
+
48
+ py_stream_r9 = None
49
+ if streaming_onnx is not None:
50
+ sess_st = ort.InferenceSession(str(streaming_onnx), providers=["CPUExecutionProvider"])
51
+ in_shapes = {i.name: i.shape for i in sess_st.get_inputs()}
52
+ h_shape = tuple(int(d) if isinstance(d, int) and d > 0 else 1 for d in in_shapes["h_in"])
53
+ c_shape = tuple(int(d) if isinstance(d, int) and d > 0 else 1 for d in in_shapes["conv_cache_in"])
54
+ h = np.zeros(h_shape, dtype=np.float32)
55
+ c = np.zeros(c_shape, dtype=np.float32)
56
+ chunks = []
57
+ t_even = (py_mel.shape[0] // 2) * 2
58
+ for pos in range(0, t_even, 4):
59
+ chunk = py_mel[pos : pos + 4]
60
+ if chunk.shape[0] < 2:
61
+ break
62
+ _, r9_c, _, h, c = sess_st.run(
63
+ None,
64
+ {"mel_chunk": chunk[None, :, :].astype(np.float32), "h_in": h, "conv_cache_in": c},
65
+ )
66
+ chunks.append(r9_c[0])
67
+ py_stream_r9 = np.concatenate(chunks, axis=0)
68
+
69
+ with tempfile.TemporaryDirectory() as td:
70
+ td_path = Path(td)
71
+ pcm_bin = td_path / "pcm.f32"
72
+ pcm.tofile(pcm_bin)
73
+ out_json = td_path / "ts_out.json"
74
+ runner = td_path / "run_ts.mjs"
75
+ runner.write_text(
76
+ f"""
77
+ import fs from "node:fs";
78
+ import * as ort from "{(pkg_dir / 'node_modules' / 'onnxruntime-web' / 'dist' / 'ort.min.mjs').as_posix()}";
79
+ import {{ LogMelExtractor, normalizeSpeechRms, N_MELS, HIDDEN_STATE_SHAPE, HIDDEN_STATE_SIZE, CONV_CACHE_SHAPE, CONV_CACHE_SIZE }} from "{(pkg_dir / 'dist' / 'index.js').as_posix()}";
80
+
81
+ ort.env.wasm.numThreads = 1;
82
+ const raw = fs.readFileSync({json.dumps(str(pcm_bin))});
83
+ const pcm = new Float32Array(raw.buffer, raw.byteOffset, raw.byteLength / 4);
84
+ const pcmNorm = normalizeSpeechRms(pcm);
85
+ const quietPcm = new Float32Array(pcm.length);
86
+ for (let i = 0; i < pcm.length; i++) quietPcm[i] = pcm[i] * 0.05;
87
+ const quietNorm = normalizeSpeechRms(quietPcm);
88
+ const extractor = new LogMelExtractor();
89
+ const mel = extractor.extract(pcmNorm, {{ causal: true, standardize: "fixed" }});
90
+
91
+ const offBytes = fs.readFileSync({json.dumps(str(offline_onnx.resolve()))});
92
+ const offSess = await ort.InferenceSession.create(offBytes, {{ executionProviders: ["wasm"] }});
93
+ const offOut = await offSess.run({{ mel: new ort.Tensor("float32", mel.data, [1, mel.frames, N_MELS]) }});
94
+
95
+ let streamR9 = null;
96
+ const streamPath = {json.dumps(str(streaming_onnx.resolve()) if streaming_onnx else "")};
97
+ if (streamPath) {{
98
+ const stBytes = fs.readFileSync(streamPath);
99
+ const stSess = await ort.InferenceSession.create(stBytes, {{ executionProviders: ["wasm"] }});
100
+ let h = new Float32Array(HIDDEN_STATE_SIZE);
101
+ let c = new Float32Array(CONV_CACHE_SIZE);
102
+ const tEven = Math.floor(mel.frames / 2) * 2;
103
+ const parts = [];
104
+ for (let pos = 0; pos < tEven; pos += 4) {{
105
+ const len = Math.min(4, tEven - pos);
106
+ if (len < 2) break;
107
+ const sub = mel.data.subarray(pos * N_MELS, (pos + len) * N_MELS);
108
+ const res = await stSess.run({{
109
+ mel_chunk: new ort.Tensor("float32", sub, [1, len, N_MELS]),
110
+ h_in: new ort.Tensor("float32", h, [...HIDDEN_STATE_SHAPE]),
111
+ conv_cache_in: new ort.Tensor("float32", c, [...CONV_CACHE_SHAPE]),
112
+ }});
113
+ parts.push(...Array.from(res.rhubarb9_logits.data));
114
+ h = new Float32Array(res.h_out.data);
115
+ c = new Float32Array(res.conv_cache_out.data);
116
+ }}
117
+ streamR9 = parts;
118
+ }}
119
+
120
+ fs.writeFileSync({json.dumps(str(out_json))}, JSON.stringify({{
121
+ quiet_norm: Array.from(quietNorm),
122
+ mel_frames: mel.frames,
123
+ mel_data: Array.from(mel.data),
124
+ v15: Array.from(offOut.viseme15_logits.data),
125
+ r9: Array.from(offOut.rhubarb9_logits.data),
126
+ curves: Array.from(offOut.mouth_curves.data),
127
+ stream_r9: streamR9,
128
+ }}));
129
+ """,
130
+ encoding="utf-8",
131
+ )
132
+ subprocess.run(["node", str(runner)], check=True, cwd=str(pkg_dir))
133
+ ts = json.loads(out_json.read_text(encoding="utf-8"))
134
+
135
+ ts_quiet_norm = np.asarray(ts["quiet_norm"], dtype=np.float32)
136
+ ts_mel = np.asarray(ts["mel_data"], dtype=np.float32).reshape(ts["mel_frames"], 80)
137
+ ts_v15 = np.asarray(ts["v15"], dtype=np.float32).reshape(py_v15.shape)
138
+ ts_r9 = np.asarray(ts["r9"], dtype=np.float32).reshape(py_r9.shape)
139
+ ts_curves = np.asarray(ts["curves"], dtype=np.float32).reshape(py_curves.shape)
140
+
141
+ metrics = {
142
+ "max_abs_rms_norm_diff": float(np.max(np.abs(py_quiet_norm - ts_quiet_norm))),
143
+ "max_abs_mel_diff": float(np.max(np.abs(py_mel - ts_mel))),
144
+ "max_abs_v15_logit_diff": float(np.max(np.abs(py_v15 - ts_v15))),
145
+ "max_abs_r9_logit_diff": float(np.max(np.abs(py_r9 - ts_r9))),
146
+ "max_abs_curves_diff": float(np.max(np.abs(py_curves - ts_curves))),
147
+ "r9_argmax_match_pct": float(
148
+ 100.0 * np.mean(np.argmax(py_r9[0], axis=-1) == np.argmax(ts_r9[0], axis=-1))
149
+ ),
150
+ }
151
+ if py_stream_r9 is not None and ts["stream_r9"] is not None:
152
+ ts_st = np.asarray(ts["stream_r9"], dtype=np.float32).reshape(py_stream_r9.shape)
153
+ metrics["max_abs_stream_r9_diff"] = float(np.max(np.abs(py_stream_r9 - ts_st)))
154
+ metrics["stream_r9_argmax_match_pct"] = float(
155
+ 100.0 * np.mean(np.argmax(py_stream_r9, axis=-1) == np.argmax(ts_st, axis=-1))
156
+ )
157
+ return metrics
158
+
159
+
160
+ def main() -> None:
161
+ parser = argparse.ArgumentParser(description="Verify Python <-> TypeScript ONNX inference parity.")
162
+ parser.add_argument("--wav", type=Path, required=True)
163
+ parser.add_argument("--offline-onnx", type=Path, required=True)
164
+ parser.add_argument("--streaming-onnx", type=Path, default=None)
165
+ parser.add_argument("--tol", type=float, default=1e-3, help="Max abs logit diff tolerance (default 1e-3 for FP32; use 5e-3 for FP16).")
166
+ args = parser.parse_args()
167
+
168
+ res = run_parity_check(args.wav, args.offline_onnx, args.streaming_onnx)
169
+ print(json.dumps(res, indent=2))
170
+ assert res["max_abs_rms_norm_diff"] < 1e-5, f"RMS norm parity failed: {res}"
171
+ assert res["max_abs_mel_diff"] < 1e-4, f"Mel parity failed: {res}"
172
+ assert res["max_abs_r9_logit_diff"] < args.tol, f"Offline r9 parity failed: {res}"
173
+ assert res["max_abs_v15_logit_diff"] < args.tol, f"Offline v15 parity failed: {res}"
174
+ assert res["max_abs_curves_diff"] < args.tol, f"Offline curves parity failed: {res}"
175
+ assert res["r9_argmax_match_pct"] == 100.0, f"Offline argmax mismatch: {res}"
176
+ if "max_abs_stream_r9_diff" in res:
177
+ assert res["max_abs_stream_r9_diff"] < args.tol, f"Streaming r9 parity failed: {res}"
178
+ assert res["stream_r9_argmax_match_pct"] == 100.0, f"Streaming argmax mismatch: {res}"
179
+
180
+
181
+ if __name__ == "__main__":
182
+ main()
lipsync_2d/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """Real-time multilingual 2D lip-sync and viseme prediction."""
2
+
3
+ from lipsync_2d.ctc_align import ctc_posteriors_to_spans, detect_speech_activity
4
+ from lipsync_2d.visemes import (
5
+ OCULUS_VISEMES,
6
+ RHUBARB_SHAPES,
7
+ VISEME15_TO_RHUBARB9_IDX,
8
+ build_vocab_projection_matrices,
9
+ ipa_to_rhubarb9,
10
+ ipa_to_viseme15,
11
+ load_xlsr_espeak_vocab,
12
+ viseme15_to_rhubarb9,
13
+ )
14
+
15
+ __all__ = [
16
+ "OCULUS_VISEMES",
17
+ "RHUBARB_SHAPES",
18
+ "VISEME15_TO_RHUBARB9_IDX",
19
+ "build_vocab_projection_matrices",
20
+ "ctc_posteriors_to_spans",
21
+ "detect_speech_activity",
22
+ "ipa_to_rhubarb9",
23
+ "ipa_to_viseme15",
24
+ "load_xlsr_espeak_vocab",
25
+ "viseme15_to_rhubarb9",
26
+ ]
lipsync_2d/cli.py ADDED
@@ -0,0 +1,212 @@
1
+ """Rhubarb-compatible CLI entrypoint for lipsync-2d."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ from scipy.io import wavfile
11
+ from scipy.signal import resample_poly
12
+
13
+ from lipsync_2d.decode import decode_cues
14
+ from lipsync_2d.exporters import (
15
+ export_blender_py,
16
+ export_godot_tres,
17
+ export_live2d_json,
18
+ export_rhubarb_json,
19
+ export_rhubarb_tsv,
20
+ export_rhubarb_xml,
21
+ )
22
+ from lipsync_2d.features import SAMPLE_RATE, compute_frame_energy_db, extract_log_mel_np, normalize_speech_rms
23
+
24
+ SUPPORTED_FORMATS: tuple[str, ...] = ("json", "tsv", "xml", "live2d", "godot", "blender")
25
+
26
+
27
+ def _softmax(logits: np.ndarray, axis: int = -1) -> np.ndarray:
28
+ shifted = logits - np.max(logits, axis=axis, keepdims=True)
29
+ exp = np.exp(shifted)
30
+ return exp / np.sum(exp, axis=axis, keepdims=True)
31
+
32
+
33
+ def load_wav_mono_16k(path: str | Path) -> tuple[np.ndarray, float]:
34
+ """Load a WAV file as float32 mono 16 kHz waveform and return (audio, duration_s)."""
35
+ sr, data = wavfile.read(str(path))
36
+ arr = np.asarray(data)
37
+ if arr.ndim == 2:
38
+ arr = arr.mean(axis=1)
39
+
40
+ if np.issubdtype(arr.dtype, np.integer):
41
+ info = np.iinfo(arr.dtype)
42
+ scale = float(max(abs(info.min), info.max))
43
+ wav = arr.astype(np.float32) / scale
44
+ else:
45
+ wav = arr.astype(np.float32)
46
+
47
+ duration = float(wav.shape[0]) / float(sr)
48
+ if sr != SAMPLE_RATE:
49
+ g = int(np.gcd(sr, SAMPLE_RATE))
50
+ wav = resample_poly(wav, SAMPLE_RATE // g, sr // g).astype(np.float32)
51
+ return wav, duration
52
+
53
+
54
+ def run_inference(
55
+ model_path: str | Path,
56
+ mel: np.ndarray,
57
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
58
+ """Run offline ONNX or PyTorch checkpoint inference on [T_10ms, 80] Mel frames."""
59
+ path = Path(model_path)
60
+ if not path.exists():
61
+ raise FileNotFoundError(f"Model file not found: {path}")
62
+
63
+ mel_batch = mel[None, :, :].astype(np.float32)
64
+ if path.suffix.lower() == ".onnx":
65
+ import onnxruntime as ort
66
+
67
+ session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
68
+ v15_logits, r9_logits, curves = session.run(None, {"mel": mel_batch})
69
+ return _softmax(v15_logits[0]), _softmax(r9_logits[0]), curves[0]
70
+
71
+ if path.suffix.lower() in (".pt", ".pth"):
72
+ import torch
73
+ from lipsync_2d.model import LipSyncStudent, ModelConfig
74
+
75
+ ckpt = torch.load(str(path), map_location="cpu", weights_only=False)
76
+ cfg = ModelConfig(**ckpt["config"]) if isinstance(ckpt, dict) and "config" in ckpt else ModelConfig()
77
+ state = ckpt["model_state_dict"] if isinstance(ckpt, dict) and "model_state_dict" in ckpt else ckpt
78
+ model = LipSyncStudent(cfg).eval()
79
+ model.load_state_dict(state)
80
+ with torch.no_grad():
81
+ v15_logits, r9_logits, curves = model(torch.from_numpy(mel_batch))
82
+ return (
83
+ _softmax(v15_logits[0].numpy()),
84
+ _softmax(r9_logits[0].numpy()),
85
+ curves[0].numpy(),
86
+ )
87
+
88
+ raise ValueError(f"Unsupported model extension {path.suffix!r}; expected .onnx, .pt, or .pth")
89
+
90
+
91
+ def resolve_model_path(model_arg: Path | None, repo_id: str, variant: str = "fp16") -> Path:
92
+ """Resolve explicit --model path, LIPSYNC_2D_MODEL env var, or auto-download from HF Hub."""
93
+ import os
94
+
95
+ if model_arg is not None:
96
+ return model_arg
97
+ env_path = os.environ.get("LIPSYNC_2D_MODEL")
98
+ if env_path:
99
+ return Path(env_path)
100
+ filename = f"onnx/lipsync_student_offline_{variant}.onnx"
101
+ try:
102
+ from huggingface_hub import hf_hub_download
103
+
104
+ downloaded = hf_hub_download(repo_id=repo_id, filename=filename, repo_type="model")
105
+ return Path(downloaded)
106
+ except Exception as exc:
107
+ raise FileNotFoundError(
108
+ f"No --model specified and auto-download of {repo_id}/{filename} failed ({exc}). "
109
+ "Pass --model path/to/lipsync_student_offline_fp16.onnx or set LIPSYNC_2D_MODEL."
110
+ ) from exc
111
+
112
+
113
+ def build_parser() -> argparse.ArgumentParser:
114
+ import os
115
+
116
+ parser = argparse.ArgumentParser(
117
+ prog="lipsync-2d",
118
+ description="Real-time multilingual 2D lip-sync and viseme generator.",
119
+ )
120
+ parser.add_argument("input_wav", type=Path, help="Input WAV audio file")
121
+ parser.add_argument(
122
+ "-f",
123
+ "--exportFormat",
124
+ dest="export_format",
125
+ choices=SUPPORTED_FORMATS,
126
+ default="json",
127
+ help="Output format (json, tsv, xml, live2d, godot, blender)",
128
+ )
129
+ parser.add_argument("-o", "--output", type=Path, default=None, help="Output file path (default: stdout)")
130
+ parser.add_argument(
131
+ "-m",
132
+ "--model",
133
+ type=Path,
134
+ default=None,
135
+ help="Path to .onnx or .pt student model (omit to auto-download from Hugging Face Hub)",
136
+ )
137
+ parser.add_argument(
138
+ "--repo-id",
139
+ type=str,
140
+ default=os.environ.get("LIPSYNC_2D_HF_REPO", "Lumonopolis/lipsync-2d"),
141
+ help="Hugging Face model repo ID for auto-download when --model is omitted",
142
+ )
143
+ parser.add_argument(
144
+ "--precision",
145
+ choices=("fp16", "int8", "fp32"),
146
+ default="fp16",
147
+ help="Model precision to auto-download when --model is omitted",
148
+ )
149
+ parser.add_argument("--switch-penalty", type=float, default=1.2, help="Viterbi transition switch penalty")
150
+ parser.add_argument("--min-duration-ms", type=float, default=40.0, help="Minimum non-plosive cue duration (ms)")
151
+ parser.add_argument("--fps", type=float, default=24.0, help="Target scene FPS for Blender export")
152
+ return parser
153
+
154
+
155
+ def main(argv: list[str] | None = None) -> int:
156
+ parser = build_parser()
157
+ args = parser.parse_args(argv)
158
+
159
+ if not args.input_wav.exists():
160
+ print(f"Error: input audio not found: {args.input_wav}", file=sys.stderr)
161
+ return 2
162
+
163
+ try:
164
+ model_path = resolve_model_path(args.model, args.repo_id, args.precision)
165
+ wav, duration = load_wav_mono_16k(args.input_wav)
166
+ wav_norm = normalize_speech_rms(wav)
167
+ mel = extract_log_mel_np(wav_norm, norm="fixed", causal=True)
168
+ rms_db = compute_frame_energy_db(wav_norm, frame_ms=20)
169
+ v15_probs, r9_probs, curves = run_inference(model_path, mel)
170
+ n_frames = min(r9_probs.shape[0], rms_db.shape[0]) if rms_db.size > 0 else r9_probs.shape[0]
171
+ rms_aligned = rms_db[:n_frames] if rms_db.size >= n_frames else None
172
+ cues = decode_cues(
173
+ r9_probs[:n_frames],
174
+ switch_penalty=args.switch_penalty,
175
+ min_duration_ms=args.min_duration_ms,
176
+ audio_rms_db=rms_aligned,
177
+ )
178
+
179
+ fmt = args.export_format
180
+ if fmt == "json":
181
+ text = export_rhubarb_json(cues, args.input_wav.name, duration)
182
+ elif fmt == "tsv":
183
+ text = export_rhubarb_tsv(cues)
184
+ elif fmt == "xml":
185
+ text = export_rhubarb_xml(cues, args.input_wav.name, duration)
186
+ elif fmt == "live2d":
187
+ text = export_live2d_json(v15_probs[:n_frames], r9_probs[:n_frames], curves[:n_frames])
188
+ elif fmt == "godot":
189
+ text = export_godot_tres(cues, mouth_curves=curves[:n_frames])
190
+ elif fmt == "blender":
191
+ text = export_blender_py(
192
+ cues,
193
+ viseme15_probs=v15_probs[:n_frames],
194
+ mouth_curves=curves[:n_frames],
195
+ fps=args.fps,
196
+ )
197
+ else:
198
+ raise ValueError(f"Unsupported format: {fmt}")
199
+
200
+ if args.output is not None:
201
+ args.output.parent.mkdir(parents=True, exist_ok=True)
202
+ args.output.write_text(text, encoding="utf-8")
203
+ else:
204
+ sys.stdout.write(text)
205
+ except Exception as exc:
206
+ print(f"Error: {exc}", file=sys.stderr)
207
+ return 1
208
+ return 0
209
+
210
+
211
+ if __name__ == "__main__":
212
+ raise SystemExit(main())