-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathnodes.py
More file actions
4922 lines (4558 loc) · 244 KB
/
Copy pathnodes.py
File metadata and controls
4922 lines (4558 loc) · 244 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2025 kijai (Jukka Seppänen) — original ComfyUI-WanAnimatePreprocess
# https://github.com/kijai/ComfyUI-WanAnimatePreprocess
# Apache License 2.0
#
# Copyright 2025 steven850 — improved pose/face pipeline (CLAHE, temporal
# smoothing, constant-size face box, blur preprocessing)
# Contributed in issue #10 of ComfyUI-WanAnimatePreprocess:
# https://github.com/kijai/ComfyUI-WanAnimatePreprocess/issues/10
# Apache License 2.0 (contributed to an Apache-2.0 repo)
#
# Copyright 2025-2026 Code2Collapse (https://github.com/Code2Collapse)
# Additional work: iris/pupil detection (gradient voting, Timm-Barth
# inspired multi-strategy), MediaPipe FaceMesh integration,
# protobuf-5.x compatibility fix, V2 extensions and enhancements
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ---- Modifications by Code2Collapse (2025-2026) relative to steven850/kijai base ----
# - Added MediaPipe FaceMesh 478-point landmark pipeline with iris/gaze tracking
# - Added protobuf >=5.x compatibility fix for mediapipe <=0.10.x
# - Added gradient-based pupil centre detection (Timm-Barth 2011 inspired)
# - Added multi-strategy iris fallback (contour moments + weighted centroid)
# - Added iris/gaze overlay to debug visualisation
# - Added lip openness ratio output
# - Renamed nodes to V2 namespace; added RETURN_TYPES for iris/gaze/lip outputs
import os
import torch
from tqdm import tqdm
import numpy as np
import folder_paths
import cv2
import json
import logging
import math
from typing import Any, Dict, List, Optional, Tuple
from . import _interrupt_check as _IC
from ._is_changed_util import hash_args_and_kwargs
script_directory = os.path.dirname(os.path.abspath(__file__))
# ---------------------------------------------------
# Optional MediaPipe Face Mesh (graceful fallback)
# ---------------------------------------------------
# MediaPipe provides 478 facial landmarks (468 mesh + 10 iris when
# refine_landmarks=True). It dramatically improves iris/lip tracking
# fidelity compared to the 68-point ViTPose face output and the custom
# OpenCV pupil voter. If `mediapipe` is not installed, the pipeline
# transparently falls back to the legacy ViTPose + `_find_pupil_center`
# code path and keeps working.
try:
import mediapipe as _mp
_MP_AVAILABLE = True
except Exception as _mp_err: # ImportError or runtime DLL issues
_mp = None
_MP_AVAILABLE = False
logging.getLogger(__name__).info(
"MediaPipe not available, falling back to ViTPose-only face pipeline (%s)",
_mp_err,
)
# Module-level FaceMesh handle (lazily constructed, reused across frames).
_MP_FACE_MESH = None
def _get_mp_face_mesh():
"""Lazily construct a single static-image FaceMesh with iris refinement.
MANUAL bug-fix (Apr 2026): mediapipe <=0.10.x's solution_base.py reads
``FieldDescriptor.label`` which was removed in protobuf 5.x. That raises
``AttributeError: 'google._upb._message.FieldDescriptor' object has no
attribute 'label'`` during ``FaceMesh()`` construction. We catch it,
log a clear remediation, and permanently disable mediapipe for this
process so the existing ViTPose-only fallback is used instead.
"""
global _MP_FACE_MESH, _MP_AVAILABLE
if not _MP_AVAILABLE:
return None
if _MP_FACE_MESH is None:
try:
_MP_FACE_MESH = _mp.solutions.face_mesh.FaceMesh(
static_image_mode=True,
max_num_faces=1,
refine_landmarks=True, # enables 10 iris landmarks (468-477)
min_detection_confidence=0.3,
min_tracking_confidence=0.3,
)
except AttributeError as exc:
_MP_AVAILABLE = False
_MP_FACE_MESH = None
logging.getLogger(__name__).warning(
"MediaPipe FaceMesh init failed (%s). This is a known "
"mediapipe<=0.10.x vs protobuf>=5.x incompatibility. "
"Fix: pip install --upgrade mediapipe (>=0.10.18) OR "
"pip install \"protobuf<=3.20.3\". Falling back to "
"ViTPose-only face pipeline for the rest of this session.",
exc,
)
return None
except Exception as exc: # noqa: BLE001 - any runtime failure -> fallback
_MP_AVAILABLE = False
_MP_FACE_MESH = None
logging.getLogger(__name__).warning(
"MediaPipe FaceMesh init failed (%s). Falling back to "
"ViTPose-only face pipeline for the rest of this session.",
exc,
)
return None
return _MP_FACE_MESH
# ---------------------------------------------------
# MediaPipe -> dlib 68 landmark mapping
# ---------------------------------------------------
# Wan 2.x face conditioning consumes the standard 68-point dlib layout
# (slotted into face_kps[1:69]; face_kps[0] is the body-anchored face
# centre coming from ViTPose). We slice the 478 MediaPipe FaceMesh
# vertices to reconstruct that exact ordering, so existing limbSeq /
# `draw_aapose_by_meta_new` visualisation and the Wan pose encoder keep
# working without modification.
#
# Layout (68 = 17+5+5+4+5+6+6+12+8):
# 0-16 jawline (right ear -> chin -> left ear)
# 17-21 right eyebrow
# 22-26 left eyebrow
# 27-30 nose bridge (top -> tip)
# 31-35 nose bottom (right nostril -> tip -> left nostril)
# 36-41 right eye (outer, upper-outer, upper-inner, inner, lower-inner, lower-outer)
# 42-47 left eye
# 48-59 outer lip (12 pts, clockwise from right corner)
# 60-67 inner lip (8 pts, clockwise from right corner)
MP_TO_DLIB68 = [
# Jaw 0-16
127, 234, 93, 132, 58, 172, 136, 150, 149, 176, 148, 152,
377, 400, 378, 379, 365,
# Right eyebrow 17-21
70, 63, 105, 66, 107,
# Left eyebrow 22-26
336, 296, 334, 293, 300,
# Nose bridge 27-30
168, 6, 197, 195,
# Nose bottom 31-35
115, 220, 4, 440, 344,
# Right eye 36-41
33, 160, 158, 133, 153, 144,
# Left eye 42-47
362, 385, 387, 263, 373, 380,
# Outer lip 48-59
61, 39, 37, 0, 267, 269, 291, 405, 314, 17, 84, 181,
# Inner lip 60-67
78, 81, 13, 311, 308, 402, 14, 178,
]
assert len(MP_TO_DLIB68) == 68, "MP -> dlib mapping must define exactly 68 indices"
# Iris landmarks (only present when refine_landmarks=True).
MP_RIGHT_IRIS_CENTER = 468
MP_LEFT_IRIS_CENTER = 473
MP_RIGHT_IRIS_RING = [469, 470, 471, 472]
MP_LEFT_IRIS_RING = [474, 475, 476, 477]
# Eye corner landmarks (same MediaPipe model as the iris — use these as
# the gaze reference frame instead of dlib eye-contour centroid. Reason:
# the dlib contour averages upper+lower eyelid points whose vertical
# spread is asymmetric (lower lid extends further than upper), biasing
# the centroid DOWN by ~2 px relative to the iris and producing a
# spurious "iris-is-up" signal even when the subject looks straight
# ahead. Eye-corner midpoint has no eyelid component, so vertical
# offset = true vertical gaze and horizontal offset = true horizontal
# gaze. Subject's right eye (viewer-left): outer=33 inner=133. Subject's
# left eye (viewer-right): inner=362 outer=263.
MP_RIGHT_EYE_OUTER = 33
MP_RIGHT_EYE_INNER = 133
MP_LEFT_EYE_INNER = 362
MP_LEFT_EYE_OUTER = 263
# Inner-lip indices used for "openness" (mouth aspect ratio).
# Vertical opening: top-inner (13) <-> bottom-inner (14).
# Horizontal width: right inner corner (78) <-> left inner corner (308).
MP_INNER_LIP_TOP = 13
MP_INNER_LIP_BOTTOM = 14
MP_INNER_LIP_RIGHT = 78
MP_INNER_LIP_LEFT = 308
def mediapipe_to_dlib_68(mp_landmarks_xy):
"""Slice the 478-point MediaPipe array down to the 68-point dlib layout.
Args:
mp_landmarks_xy: (478, 2) ndarray of (x, y) coordinates in any
consistent space (normalised or pixel).
Returns:
(68, 2) ndarray in the same coordinate space, ordered exactly as
dlib's 68-point shape predictor expects.
"""
return mp_landmarks_xy[MP_TO_DLIB68].copy()
# FaceMesh/FaceLandmarker need the face at a decent pixel size — the attention
# (iris) submesh loses the eye region below roughly ~200px faces. On full/half-
# body shots (the NORMAL Wan Animate input) the padded face crop is often only
# 60–120px → "no face found" / garbage iris = the user's "eye detection not at
# all working". Upscaling the CROP is free w.r.t. coordinate mapping because
# MediaPipe returns NORMALISED [0,1] coords (scale-invariant) that we multiply
# by the ORIGINAL crop_size_wh. Verified live: a 288px face crop failed raw,
# detected perfectly at 3× with iris rings exactly on the irises.
_MP_MIN_CROP_SIDE = 384
def _upscale_face_crop_if_small(face_crop_rgb_uint8):
"""Return the crop upscaled so its long side is >= _MP_MIN_CROP_SIDE."""
try:
h, w = face_crop_rgb_uint8.shape[:2]
side = max(h, w)
if side >= _MP_MIN_CROP_SIDE or side < 8:
return face_crop_rgb_uint8
s = _MP_MIN_CROP_SIDE / float(side)
return cv2.resize(face_crop_rgb_uint8, (max(8, int(round(w * s))), max(8, int(round(h * s)))),
interpolation=cv2.INTER_CUBIC)
except Exception:
return face_crop_rgb_uint8
def _run_mediapipe_on_face_crop(face_crop_rgb_uint8, crop_origin_xy, crop_size_wh,
full_w, full_h):
"""Run MediaPipe FaceMesh on a single face crop.
Args:
face_crop_rgb_uint8: (h, w, 3) uint8 RGB face crop.
crop_origin_xy: (x1, y1) origin of the crop in the full image.
crop_size_wh: (cw, ch) pixel size of the crop.
full_w, full_h: full image pixel dimensions.
Returns:
dict with:
- 'kps68_norm' (68, 3) [x/W, y/H, conf=1.0] in *full image* normalised space
- 'right_iris_px', 'left_iris_px': (x, y) in full image pixel space
- 'right_iris_radius_px', 'left_iris_radius_px': float
- 'lip_openness_ratio': float (vertical inner-lip / inner-lip width)
Or None if MediaPipe failed to detect a face.
"""
fm = _get_mp_face_mesh()
if fm is None or face_crop_rgb_uint8 is None or face_crop_rgb_uint8.size == 0:
return None
try:
results = fm.process(_upscale_face_crop_if_small(face_crop_rgb_uint8))
except Exception:
return None
if not results.multi_face_landmarks:
return None
lms = results.multi_face_landmarks[0].landmark
if len(lms) < 478:
# Iris landmarks missing - refine_landmarks must have been disabled
# at build time (e.g. older mediapipe). Treat as failure so we use
# the fallback path that includes iris voting.
return None
cx0, cy0 = crop_origin_xy
cw, ch = crop_size_wh
# MediaPipe gives normalised coords [0, 1] relative to the crop.
pts_px = np.zeros((len(lms), 2), dtype=np.float32)
for i, lm in enumerate(lms):
pts_px[i, 0] = lm.x * cw + cx0
pts_px[i, 1] = lm.y * ch + cy0
# Build the 68-point array in *full image* normalised space, with
# confidence forced to 1.0 (MediaPipe doesn't expose per-point conf).
kps68_px = pts_px[MP_TO_DLIB68]
kps68_norm = np.zeros((68, 3), dtype=np.float32)
kps68_norm[:, 0] = kps68_px[:, 0] / max(full_w, 1)
kps68_norm[:, 1] = kps68_px[:, 1] / max(full_h, 1)
kps68_norm[:, 2] = 1.0
# Iris centres (full image pixel space)
r_iris = pts_px[MP_RIGHT_IRIS_CENTER]
l_iris = pts_px[MP_LEFT_IRIS_CENTER]
r_ring = pts_px[MP_RIGHT_IRIS_RING]
l_ring = pts_px[MP_LEFT_IRIS_RING]
r_radius = float(np.mean(np.linalg.norm(r_ring - r_iris[None, :], axis=1)))
l_radius = float(np.mean(np.linalg.norm(l_ring - l_iris[None, :], axis=1)))
# Eye corners (full image pixel space) — used downstream as the
# gaze reference frame in lieu of dlib eye-contour centroid.
r_outer = pts_px[MP_RIGHT_EYE_OUTER]
r_inner = pts_px[MP_RIGHT_EYE_INNER]
l_inner = pts_px[MP_LEFT_EYE_INNER]
l_outer = pts_px[MP_LEFT_EYE_OUTER]
top = pts_px[MP_INNER_LIP_TOP]
bot = pts_px[MP_INNER_LIP_BOTTOM]
rgt = pts_px[MP_INNER_LIP_RIGHT]
lft = pts_px[MP_INNER_LIP_LEFT]
v = float(np.linalg.norm(top - bot))
h = float(np.linalg.norm(rgt - lft))
lip_ratio = float(v / h) if h > 1e-6 else 0.0
return {
'kps68_norm': kps68_norm,
'right_iris_px': (float(r_iris[0]), float(r_iris[1])),
'left_iris_px': (float(l_iris[0]), float(l_iris[1])),
'right_iris_radius_px': r_radius,
'left_iris_radius_px': l_radius,
'right_eye_outer_px': (float(r_outer[0]), float(r_outer[1])),
'right_eye_inner_px': (float(r_inner[0]), float(r_inner[1])),
'left_eye_inner_px': (float(l_inner[0]), float(l_inner[1])),
'left_eye_outer_px': (float(l_outer[0]), float(l_outer[1])),
'lip_openness_ratio': lip_ratio,
# Full 478-point MediaPipe mesh in FULL-FRAME pixel coords.
# Consumed by gaze_pose_norm for solvePnP head-pose estimation.
'landmarks_px_full': pts_px,
}
# ---------------------------------------------------
# Production gaze via FaceLandmarker Tasks API + blend shapes
# ---------------------------------------------------
# The Tasks API replaces the legacy `mp.solutions.face_mesh` glue and
# additionally returns 52 ARKit-compatible blend shapes per face. We use
# the eight `eyeLookIn/Out/Up/Down{Left,Right}` shapes to derive
# head-pose-corrected per-eye yaw/pitch in radians — i.e. real gaze
# angles, not 2D iris offsets. See `gaze_blendshape.py` for the math.
try:
from . import gaze_blendshape as _gaze_bs # type: ignore
_GAZE_BS_IMPORTED = True
except Exception as _exc: # noqa: BLE001
_gaze_bs = None
_GAZE_BS_IMPORTED = False
logging.getLogger(__name__).info(
"gaze_blendshape module unavailable (%s); blend-shape gaze disabled.",
_exc,
)
# Stage-1 gaze upgrade: solvePnP head pose + Kalman temporal smoother.
# Pure numpy + cv2, no extra downloads. Powers the
# `gaze_engine='blendshape_head_corrected'` widget option.
try:
from . import gaze_3d as _gaze_3d # type: ignore
_GAZE_3D_IMPORTED = True
except Exception as _exc: # noqa: BLE001
_gaze_3d = None
_GAZE_3D_IMPORTED = False
logging.getLogger(__name__).info(
"gaze_3d module unavailable (%s); head-pose gaze correction disabled.",
_exc,
)
# W7-G1 gaze upgrade: geometric (measured-iris) eye-in-head engine.
# MEASURES the iris position inside the eye aperture instead of estimating
# gaze with a NN; composes with the same solvePnP head pose + Kalman as
# blendshape_head_corrected. Pure math, no downloads.
try:
from . import gaze_iris_geometric as _gaze_iris # type: ignore
_GAZE_IRIS_IMPORTED = True
except Exception as _exc: # noqa: BLE001
_gaze_iris = None
_GAZE_IRIS_IMPORTED = False
logging.getLogger(__name__).info(
"gaze_iris_geometric module unavailable (%s); iris_geometric engine disabled.",
_exc,
)
# Stage-2 gaze upgrade: L2CS-Net (MIT license, ~3.9 deg MPIIGaze MAE,
# ~10.4 deg Gaze360 MAE — robust to extreme head poses). Optional; only
# imported when the user explicitly selects an `l2cs_*` engine.
try:
from . import gaze_l2cs as _gaze_l2cs # type: ignore
_GAZE_L2CS_IMPORTED = True
except Exception as _exc: # noqa: BLE001
_gaze_l2cs = None
_GAZE_L2CS_IMPORTED = False
logging.getLogger(__name__).debug(
"gaze_l2cs module unavailable (%s); L2CS-Net engine disabled.",
_exc,
)
# Stage-3 gaze upgrade: pose-normalized data preprocessing (clean-room
# port of the 2018 ETRA paper, Apache-2.0). Pure cv2+numpy; head-pose-
# invariant input warp.
try:
from . import gaze_pose_norm as _gaze_pose_norm # type: ignore
_GAZE_POSE_NORM_IMPORTED = True
except Exception as _exc: # noqa: BLE001
_gaze_pose_norm = None
_GAZE_POSE_NORM_IMPORTED = False
logging.getLogger(__name__).debug(
"gaze_pose_norm module unavailable (%s); pose normalization disabled.",
_exc,
)
# Pose-normalized ResNet50 gaze estimator (operates on the warped
# canonical face crop from gaze_pose_norm). Wraps a community-released
# checkpoint that the USER places at ComfyUI/models/gaze/ — see the
# license note in gaze_normalized_estimator.py for terms of use.
try:
from . import gaze_normalized_estimator as _gaze_normalized_estimator # type: ignore
_GAZE_NORM_EST_IMPORTED = True
except Exception as _exc: # noqa: BLE001
_gaze_normalized_estimator = None
_GAZE_NORM_EST_IMPORTED = False
logging.getLogger(__name__).debug(
"gaze_normalized_estimator module unavailable (%s); "
"pose_normalized_resnet50 engine disabled.",
_exc,
)
def _run_face_landmarker_on_face_crop(
face_crop_rgb_uint8, crop_origin_xy, crop_size_wh, full_w, full_h,
):
"""Run MediaPipe FaceLandmarker on a face crop and pack into the
same dict shape as :func:`_run_mediapipe_on_face_crop`, plus an
extra ``gaze`` entry derived from the eye-look blend shapes.
Returns ``None`` when the Tasks API is not available or no face was
found in the crop. Caller may fall back to FaceMesh.
"""
if not _GAZE_BS_IMPORTED or _gaze_bs is None:
return None
if face_crop_rgb_uint8 is None or face_crop_rgb_uint8.size == 0:
return None
# Same small-face upscale as the FaceMesh path — normalised coords make it
# transparent to the crop_size_wh mapping below.
res = _gaze_bs.run_face_landmarker(_upscale_face_crop_if_small(face_crop_rgb_uint8))
if res is None:
return None
landmarks = res["landmarks_norm"] # (478, 3) in [0,1] crop-space
if landmarks.shape[0] < 478:
return None
cx0, cy0 = crop_origin_xy
cw, ch = crop_size_wh
pts_px = np.empty((landmarks.shape[0], 2), dtype=np.float32)
pts_px[:, 0] = landmarks[:, 0] * cw + cx0
pts_px[:, 1] = landmarks[:, 1] * ch + cy0
kps68_px = pts_px[MP_TO_DLIB68]
kps68_norm = np.zeros((68, 3), dtype=np.float32)
kps68_norm[:, 0] = kps68_px[:, 0] / max(full_w, 1)
kps68_norm[:, 1] = kps68_px[:, 1] / max(full_h, 1)
kps68_norm[:, 2] = 1.0
r_iris = pts_px[MP_RIGHT_IRIS_CENTER]
l_iris = pts_px[MP_LEFT_IRIS_CENTER]
r_ring = pts_px[MP_RIGHT_IRIS_RING]
l_ring = pts_px[MP_LEFT_IRIS_RING]
r_radius = float(np.mean(np.linalg.norm(r_ring - r_iris[None, :], axis=1)))
l_radius = float(np.mean(np.linalg.norm(l_ring - l_iris[None, :], axis=1)))
r_outer = pts_px[MP_RIGHT_EYE_OUTER]
r_inner = pts_px[MP_RIGHT_EYE_INNER]
l_inner = pts_px[MP_LEFT_EYE_INNER]
l_outer = pts_px[MP_LEFT_EYE_OUTER]
top = pts_px[MP_INNER_LIP_TOP]
bot = pts_px[MP_INNER_LIP_BOTTOM]
rgt = pts_px[MP_INNER_LIP_RIGHT]
lft = pts_px[MP_INNER_LIP_LEFT]
v = float(np.linalg.norm(top - bot))
h = float(np.linalg.norm(rgt - lft))
lip_ratio = float(v / h) if h > 1e-6 else 0.0
gaze = _gaze_bs.blendshapes_to_gaze(res.get("blendshapes") or {})
# Stage-1: solvePnP head rotation from full-frame MediaPipe pixel
# landmarks. Used downstream to compose eye-in-head gaze with the
# head pose so the rendered arrow tracks rotated heads correctly.
R_head = None
if _GAZE_3D_IMPORTED and _gaze_3d is not None:
try:
hp = _gaze_3d.estimate_head_pose_from_pixels(
pts_px, (int(full_w), int(full_h)),
)
if hp is not None:
R_head = hp[0]
except Exception: # noqa: BLE001
R_head = None
return {
'kps68_norm': kps68_norm,
'right_iris_px': (float(r_iris[0]), float(r_iris[1])),
'left_iris_px': (float(l_iris[0]), float(l_iris[1])),
'right_iris_radius_px': r_radius,
'left_iris_radius_px': l_radius,
'right_eye_outer_px': (float(r_outer[0]), float(r_outer[1])),
'right_eye_inner_px': (float(r_inner[0]), float(r_inner[1])),
'left_eye_inner_px': (float(l_inner[0]), float(l_inner[1])),
'left_eye_outer_px': (float(l_outer[0]), float(l_outer[1])),
'lip_openness_ratio': lip_ratio,
# NEW: production gaze from blend shapes — head-pose corrected,
# in radians per eye, plus a 2D dx/dy for legacy debug overlay.
'gaze_blendshape': gaze,
'blendshapes': res.get("blendshapes") or {},
'face_transform': res.get("transform"),
'R_head': R_head,
'source': 'face_landmarker',
# Full 478-point MediaPipe mesh in FULL-FRAME pixel coords.
# Consumed by gaze_pose_norm for solvePnP head-pose estimation.
'landmarks_px_full': pts_px,
}
from comfy import model_management as mm
from comfy.utils import ProgressBar
device = mm.get_torch_device()
offload_device = mm.unet_offload_device()
folder_paths.add_model_folder_path("detection", os.path.join(folder_paths.models_dir, "detection"))
def _ensure_onnx_detection_support():
"""Make our nodes detect `.onnx` even when ComfyUI's folder extension
filter omits it. ComfyUI's `get_filename_list` only returns files whose
extension is registered for the folder; `.onnx` is not in the default set,
so detection models silently fail to list. We force-register `.onnx`
(plus the usual weight extensions) for the `detection` folder, creating the
entry and the directory if needed, and bust the filename cache.
"""
exts = {".onnx", ".pt", ".pth", ".safetensors", ".bin"}
extra_dirs = []
try:
det = os.path.join(folder_paths.models_dir, "detection")
os.makedirs(det, exist_ok=True)
extra_dirs.append(det)
# also surface a couple of common alt locations users drop ONNX into
for alt in ("onnx", "ultralytics", "vitpose", "yolo"):
p = os.path.join(folder_paths.models_dir, alt)
if os.path.isdir(p):
extra_dirs.append(p)
except Exception:
pass
try:
entry = folder_paths.folder_names_and_paths.get("detection")
if entry is None:
folder_paths.folder_names_and_paths["detection"] = (list(extra_dirs), set(exts))
else:
paths, e = entry[0], entry[1]
for d in extra_dirs:
if d not in paths:
paths.append(d)
try:
e.update(exts) # mutate existing set
except (AttributeError, TypeError):
folder_paths.folder_names_and_paths["detection"] = (paths, set(e) | exts)
except Exception as _e:
print(f"[WanAnimateV2] .onnx detection registration warning: {_e}")
# bust caches so the new extension takes effect immediately
for attr in ("filename_list_cache", "cache_helper"):
try:
c = getattr(folder_paths, attr, None)
if isinstance(c, dict):
c.pop("detection", None)
except Exception:
pass
_ensure_onnx_detection_support()
def list_onnx_detection_models():
"""Robust model list for the detection dropdowns: prefer ComfyUI's
`get_filename_list("detection")`, but ALSO scan the detection folder(s) on
disk for `*.onnx` directly — so files show up even if folder_paths refuses
to (the user's explicit requirement: ours must detect `.onnx` regardless).
"""
names = []
seen = set()
def _add(n):
if not n:
return
n = n.replace("\\", "/") # normalise so disk-scan + folder_paths dedupe
if n not in seen:
seen.add(n)
names.append(n)
try:
for n in folder_paths.get_filename_list("detection"):
_add(n)
except Exception:
pass
try:
for base in folder_paths.get_folder_paths("detection"):
if not base or not os.path.isdir(base):
continue
for root, _dirs, files in os.walk(base):
for f in files:
if f.lower().endswith((".onnx", ".pt", ".pth", ".safetensors")):
rel = os.path.relpath(os.path.join(root, f), base)
_add(rel.replace("\\", "/"))
except Exception:
pass
return names if names else ["(place .onnx models in ComfyUI/models/detection)"]
def _resolve_detection_path(name):
"""Path resolver that tolerates names discovered by the disk scan even if
folder_paths can't map them (mirrors list_onnx_detection_models)."""
try:
p = folder_paths.get_full_path("detection", name)
if p and os.path.exists(p):
return p
except Exception:
pass
try:
for base in folder_paths.get_folder_paths("detection"):
cand = os.path.join(base, name.replace("/", os.sep))
if os.path.exists(cand):
return cand
except Exception:
pass
raise FileNotFoundError(
f"Detection model {name!r} not found under ComfyUI/models/detection/. "
f"Place the .onnx file there (or check the name)."
)
from .models.onnx_models import ViTPose, Yolo
from .pose_utils.pose2d_utils import load_pose_metas_from_kp2ds_seq, crop, bbox_from_detector
from .utils import (
get_face_bboxes,
padding_resize,
adjust_bbox_eye_upper_third,
compute_eye_midpoint_from_face_kps,
compute_frame_blur_score,
compute_eye_region_brightness,
)
from .pose_utils.human_visualization import AAPoseMeta, draw_aapose_by_meta_new
from .retarget_pose import get_retarget_pose
# ---------------------------------------------------
# Image enhancement utilities
# ---------------------------------------------------
def preprocess_for_pose(img, use_clahe=True):
"""Optional CLAHE contrast enhancement for ViTPose inputs."""
if not use_clahe:
return img
img_uint8 = (np.clip(img, 0, 1) * 255).astype(np.uint8)
lab = cv2.cvtColor(img_uint8, cv2.COLOR_RGB2LAB)
l, a, b = cv2.split(lab)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
l = clahe.apply(l)
img_uint8 = cv2.cvtColor(cv2.merge((l, a, b)), cv2.COLOR_LAB2RGB)
return img_uint8.astype(np.float32) / 255.0
# ---------------------------------------------------
# Iris / pupil estimation (image-based)
# ---------------------------------------------------
# Eye contour landmark indices within the 69-point face array.
# face array = kp2ds[22:91]; index 0 is body, indices 1-68 are
# standard 68-face landmarks (standard N -> face[N+1]).
#
# Dlib-68 eye contour indices for the EXISTING ``face_kps`` array layout.
#
# CRITICAL INDEXING NOTE (verified May 2026 with live _gaze_debug.log):
# face_kps[0] is the body-anchored face anchor; face_kps[1:69] holds the
# 68 dlib landmarks (assigned via `face_kps[1:69, :] = mp_result['kps68_norm']`
# where kps68_norm is 0-indexed dlib order). So to access dlib's right-eye
# contour (dlib indices 36-41) we read array slots 37-42; for the left eye
# (dlib 42-47) we read array slots 43-48.
#
# History: A prior attempted fix changed these to [36..41]/[42..47]
# (commit cc608dd) on the assumption the array was 0-indexed dlib. Live
# diagnostics on a real frame proved otherwise: the LEFT-eye centroid was
# being contaminated by the lower-outer RIGHT-eye corner, dragging the
# centroid leftward and flipping (iris - centroid) to positive when the
# subject was actually looking left — i.e. arrow pointed RIGHT. Reverted.
_RIGHT_EYE_IDX = [37, 38, 39, 40, 41, 42]
_LEFT_EYE_IDX = [43, 44, 45, 46, 47, 48]
_EYE_CONTOUR_INDICES = [_RIGHT_EYE_IDX, _LEFT_EYE_IDX]
# Gaze-arrow rendering tunables.
# DEAD_ZONE_PX: iris-centroid offsets smaller than this are treated as
# noise (MediaPipe landmark precision is roughly 1px on cropped faces).
# Below the dead-zone we suppress the arrow entirely.
_GAZE_DEAD_ZONE_PX = 1.2
# Arrow length is scaled by gaze magnitude (offset / iris_radius) so
# subtle gazes show subtle arrows instead of always-35-pixel arrows. Hard
# floor + ceiling keep arrows in [0, MAX_ARROW_LEN_PX].
_GAZE_MAX_ARROW_LEN_PX = 35
_GAZE_MIN_ARROW_LEN_PX = 6
def _gradient_vote_pupil(roi_gray, mask, gc_local, eye_w, eye_h):
"""Gradient-based pupil centre detection (Timm-Barth 2011 inspired).
Edge gradients around the circular pupil boundary point radially outward.
By casting rays in the *negative* gradient direction from every strong-edge
pixel we accumulate votes at the true centre.
Returns (local_cx, local_cy, score) or None.
"""
h, w = roi_gray.shape
gx = cv2.Sobel(roi_gray.astype(np.float64), cv2.CV_64F, 1, 0, ksize=3)
gy = cv2.Sobel(roi_gray.astype(np.float64), cv2.CV_64F, 0, 1, ksize=3)
mag = np.sqrt(gx ** 2 + gy ** 2)
mag_masked = mag.copy()
mag_masked[mask == 0] = 0
vals = mag_masked[mask > 0]
if len(vals) < 8 or vals.max() < 1:
return None
thresh = float(np.percentile(vals, 70)) # top 30 % of gradients
strong = (mag > thresh) & (mask > 0)
if np.count_nonzero(strong) < 8:
return None
ys, xs = np.where(strong)
gx_s = gx[ys, xs]
gy_s = gy[ys, xs]
mag_s = mag[ys, xs]
# Normalise & negate (point *toward* centre)
gx_n = -gx_s / (mag_s + 1e-10)
gy_n = -gy_s / (mag_s + 1e-10)
accumulator = np.zeros((h, w), np.float64)
max_t = max(int(max(eye_w, eye_h) * 0.5), 5)
for t in range(1, max_t + 1):
px = (xs + gx_n * t + 0.5).astype(np.int32)
py = (ys + gy_n * t + 0.5).astype(np.int32)
valid = (px >= 0) & (px < w) & (py >= 0) & (py < h)
pxv, pyv, magv = px[valid], py[valid], mag_s[valid]
in_mask = mask[pyv, pxv] > 0
np.add.at(accumulator, (pyv[in_mask], pxv[in_mask]), magv[in_mask])
# Weight by darkness (pupil region is darker than sclera)
dark_w = (255.0 - roi_gray.astype(np.float64)) / 255.0
accumulator *= (0.5 + 0.5 * dark_w)
accumulator[mask == 0] = 0
if accumulator.max() < 1:
return None
acc_smooth = cv2.GaussianBlur(accumulator, (5, 5), 1.0)
_, max_val, _, max_loc = cv2.minMaxLoc(acc_smooth, mask=mask)
cx, cy = float(max_loc[0]), float(max_loc[1])
mean_acc = float(np.mean(accumulator[mask > 0]) + 1e-6)
score = min(1.0, max_val / (mean_acc * 5))
return cx, cy, score
def _find_pupil_center(eye_pts_px, img_gray, W, H):
"""Locate the pupil/iris centre inside one eye.
Pipeline
--------
1. Build a tight eye-region mask from 6 contour landmarks.
2. Restrict search to the **upper 65 %** of the lid opening to avoid
eyelid / eyelash shadow contamination.
3. Apply CLAHE for better pupil-iris-sclera contrast.
4. **Primary** – gradient-based centre voting (Timm-Barth inspired):
robust to lighting, threshold-free.
5. **Secondary** – multi-threshold contour moments with asymmetric
vertical scoring.
6. **Tertiary** – weighted dark-pixel centroid with upper-region bias.
7. Fallback – geometric centre of the eye contour.
"""
geo_center = np.mean(eye_pts_px, axis=0)
# --- Eye Aspect Ratio (EAR) – skip closed eyes ---
v1 = np.linalg.norm(eye_pts_px[1] - eye_pts_px[5])
v2 = np.linalg.norm(eye_pts_px[2] - eye_pts_px[4])
horiz = np.linalg.norm(eye_pts_px[0] - eye_pts_px[3])
if horiz < 3:
return float(geo_center[0]), float(geo_center[1]), 0.0
ear = (v1 + v2) / (2.0 * horiz)
if ear < 0.12:
return float(geo_center[0]), float(geo_center[1]), 0.05
# --- Tight padded ROI ---
min_xy = np.min(eye_pts_px, axis=0)
max_xy = np.max(eye_pts_px, axis=0)
eye_w = max_xy[0] - min_xy[0]
eye_h = max_xy[1] - min_xy[1]
pad = max(int(eye_w * 0.15), 2)
rx1 = max(0, int(min_xy[0]) - pad)
ry1 = max(0, int(min_xy[1]) - pad)
rx2 = min(W, int(max_xy[0]) + pad)
ry2 = min(H, int(max_xy[1]) + pad)
roi = img_gray[ry1:ry2, rx1:rx2]
if roi.size < 20:
return float(geo_center[0]), float(geo_center[1]), 0.1
h_roi, w_roi = roi.shape
# --- Eye contour mask ---
pts_local = eye_pts_px.astype(np.int32).copy()
pts_local[:, 0] -= rx1
pts_local[:, 1] -= ry1
mask_full = np.zeros((h_roi, w_roi), dtype=np.uint8)
cv2.fillConvexPoly(mask_full, pts_local, 255)
# --- Restrict to upper 65 % of lid opening ---
eye_top_l = max(0, int(min_xy[1]) - ry1)
eye_bot_l = min(h_roi, int(max_xy[1]) - ry1)
cutoff = int(eye_top_l + 0.65 * (eye_bot_l - eye_top_l))
mask = mask_full.copy()
mask[cutoff:, :] = 0
kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
mask_inner = cv2.erode(mask, kern, iterations=2)
if np.count_nonzero(mask_inner) < 5:
mask_inner = cv2.erode(mask, kern, iterations=1)
if np.count_nonzero(mask_inner) < 5:
mask_inner = mask
# --- CLAHE + gentle blur ---
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(4, 4))
roi_eq = clahe.apply(roi)
roi_blur = cv2.GaussianBlur(roi_eq, (3, 3), 0.7)
masked_pixels = roi_blur[mask_inner > 0]
if len(masked_pixels) < 5:
return float(geo_center[0]), float(geo_center[1]), 0.1
gc_local = geo_center - np.array([rx1, ry1])
mask_area = float(max(np.count_nonzero(mask_inner), 1))
# ================================================================
# Strategy 1 – gradient-based centre voting (primary)
# ================================================================
grad = _gradient_vote_pupil(roi_blur, mask_inner, gc_local, eye_w, eye_h)
if grad is not None:
gcx, gcy, gscore = grad
if gscore > 0.20:
conf = float(np.clip(ear * 2.5 * gscore, 0.1, 1.0))
return float(gcx) + rx1, float(gcy) + ry1, conf
# ================================================================
# Strategy 2 – multi-threshold contour moments (secondary)
# ================================================================
best_cx, best_cy, best_score = None, None, -1.0
for pct in (10, 20, 30, 40):
thresh_val = int(np.percentile(masked_pixels, pct))
binary = np.zeros_like(roi_blur)
binary[(roi_blur <= thresh_val) & (mask_inner > 0)] = 255
binary = cv2.morphologyEx(binary.astype(np.uint8), cv2.MORPH_OPEN, kern)
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kern)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
area = cv2.contourArea(cnt)
if area < 4:
continue
M = cv2.moments(cnt)
if M["m00"] < 1:
continue
cx_l = M["m10"] / M["m00"]
cy_l = M["m01"] / M["m00"]
ix, iy = int(cx_l), int(cy_l)
if not (0 <= ix < w_roi and 0 <= iy < h_roi):
continue
if mask_full[iy, ix] == 0:
continue
# Circularity
perim = cv2.arcLength(cnt, True)
circ = 4 * np.pi * area / (perim ** 2 + 1e-6)
circ_score = min(circ, 1.0)
# Proximity – asymmetric vertical penalty
dx = abs(cx_l - gc_local[0])
dy = cy_l - gc_local[1] # positive = below centre
max_dx = max(eye_w * 0.45, 1)
h_prox = max(0.0, 1.0 - dx / max_dx)
max_dy_up = max(eye_h * 0.4, 1)
max_dy_dn = max(eye_h * 0.25, 1) # tighter below
v_prox = max(0.0, 1.0 - abs(dy) / (max_dy_dn if dy > 0 else max_dy_up))
prox_score = 0.5 * h_prox + 0.5 * v_prox
# Size
ratio = area / mask_area
if ratio < 0.03 or ratio > 0.70:
size_score = 0.1
elif 0.08 <= ratio <= 0.45:
size_score = 1.0
else:
size_score = 0.5
score = circ_score * 0.25 + prox_score * 0.45 + size_score * 0.30
if score > best_score:
best_score = score
best_cx = cx_l + rx1
best_cy = cy_l + ry1
if best_cx is not None and best_score > 0.25:
conf = float(np.clip(ear * 2.5 * best_score, 0.1, 1.0))
return float(best_cx), float(best_cy), conf
# ================================================================
# Strategy 3 – weighted dark-pixel centroid with upper-region bias
# ================================================================
thresh_val = int(np.percentile(masked_pixels, 25))
dark = (roi_blur <= thresh_val) & (mask_inner > 0)
ys, xs = np.where(dark)
if len(xs) > 3:
weights = (255.0 - roi_blur[dark]).astype(np.float64)
vert_bias = np.clip(
1.0 - (ys - gc_local[1]) / max(eye_h * 0.3, 1), 0.3, 1.5)
weights *= vert_bias
total = weights.sum()
if total > 0:
cx = float(np.sum(xs * weights) / total) + rx1
cy = float(np.sum(ys * weights) / total) + ry1
return cx, cy, float(np.clip(ear * 1.5, 0.1, 0.7))
# --- Fallback: geometric centre ---
return float(geo_center[0]), float(geo_center[1]), 0.1
def estimate_iris_positions(face_kps, image_np, img_width, img_height):
"""Estimate iris centres for both eyes using image-based pupil detection.
Args:
face_kps: (69, 3) normalised keypoints [x/W, y/H, conf]
image_np: (H, W, 3) float32 RGB image [0, 1]
img_width, img_height: pixel dimensions
Returns:
dict with right_iris, left_iris, right_gaze, left_gaze.
"""
W, H = img_width, img_height
kps_px = face_kps[:, :2].copy() * np.array([W, H])
kps_conf = face_kps[:, 2].copy()
img_u8 = (np.clip(image_np, 0, 1) * 255).astype(np.uint8)
img_gray = cv2.cvtColor(img_u8, cv2.COLOR_RGB2GRAY)
results = {}
for eye_name, eye_idx in [('right', _RIGHT_EYE_IDX),
('left', _LEFT_EYE_IDX)]:
pts = kps_px[eye_idx] # (6, 2)
confs = kps_conf[eye_idx]
mc = float(np.mean(confs))
geo = np.mean(pts, axis=0)
if mc < 0.05:
results[f'{eye_name}_iris'] = {
'x': float(geo[0]), 'y': float(geo[1]), 'confidence': 0.0}
results[f'{eye_name}_gaze'] = {'dx': 0.0, 'dy': 0.0}
continue
ix, iy, ic = _find_pupil_center(pts, img_gray, W, H)
results[f'{eye_name}_iris'] = {'x': ix, 'y': iy, 'confidence': ic}
dx = ix - float(geo[0])
dy = iy - float(geo[1])
norm = max(np.hypot(dx, dy), 1e-6)
# Approximate yaw/pitch from 2D iris-offset (small-angle, scaled by
# eye span). This lets the downstream gaze-lock + OneEuro paths
# work even when MediaPipe blendshapes are unavailable.
eye_span_x = float(np.ptp(pts[:, 0])) or 1.0
eye_span_y = float(np.ptp(pts[:, 1])) or 1.0
yaw_rad = np.clip(dx / (eye_span_x * 0.5), -1.2, 1.2) * 0.5 # ~30 deg max
pitch_rad = np.clip(dy / (eye_span_y * 0.5), -1.2, 1.2) * 0.4 # ~25 deg max
results[f'{eye_name}_gaze'] = {
'dx': round(dx / norm, 4), 'dy': round(dy / norm, 4),
'yaw_rad': float(yaw_rad), 'pitch_rad': float(pitch_rad),
'magnitude': float(np.hypot(yaw_rad, pitch_rad)),
'source': 'iris_offset_2d',
}
return results
# ---------------------------------------------------
# Debug visualisation overlay
# ---------------------------------------------------
# Colour palette for 68-landmark regions (face-array index ranges)
_LANDMARK_COLORS = [
(1, 17, (255, 200, 0)), # jawline
(18, 22, (200, 255, 0)), # right eyebrow
(23, 27, (200, 255, 0)), # left eyebrow
(28, 36, (0, 0, 255)), # nose
(37, 42, (0, 255, 0)), # right eye
(43, 48, (0, 255, 0)), # left eye
(49, 60, (0, 255, 255)), # outer mouth
(61, 68, (0, 255, 200)), # inner mouth
]