FangSen9000 commited on
Commit ·
adbfc5d
1
Parent(s): cb41553
Add the modified openpose and add confidence level filtering.
Browse files- .gitignore +7 -0
- One-to-All-Animation +1 -0
- easy_dwpose/__pycache__/__init__.cpython-311.pyc +0 -0
- easy_dwpose/__pycache__/__init__.cpython-38.pyc +0 -0
- easy_dwpose/__pycache__/dwpose.cpython-311.pyc +0 -0
- easy_dwpose/__pycache__/dwpose.cpython-38.pyc +0 -0
- easy_dwpose/body_estimation/__pycache__/__init__.cpython-311.pyc +0 -0
- easy_dwpose/body_estimation/__pycache__/__init__.cpython-38.pyc +0 -0
- easy_dwpose/body_estimation/__pycache__/detector.cpython-38.pyc +0 -0
- easy_dwpose/body_estimation/__pycache__/pose.cpython-38.pyc +0 -0
- easy_dwpose/body_estimation/__pycache__/utils.cpython-311.pyc +0 -0
- easy_dwpose/body_estimation/__pycache__/utils.cpython-38.pyc +0 -0
- easy_dwpose/body_estimation/__pycache__/wholebody.cpython-311.pyc +0 -0
- easy_dwpose/body_estimation/__pycache__/wholebody.cpython-38.pyc +0 -0
- easy_dwpose/draw/__pycache__/__init__.cpython-38.pyc +0 -0
- easy_dwpose/draw/__pycache__/controlnext.cpython-310.pyc +0 -0
- easy_dwpose/draw/__pycache__/controlnext.cpython-312.pyc +0 -0
- easy_dwpose/draw/__pycache__/controlnext.cpython-38.pyc +0 -0
- easy_dwpose/draw/__pycache__/openpose.cpython-310.pyc +0 -0
- easy_dwpose/draw/__pycache__/openpose.cpython-312.pyc +0 -0
- easy_dwpose/draw/__pycache__/openpose.cpython-38.pyc +0 -0
- easy_dwpose/draw/__pycache__/wan_style.cpython-310.pyc +0 -0
- easy_dwpose/draw/openpose.py +95 -13
- generated_pose_video/GOOD_MORNING_AFTERNOON_25073_36863_01435_20250804_214708.mp4 +0 -3
- generated_pose_video/HELLO_WORLD_27184_63831_20250804_215328.mp4 +0 -3
- generated_pose_video/I_WILL_ATTEND_THIS_DINNER_PARTY_28794_63364_04007_66628_16327_41325_20250804_215724.mp4 +0 -3
- generated_pose_video/NOT_FIND_YET_38868_21853_18537_20250804_220326.mp4 +0 -3
- generated_pose_video/NOT_FIND_YET_38868_21853_38944_20250804_223748.mp4 +0 -3
- src/sam-2 +1 -0
- text2pose.py +244 -88
- train_end2end.py +460 -0
- utils/__pycache__/npz_interpolation.cpython-312.pyc +0 -0
.gitignore
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.mp4
|
| 2 |
+
*.jpg
|
| 3 |
+
*.png
|
| 4 |
+
*.npy
|
| 5 |
+
部分尝试
|
| 6 |
+
论文工具
|
| 7 |
+
论文所需
|
One-to-All-Animation
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Subproject commit fc608e58e3956f26aebf44a4387701f5d64ffd4a
|
easy_dwpose/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (274 Bytes). View file
|
|
|
easy_dwpose/__pycache__/__init__.cpython-38.pyc
CHANGED
|
Binary files a/easy_dwpose/__pycache__/__init__.cpython-38.pyc and b/easy_dwpose/__pycache__/__init__.cpython-38.pyc differ
|
|
|
easy_dwpose/__pycache__/dwpose.cpython-311.pyc
ADDED
|
Binary file (5.04 kB). View file
|
|
|
easy_dwpose/__pycache__/dwpose.cpython-38.pyc
CHANGED
|
Binary files a/easy_dwpose/__pycache__/dwpose.cpython-38.pyc and b/easy_dwpose/__pycache__/dwpose.cpython-38.pyc differ
|
|
|
easy_dwpose/body_estimation/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (343 Bytes). View file
|
|
|
easy_dwpose/body_estimation/__pycache__/__init__.cpython-38.pyc
CHANGED
|
Binary files a/easy_dwpose/body_estimation/__pycache__/__init__.cpython-38.pyc and b/easy_dwpose/body_estimation/__pycache__/__init__.cpython-38.pyc differ
|
|
|
easy_dwpose/body_estimation/__pycache__/detector.cpython-38.pyc
CHANGED
|
Binary files a/easy_dwpose/body_estimation/__pycache__/detector.cpython-38.pyc and b/easy_dwpose/body_estimation/__pycache__/detector.cpython-38.pyc differ
|
|
|
easy_dwpose/body_estimation/__pycache__/pose.cpython-38.pyc
CHANGED
|
Binary files a/easy_dwpose/body_estimation/__pycache__/pose.cpython-38.pyc and b/easy_dwpose/body_estimation/__pycache__/pose.cpython-38.pyc differ
|
|
|
easy_dwpose/body_estimation/__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (1.26 kB). View file
|
|
|
easy_dwpose/body_estimation/__pycache__/utils.cpython-38.pyc
CHANGED
|
Binary files a/easy_dwpose/body_estimation/__pycache__/utils.cpython-38.pyc and b/easy_dwpose/body_estimation/__pycache__/utils.cpython-38.pyc differ
|
|
|
easy_dwpose/body_estimation/__pycache__/wholebody.cpython-311.pyc
ADDED
|
Binary file (3.06 kB). View file
|
|
|
easy_dwpose/body_estimation/__pycache__/wholebody.cpython-38.pyc
CHANGED
|
Binary files a/easy_dwpose/body_estimation/__pycache__/wholebody.cpython-38.pyc and b/easy_dwpose/body_estimation/__pycache__/wholebody.cpython-38.pyc differ
|
|
|
easy_dwpose/draw/__pycache__/__init__.cpython-38.pyc
CHANGED
|
Binary files a/easy_dwpose/draw/__pycache__/__init__.cpython-38.pyc and b/easy_dwpose/draw/__pycache__/__init__.cpython-38.pyc differ
|
|
|
easy_dwpose/draw/__pycache__/controlnext.cpython-310.pyc
CHANGED
|
Binary files a/easy_dwpose/draw/__pycache__/controlnext.cpython-310.pyc and b/easy_dwpose/draw/__pycache__/controlnext.cpython-310.pyc differ
|
|
|
easy_dwpose/draw/__pycache__/controlnext.cpython-312.pyc
CHANGED
|
Binary files a/easy_dwpose/draw/__pycache__/controlnext.cpython-312.pyc and b/easy_dwpose/draw/__pycache__/controlnext.cpython-312.pyc differ
|
|
|
easy_dwpose/draw/__pycache__/controlnext.cpython-38.pyc
CHANGED
|
Binary files a/easy_dwpose/draw/__pycache__/controlnext.cpython-38.pyc and b/easy_dwpose/draw/__pycache__/controlnext.cpython-38.pyc differ
|
|
|
easy_dwpose/draw/__pycache__/openpose.cpython-310.pyc
CHANGED
|
Binary files a/easy_dwpose/draw/__pycache__/openpose.cpython-310.pyc and b/easy_dwpose/draw/__pycache__/openpose.cpython-310.pyc differ
|
|
|
easy_dwpose/draw/__pycache__/openpose.cpython-312.pyc
CHANGED
|
Binary files a/easy_dwpose/draw/__pycache__/openpose.cpython-312.pyc and b/easy_dwpose/draw/__pycache__/openpose.cpython-312.pyc differ
|
|
|
easy_dwpose/draw/__pycache__/openpose.cpython-38.pyc
CHANGED
|
Binary files a/easy_dwpose/draw/__pycache__/openpose.cpython-38.pyc and b/easy_dwpose/draw/__pycache__/openpose.cpython-38.pyc differ
|
|
|
easy_dwpose/draw/__pycache__/wan_style.cpython-310.pyc
ADDED
|
Binary file (8.09 kB). View file
|
|
|
easy_dwpose/draw/openpose.py
CHANGED
|
@@ -6,7 +6,16 @@ import numpy as np
|
|
| 6 |
eps = 0.01
|
| 7 |
|
| 8 |
|
| 9 |
-
def draw_bodypose(canvas, candidate, subset):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
H, W, C = canvas.shape
|
| 11 |
candidate = np.array(candidate)
|
| 12 |
subset = np.array(subset)
|
|
@@ -61,6 +70,13 @@ def draw_bodypose(canvas, candidate, subset):
|
|
| 61 |
index = subset[n][np.array(limbSeq[i]) - 1]
|
| 62 |
if -1 in index:
|
| 63 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
Y = candidate[index.astype(int), 0] * float(W)
|
| 65 |
X = candidate[index.astype(int), 1] * float(H)
|
| 66 |
mX = np.mean(X)
|
|
@@ -77,6 +93,13 @@ def draw_bodypose(canvas, candidate, subset):
|
|
| 77 |
index = int(subset[n][i])
|
| 78 |
if index == -1:
|
| 79 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
x, y = candidate[index][0:2]
|
| 81 |
x = int(x * W)
|
| 82 |
y = int(y * H)
|
|
@@ -85,7 +108,15 @@ def draw_bodypose(canvas, candidate, subset):
|
|
| 85 |
return canvas
|
| 86 |
|
| 87 |
|
| 88 |
-
def draw_handpose(canvas, all_hand_peaks):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
import matplotlib
|
| 90 |
|
| 91 |
H, W, C = canvas.shape
|
|
@@ -117,11 +148,19 @@ def draw_handpose(canvas, all_hand_peaks):
|
|
| 117 |
for i in range(len(all_hand_peaks)):
|
| 118 |
peaks = all_hand_peaks[i]
|
| 119 |
peaks = np.array(peaks)
|
|
|
|
| 120 |
|
| 121 |
for ie, e in enumerate(edges):
|
| 122 |
x1, y1 = peaks[e[0]]
|
| 123 |
x2, y2 = peaks[e[1]]
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
x1 = int(x1 * W)
|
| 126 |
y1 = int(y1 * H)
|
| 127 |
x2 = int(x2 * W)
|
|
@@ -135,9 +174,13 @@ def draw_handpose(canvas, all_hand_peaks):
|
|
| 135 |
thickness=2,
|
| 136 |
)
|
| 137 |
|
| 138 |
-
for
|
| 139 |
x, y = keyponit
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
x = int(x * W)
|
| 142 |
y = int(y * H)
|
| 143 |
if x > eps and y > eps:
|
|
@@ -145,11 +188,25 @@ def draw_handpose(canvas, all_hand_peaks):
|
|
| 145 |
return canvas
|
| 146 |
|
| 147 |
|
| 148 |
-
def draw_facepose(canvas, all_lmks):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
H, W, C = canvas.shape
|
| 150 |
-
for lmks in all_lmks:
|
| 151 |
lmks = np.array(lmks)
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
x, y = lmk
|
| 154 |
x = int(x * W)
|
| 155 |
y = int(y * H)
|
|
@@ -158,19 +215,44 @@ def draw_facepose(canvas, all_lmks):
|
|
| 158 |
return canvas
|
| 159 |
|
| 160 |
|
| 161 |
-
def draw_pose(pose, height: int, width: int, include_face: bool = True, include_hands: bool = True) -> np.ndarray:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
canvas = np.zeros(shape=(height, width, 3), dtype=np.uint8)
|
| 163 |
|
|
|
|
| 164 |
candidate = pose["bodies"]
|
| 165 |
-
subset
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
if include_face:
|
| 169 |
-
faces = pose
|
| 170 |
-
|
|
|
|
|
|
|
| 171 |
|
| 172 |
if include_hands:
|
| 173 |
-
hands = pose
|
| 174 |
-
|
|
|
|
|
|
|
| 175 |
|
| 176 |
return canvas
|
|
|
|
| 6 |
eps = 0.01
|
| 7 |
|
| 8 |
|
| 9 |
+
def draw_bodypose(canvas, candidate, subset, score=None, conf_threshold=0.3):
|
| 10 |
+
"""Draw body pose with optional confidence filtering
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
canvas: canvas to draw on
|
| 14 |
+
candidate: pose candidate
|
| 15 |
+
subset: pose subset
|
| 16 |
+
score: confidence scores (optional)
|
| 17 |
+
conf_threshold: confidence threshold for filtering (default: 0.3)
|
| 18 |
+
"""
|
| 19 |
H, W, C = canvas.shape
|
| 20 |
candidate = np.array(candidate)
|
| 21 |
subset = np.array(subset)
|
|
|
|
| 70 |
index = subset[n][np.array(limbSeq[i]) - 1]
|
| 71 |
if -1 in index:
|
| 72 |
continue
|
| 73 |
+
|
| 74 |
+
# Add confidence filtering (like ControlNeXt)
|
| 75 |
+
if score is not None:
|
| 76 |
+
conf = score[n][np.array(limbSeq[i]) - 1]
|
| 77 |
+
if conf[0] < conf_threshold or conf[1] < conf_threshold:
|
| 78 |
+
continue
|
| 79 |
+
|
| 80 |
Y = candidate[index.astype(int), 0] * float(W)
|
| 81 |
X = candidate[index.astype(int), 1] * float(H)
|
| 82 |
mX = np.mean(X)
|
|
|
|
| 93 |
index = int(subset[n][i])
|
| 94 |
if index == -1:
|
| 95 |
continue
|
| 96 |
+
|
| 97 |
+
# Add confidence filtering for keypoints
|
| 98 |
+
if score is not None:
|
| 99 |
+
conf = score[n][i]
|
| 100 |
+
if conf < conf_threshold:
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
x, y = candidate[index][0:2]
|
| 104 |
x = int(x * W)
|
| 105 |
y = int(y * H)
|
|
|
|
| 108 |
return canvas
|
| 109 |
|
| 110 |
|
| 111 |
+
def draw_handpose(canvas, all_hand_peaks, all_hand_scores=None, conf_threshold=0.3):
|
| 112 |
+
"""Draw hand pose with optional confidence filtering
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
canvas: canvas to draw on
|
| 116 |
+
all_hand_peaks: hand keypoints
|
| 117 |
+
all_hand_scores: confidence scores (optional)
|
| 118 |
+
conf_threshold: confidence threshold for filtering (default: 0.3)
|
| 119 |
+
"""
|
| 120 |
import matplotlib
|
| 121 |
|
| 122 |
H, W, C = canvas.shape
|
|
|
|
| 148 |
for i in range(len(all_hand_peaks)):
|
| 149 |
peaks = all_hand_peaks[i]
|
| 150 |
peaks = np.array(peaks)
|
| 151 |
+
scores = all_hand_scores[i] if all_hand_scores is not None else None
|
| 152 |
|
| 153 |
for ie, e in enumerate(edges):
|
| 154 |
x1, y1 = peaks[e[0]]
|
| 155 |
x2, y2 = peaks[e[1]]
|
| 156 |
|
| 157 |
+
# Add confidence filtering
|
| 158 |
+
if scores is not None:
|
| 159 |
+
score1 = scores[e[0]]
|
| 160 |
+
score2 = scores[e[1]]
|
| 161 |
+
if score1 < conf_threshold or score2 < conf_threshold:
|
| 162 |
+
continue
|
| 163 |
+
|
| 164 |
x1 = int(x1 * W)
|
| 165 |
y1 = int(y1 * H)
|
| 166 |
x2 = int(x2 * W)
|
|
|
|
| 174 |
thickness=2,
|
| 175 |
)
|
| 176 |
|
| 177 |
+
for idx, keyponit in enumerate(peaks):
|
| 178 |
x, y = keyponit
|
| 179 |
|
| 180 |
+
# Add confidence filtering for keypoints
|
| 181 |
+
if scores is not None and scores[idx] < conf_threshold:
|
| 182 |
+
continue
|
| 183 |
+
|
| 184 |
x = int(x * W)
|
| 185 |
y = int(y * H)
|
| 186 |
if x > eps and y > eps:
|
|
|
|
| 188 |
return canvas
|
| 189 |
|
| 190 |
|
| 191 |
+
def draw_facepose(canvas, all_lmks, all_scores=None, conf_threshold=0.3):
|
| 192 |
+
"""Draw face pose with optional confidence filtering
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
canvas: canvas to draw on
|
| 196 |
+
all_lmks: face landmarks
|
| 197 |
+
all_scores: confidence scores (optional)
|
| 198 |
+
conf_threshold: confidence threshold for filtering (default: 0.3)
|
| 199 |
+
"""
|
| 200 |
H, W, C = canvas.shape
|
| 201 |
+
for i, lmks in enumerate(all_lmks):
|
| 202 |
lmks = np.array(lmks)
|
| 203 |
+
scores = all_scores[i] if all_scores is not None else None
|
| 204 |
+
|
| 205 |
+
for idx, lmk in enumerate(lmks):
|
| 206 |
+
# Add confidence filtering
|
| 207 |
+
if scores is not None and scores[idx] < conf_threshold:
|
| 208 |
+
continue
|
| 209 |
+
|
| 210 |
x, y = lmk
|
| 211 |
x = int(x * W)
|
| 212 |
y = int(y * H)
|
|
|
|
| 215 |
return canvas
|
| 216 |
|
| 217 |
|
| 218 |
+
def draw_pose(pose, height: int, width: int, include_face: bool = True, include_hands: bool = True, conf_threshold: float = 0.3) -> np.ndarray:
|
| 219 |
+
"""Draw pose with confidence filtering
|
| 220 |
+
|
| 221 |
+
Args:
|
| 222 |
+
pose: pose data dictionary
|
| 223 |
+
height: canvas height
|
| 224 |
+
width: canvas width
|
| 225 |
+
include_face: whether to draw face
|
| 226 |
+
include_hands: whether to draw hands
|
| 227 |
+
conf_threshold: confidence threshold for filtering (default: 0.3)
|
| 228 |
+
"""
|
| 229 |
canvas = np.zeros(shape=(height, width, 3), dtype=np.uint8)
|
| 230 |
|
| 231 |
+
# Handle bodies
|
| 232 |
candidate = pose["bodies"]
|
| 233 |
+
# For openpose format, subset is typically derived from body_scores
|
| 234 |
+
# Create a simple subset array for single person (18 keypoints)
|
| 235 |
+
body_scores_data = pose.get("body_scores", None)
|
| 236 |
+
|
| 237 |
+
if body_scores_data is not None:
|
| 238 |
+
# Create subset: reshape scores to be compatible
|
| 239 |
+
subset = body_scores_data.reshape(1, -1) if len(body_scores_data.shape) == 1 else body_scores_data
|
| 240 |
+
else:
|
| 241 |
+
# No scores available, create dummy subset
|
| 242 |
+
subset = np.zeros((1, 18))
|
| 243 |
+
|
| 244 |
+
canvas = draw_bodypose(canvas, candidate, subset, score=subset, conf_threshold=conf_threshold)
|
| 245 |
|
| 246 |
if include_face:
|
| 247 |
+
faces = pose.get("faces", [])
|
| 248 |
+
face_scores = pose.get("faces_scores", None)
|
| 249 |
+
if len(faces) > 0:
|
| 250 |
+
canvas = draw_facepose(canvas, faces, all_scores=face_scores, conf_threshold=conf_threshold)
|
| 251 |
|
| 252 |
if include_hands:
|
| 253 |
+
hands = pose.get("hands", [])
|
| 254 |
+
hand_scores = pose.get("hands_scores", None)
|
| 255 |
+
if len(hands) > 0:
|
| 256 |
+
canvas = draw_handpose(canvas, hands, all_hand_scores=hand_scores, conf_threshold=conf_threshold)
|
| 257 |
|
| 258 |
return canvas
|
generated_pose_video/GOOD_MORNING_AFTERNOON_25073_36863_01435_20250804_214708.mp4
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:e0d25a5c9af662adc2c417bbd9564cb71287f58ae6ef92cbdcc71dccd6ab6966
|
| 3 |
-
size 1668013
|
|
|
|
|
|
|
|
|
|
|
|
generated_pose_video/HELLO_WORLD_27184_63831_20250804_215328.mp4
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:2ff6dbbc50441746c7d494956bc72987878f359dd5ff96c765adb51e5631becb
|
| 3 |
-
size 2183071
|
|
|
|
|
|
|
|
|
|
|
|
generated_pose_video/I_WILL_ATTEND_THIS_DINNER_PARTY_28794_63364_04007_66628_16327_41325_20250804_215724.mp4
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:ad2836123b570c7aa716e4f02e447e1e004a3d439fbcc9a6e282175475d4539c
|
| 3 |
-
size 4409427
|
|
|
|
|
|
|
|
|
|
|
|
generated_pose_video/NOT_FIND_YET_38868_21853_18537_20250804_220326.mp4
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:912d9a76db09fe053361692239ba9644a47f144ec7832a2e38850811b9e5b652
|
| 3 |
-
size 2095895
|
|
|
|
|
|
|
|
|
|
|
|
generated_pose_video/NOT_FIND_YET_38868_21853_38944_20250804_223748.mp4
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:23b47ae5720cb5d7ba9b5e34a63e6f31f1c136d440a6a43c9113ad8a5ff5982c
|
| 3 |
-
size 1340578
|
|
|
|
|
|
|
|
|
|
|
|
src/sam-2
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Subproject commit 0e78a118995e66bb27d78518c4bd9a3e95b4e266
|
text2pose.py
CHANGED
|
@@ -18,7 +18,8 @@ import re
|
|
| 18 |
from datetime import datetime
|
| 19 |
|
| 20 |
from easy_dwpose import DWposeDetector
|
| 21 |
-
from easy_dwpose.draw.controlnext import draw_pose, process_pose_data
|
|
|
|
| 22 |
from utils.npz_interpolation import interpolate_pose_npz, ease_in_out_cubic
|
| 23 |
import copy
|
| 24 |
|
|
@@ -83,7 +84,7 @@ class SignLanguageQA:
|
|
| 83 |
npz_path = Path(NPZ_DIR) / f"{video_id}.npz"
|
| 84 |
|
| 85 |
if not npz_path.exists():
|
| 86 |
-
print(f" ⚠️ NPZ file not found: {npz_path}")
|
| 87 |
return None
|
| 88 |
|
| 89 |
try:
|
|
@@ -210,30 +211,46 @@ class SignLanguageQA:
|
|
| 210 |
frame_keys = [k for k in npz_data.keys() if k.startswith('frame_') and k.endswith('_bodies')]
|
| 211 |
return len(frame_keys)
|
| 212 |
|
| 213 |
-
def create_pose_frame(self, frame_data, width=480, height=480, scale_x=1.0, scale_y=1.0, hide_torso_lines=False, y_offset=0):
|
| 214 |
-
"""Create single frame pose image with progressive scaling and optional y offset
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
try:
|
| 216 |
# Apply progressive scaling if needed
|
| 217 |
if scale_x != 1.0 or scale_y != 1.0:
|
| 218 |
frame_data = self.apply_progressive_scaling(frame_data, scale_x, scale_y)
|
| 219 |
-
|
| 220 |
# Apply y offset if provided
|
| 221 |
if y_offset != 0:
|
| 222 |
frame_data = self.apply_y_offset(frame_data, y_offset)
|
| 223 |
-
|
| 224 |
-
processed_pred = process_pose_data(frame_data, height, width)
|
| 225 |
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
-
|
| 237 |
|
| 238 |
except Exception as e:
|
| 239 |
import traceback
|
|
@@ -470,7 +487,43 @@ class SignLanguageQA:
|
|
| 470 |
except Exception as e:
|
| 471 |
print(f"⚠️ Failed to get reference head position: {e}")
|
| 472 |
return None
|
| 473 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
def get_pose_head_top(self, frame_data):
|
| 475 |
"""Get the top of head position from pose frame data"""
|
| 476 |
# Try faces first
|
|
@@ -507,8 +560,12 @@ class SignLanguageQA:
|
|
| 507 |
|
| 508 |
def generate_video_from_glosses(self, gloss_list, output_path, fps=30, width=480, height=480,
|
| 509 |
smoothing_frames=5, smoothing_method='none', npz_interpolation_frames=0,
|
| 510 |
-
scale_x=1.0, scale_y=1.0, hide_torso_lines=False, ref_image_path=None):
|
| 511 |
-
"""Generate video from gloss list with optional progressive scaling and head alignment
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
# Create output directory
|
| 513 |
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 514 |
|
|
@@ -529,73 +586,93 @@ class SignLanguageQA:
|
|
| 529 |
matched_videos = self.find_gloss_videos(gloss)
|
| 530 |
|
| 531 |
if not matched_videos:
|
| 532 |
-
print(f"❌ '{gloss}' -> No matching
|
| 533 |
continue
|
| 534 |
|
| 535 |
-
print(f"🎯 '{gloss}' -> Found {len(matched_videos)}
|
| 536 |
-
|
| 537 |
-
#
|
| 538 |
-
|
|
|
|
| 539 |
for idx, video_id in enumerate(matched_videos):
|
| 540 |
npz_data = self.load_video_npz(video_id)
|
| 541 |
if npz_data is not None:
|
| 542 |
total_frames = self.get_total_frames(npz_data)
|
| 543 |
-
|
| 544 |
-
|
| 545 |
# Check video quality
|
| 546 |
is_good_quality, quality_msg = self.check_video_quality(npz_data)
|
| 547 |
-
|
| 548 |
if not is_good_quality:
|
| 549 |
-
print(f" ❌ Video quality check failed: {quality_msg}")
|
| 550 |
-
if idx < len(matched_videos) - 1:
|
| 551 |
-
print(f" 🔄 Trying next video for '{gloss}'...")
|
| 552 |
continue
|
| 553 |
-
|
| 554 |
# Get valid frame range
|
| 555 |
start_frame, end_frame = self.get_valid_frame_range(npz_data)
|
| 556 |
if start_frame > end_frame:
|
| 557 |
-
print(f" ❌ No valid frames found in video")
|
| 558 |
continue
|
| 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 |
if not all_pose_frames:
|
| 601 |
print("❌ No frames generated")
|
|
@@ -646,7 +723,7 @@ class SignLanguageQA:
|
|
| 646 |
|
| 647 |
# Create visual frame
|
| 648 |
if frame_data:
|
| 649 |
-
pose_frame = self.create_pose_frame(frame_data, width, height, scale_x, scale_y, hide_torso_lines, y_offset)
|
| 650 |
if pose_frame is not None:
|
| 651 |
interpolated_pose_frames.append(pose_frame)
|
| 652 |
|
|
@@ -663,22 +740,96 @@ class SignLanguageQA:
|
|
| 663 |
for group in all_pose_frames:
|
| 664 |
final_frames.extend(group)
|
| 665 |
|
| 666 |
-
# Write video
|
| 667 |
print("💾 Writing video file...")
|
| 668 |
-
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 669 |
-
video_writer = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
|
| 670 |
-
|
| 671 |
-
if not video_writer.isOpened():
|
| 672 |
-
print("❌ Unable to create video file")
|
| 673 |
-
return False
|
| 674 |
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 678 |
|
| 679 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 680 |
|
| 681 |
-
print(f"✅ Video generated successfully!")
|
| 682 |
print(f" 📁 File: {output_path}")
|
| 683 |
print(f" 📊 {len(final_frames)} frames, {fps}fps, {width}x{height}")
|
| 684 |
if output_path.exists():
|
|
@@ -904,6 +1055,8 @@ def main():
|
|
| 904 |
help='Hide torso lines from neck to hips (set to black). Choices: true/false (default: false)')
|
| 905 |
parser.add_argument('--ref-image-path', type=str, default=None,
|
| 906 |
help='Reference image path for head alignment')
|
|
|
|
|
|
|
| 907 |
|
| 908 |
args = parser.parse_args()
|
| 909 |
|
|
@@ -931,15 +1084,18 @@ def main():
|
|
| 931 |
|
| 932 |
if args.smoothing != 'none':
|
| 933 |
print(f"🌊 Using {args.smoothing} smoothing ({args.smoothing_frames} frames)")
|
| 934 |
-
|
| 935 |
if args.scale_x != 1.0 or args.scale_y != 1.0:
|
| 936 |
print(f"📏 Using progressive scaling: X={args.scale_x}, Y={args.scale_y}")
|
| 937 |
|
|
|
|
|
|
|
|
|
|
| 938 |
success = qa_system.generate_video_from_glosses(
|
| 939 |
gloss_list, output_file, args.fps, args.width, args.height,
|
| 940 |
args.smoothing_frames, args.smoothing, args.npz_interpolation,
|
| 941 |
args.scale_x, args.scale_y, args.hide_torso_lines == 'true',
|
| 942 |
-
args.ref_image_path
|
| 943 |
)
|
| 944 |
|
| 945 |
if not success:
|
|
|
|
| 18 |
from datetime import datetime
|
| 19 |
|
| 20 |
from easy_dwpose import DWposeDetector
|
| 21 |
+
from easy_dwpose.draw.controlnext import draw_pose as draw_pose_controlnext, process_pose_data
|
| 22 |
+
from easy_dwpose.draw.openpose import draw_pose as draw_pose_openpose
|
| 23 |
from utils.npz_interpolation import interpolate_pose_npz, ease_in_out_cubic
|
| 24 |
import copy
|
| 25 |
|
|
|
|
| 84 |
npz_path = Path(NPZ_DIR) / f"{video_id}.npz"
|
| 85 |
|
| 86 |
if not npz_path.exists():
|
| 87 |
+
print(f" ⚠️ NPZ file not found in Pose Dict: {npz_path}")
|
| 88 |
return None
|
| 89 |
|
| 90 |
try:
|
|
|
|
| 211 |
frame_keys = [k for k in npz_data.keys() if k.startswith('frame_') and k.endswith('_bodies')]
|
| 212 |
return len(frame_keys)
|
| 213 |
|
| 214 |
+
def create_pose_frame(self, frame_data, width=480, height=480, scale_x=1.0, scale_y=1.0, hide_torso_lines=False, y_offset=0, draw_style='controlnext'):
|
| 215 |
+
"""Create single frame pose image with progressive scaling and optional y offset
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
draw_style: 'controlnext' or 'openpose'
|
| 219 |
+
"""
|
| 220 |
try:
|
| 221 |
# Apply progressive scaling if needed
|
| 222 |
if scale_x != 1.0 or scale_y != 1.0:
|
| 223 |
frame_data = self.apply_progressive_scaling(frame_data, scale_x, scale_y)
|
| 224 |
+
|
| 225 |
# Apply y offset if provided
|
| 226 |
if y_offset != 0:
|
| 227 |
frame_data = self.apply_y_offset(frame_data, y_offset)
|
|
|
|
|
|
|
| 228 |
|
| 229 |
+
if draw_style == 'openpose':
|
| 230 |
+
# Use OpenPose style (simpler, no processing needed)
|
| 231 |
+
vis_img = draw_pose_openpose(
|
| 232 |
+
pose=frame_data,
|
| 233 |
+
height=height,
|
| 234 |
+
width=width,
|
| 235 |
+
include_face=True,
|
| 236 |
+
include_hands=True
|
| 237 |
+
)
|
| 238 |
+
return vis_img
|
| 239 |
+
else:
|
| 240 |
+
# Use ControlNeXt style (default, with advanced features)
|
| 241 |
+
processed_pred = process_pose_data(frame_data, height, width)
|
| 242 |
+
|
| 243 |
+
vis_img = draw_pose_controlnext(
|
| 244 |
+
pose=processed_pred,
|
| 245 |
+
H=height,
|
| 246 |
+
W=width,
|
| 247 |
+
include_body=True,
|
| 248 |
+
include_hand=True,
|
| 249 |
+
include_face=True,
|
| 250 |
+
hide_torso_lines=hide_torso_lines
|
| 251 |
+
)
|
| 252 |
|
| 253 |
+
return vis_img.transpose(1, 2, 0)
|
| 254 |
|
| 255 |
except Exception as e:
|
| 256 |
import traceback
|
|
|
|
| 487 |
except Exception as e:
|
| 488 |
print(f"⚠️ Failed to get reference head position: {e}")
|
| 489 |
return None
|
| 490 |
+
|
| 491 |
+
def calculate_neck_centrality_score(self, npz_data):
|
| 492 |
+
"""Calculate how centered the neck position is in the video
|
| 493 |
+
|
| 494 |
+
Returns a score from 0 to 1, where 1 means perfectly centered
|
| 495 |
+
Lower score means the person is more off-center
|
| 496 |
+
"""
|
| 497 |
+
neck_x_positions = []
|
| 498 |
+
|
| 499 |
+
# Sample frames throughout the video
|
| 500 |
+
total_frames = self.get_total_frames(npz_data)
|
| 501 |
+
sample_frames = [0, total_frames // 4, total_frames // 2, 3 * total_frames // 4, total_frames - 1]
|
| 502 |
+
|
| 503 |
+
for frame_num in sample_frames:
|
| 504 |
+
if frame_num >= total_frames:
|
| 505 |
+
continue
|
| 506 |
+
|
| 507 |
+
frame_data = self.get_frame_data(npz_data, frame_num)
|
| 508 |
+
if frame_data and 'bodies' in frame_data:
|
| 509 |
+
bodies = frame_data['bodies']
|
| 510 |
+
# Neck is typically index 1 in body keypoints
|
| 511 |
+
if len(bodies) > 1 and bodies[1, 0] > 0:
|
| 512 |
+
neck_x_positions.append(bodies[1, 0])
|
| 513 |
+
|
| 514 |
+
if not neck_x_positions:
|
| 515 |
+
return 0.0 # No valid neck positions found
|
| 516 |
+
|
| 517 |
+
# Calculate average neck X position
|
| 518 |
+
avg_neck_x = np.mean(neck_x_positions)
|
| 519 |
+
|
| 520 |
+
# Calculate distance from center (0.5)
|
| 521 |
+
# Score is higher when closer to center
|
| 522 |
+
distance_from_center = abs(avg_neck_x - 0.5)
|
| 523 |
+
centrality_score = 1.0 - (distance_from_center * 2) # Scale to 0-1
|
| 524 |
+
|
| 525 |
+
return max(0.0, centrality_score) # Ensure non-negative
|
| 526 |
+
|
| 527 |
def get_pose_head_top(self, frame_data):
|
| 528 |
"""Get the top of head position from pose frame data"""
|
| 529 |
# Try faces first
|
|
|
|
| 560 |
|
| 561 |
def generate_video_from_glosses(self, gloss_list, output_path, fps=30, width=480, height=480,
|
| 562 |
smoothing_frames=5, smoothing_method='none', npz_interpolation_frames=0,
|
| 563 |
+
scale_x=1.0, scale_y=1.0, hide_torso_lines=False, ref_image_path=None, draw_style='controlnext'):
|
| 564 |
+
"""Generate video from gloss list with optional progressive scaling and head alignment
|
| 565 |
+
|
| 566 |
+
Args:
|
| 567 |
+
draw_style: 'controlnext' (default) or 'openpose' - drawing style for pose visualization
|
| 568 |
+
"""
|
| 569 |
# Create output directory
|
| 570 |
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 571 |
|
|
|
|
| 586 |
matched_videos = self.find_gloss_videos(gloss)
|
| 587 |
|
| 588 |
if not matched_videos:
|
| 589 |
+
print(f"❌ '{gloss}' -> No matching Pose unit found")
|
| 590 |
continue
|
| 591 |
|
| 592 |
+
print(f"🎯 '{gloss}' -> Found {len(matched_videos)} Unit in Pose Dict")
|
| 593 |
+
|
| 594 |
+
# Evaluate all videos and select the best one based on quality and centering
|
| 595 |
+
candidate_videos = []
|
| 596 |
+
|
| 597 |
for idx, video_id in enumerate(matched_videos):
|
| 598 |
npz_data = self.load_video_npz(video_id)
|
| 599 |
if npz_data is not None:
|
| 600 |
total_frames = self.get_total_frames(npz_data)
|
| 601 |
+
|
|
|
|
| 602 |
# Check video quality
|
| 603 |
is_good_quality, quality_msg = self.check_video_quality(npz_data)
|
| 604 |
+
|
| 605 |
if not is_good_quality:
|
|
|
|
|
|
|
|
|
|
| 606 |
continue
|
| 607 |
+
|
| 608 |
# Get valid frame range
|
| 609 |
start_frame, end_frame = self.get_valid_frame_range(npz_data)
|
| 610 |
if start_frame > end_frame:
|
|
|
|
| 611 |
continue
|
| 612 |
+
|
| 613 |
+
# Calculate neck centrality score
|
| 614 |
+
centrality_score = self.calculate_neck_centrality_score(npz_data)
|
| 615 |
+
|
| 616 |
+
candidate_videos.append({
|
| 617 |
+
'video_id': video_id,
|
| 618 |
+
'npz_data': npz_data,
|
| 619 |
+
'total_frames': total_frames,
|
| 620 |
+
'start_frame': start_frame,
|
| 621 |
+
'end_frame': end_frame,
|
| 622 |
+
'quality_msg': quality_msg,
|
| 623 |
+
'centrality_score': centrality_score
|
| 624 |
+
})
|
| 625 |
+
|
| 626 |
+
if not candidate_videos:
|
| 627 |
+
print(f" ❌ No good quality poses dict found for '{gloss}'")
|
| 628 |
+
continue
|
| 629 |
+
|
| 630 |
+
# Select video with best centrality score
|
| 631 |
+
best_video = max(candidate_videos, key=lambda x: x['centrality_score'])
|
| 632 |
+
video_id = best_video['video_id']
|
| 633 |
+
npz_data = best_video['npz_data']
|
| 634 |
+
total_frames = best_video['total_frames']
|
| 635 |
+
start_frame = best_video['start_frame']
|
| 636 |
+
end_frame = best_video['end_frame']
|
| 637 |
+
quality_msg = best_video['quality_msg']
|
| 638 |
+
centrality_score = best_video['centrality_score']
|
| 639 |
+
|
| 640 |
+
print(f" 📹 {video_id}: {total_frames} frames")
|
| 641 |
+
print(f" ✅ {quality_msg}")
|
| 642 |
+
print(f" 🎯 Centrality score: {centrality_score:.2f} (selected from {len(candidate_videos)} candidates)")
|
| 643 |
+
print(f" 📊 Using frames {start_frame} to {end_frame} (out of {total_frames})")
|
| 644 |
+
|
| 645 |
+
# Store NPZ data for potential interpolation
|
| 646 |
+
all_npz_data.append(npz_data)
|
| 647 |
+
|
| 648 |
+
# Extract frames within valid range
|
| 649 |
+
gloss_frames = []
|
| 650 |
+
for frame_num in range(start_frame, end_frame + 1):
|
| 651 |
+
frame_data = self.get_frame_data(npz_data, frame_num)
|
| 652 |
+
if frame_data and self.check_frame_quality(frame_data):
|
| 653 |
+
# Calculate y offset for first frame if reference provided
|
| 654 |
+
if ref_head_top is not None and y_offset == 0 and frame_num == start_frame:
|
| 655 |
+
# Get head top from current pose
|
| 656 |
+
current_head_top = self.get_pose_head_top(frame_data)
|
| 657 |
+
if current_head_top is not None:
|
| 658 |
+
y_offset = ref_head_top - current_head_top
|
| 659 |
+
print(f"📐 Calculated Y offset: {y_offset:.2f}")
|
| 660 |
+
|
| 661 |
+
pose_frame = self.create_pose_frame(frame_data, width, height, scale_x, scale_y, hide_torso_lines, y_offset, draw_style)
|
| 662 |
+
if pose_frame is not None:
|
| 663 |
+
gloss_frames.append(pose_frame)
|
| 664 |
+
|
| 665 |
+
if gloss_frames:
|
| 666 |
+
all_pose_frames.append(gloss_frames)
|
| 667 |
+
video_info.append({
|
| 668 |
+
'gloss': gloss,
|
| 669 |
+
'video_id': video_id,
|
| 670 |
+
'frame_count': len(gloss_frames),
|
| 671 |
+
'npz_data': npz_data,
|
| 672 |
+
'start_frame': start_frame,
|
| 673 |
+
'end_frame': end_frame
|
| 674 |
+
})
|
| 675 |
+
print(f" ✅ Generated {len(gloss_frames)} pose frames")
|
| 676 |
|
| 677 |
if not all_pose_frames:
|
| 678 |
print("❌ No frames generated")
|
|
|
|
| 723 |
|
| 724 |
# Create visual frame
|
| 725 |
if frame_data:
|
| 726 |
+
pose_frame = self.create_pose_frame(frame_data, width, height, scale_x, scale_y, hide_torso_lines, y_offset, draw_style)
|
| 727 |
if pose_frame is not None:
|
| 728 |
interpolated_pose_frames.append(pose_frame)
|
| 729 |
|
|
|
|
| 740 |
for group in all_pose_frames:
|
| 741 |
final_frames.extend(group)
|
| 742 |
|
| 743 |
+
# Write video using FFmpeg directly for better compatibility
|
| 744 |
print("💾 Writing video file...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 745 |
|
| 746 |
+
# Try to use FFmpeg pipe for direct H.264 encoding
|
| 747 |
+
use_ffmpeg_pipe = True
|
| 748 |
+
try:
|
| 749 |
+
import subprocess
|
| 750 |
+
import threading
|
| 751 |
+
|
| 752 |
+
# Create FFmpeg command for pipe input
|
| 753 |
+
ffmpeg_cmd = [
|
| 754 |
+
'ffmpeg',
|
| 755 |
+
'-y', # Overwrite output file
|
| 756 |
+
'-f', 'rawvideo',
|
| 757 |
+
'-vcodec', 'rawvideo',
|
| 758 |
+
'-s', f'{width}x{height}',
|
| 759 |
+
'-pix_fmt', 'rgb24',
|
| 760 |
+
'-r', str(fps),
|
| 761 |
+
'-i', '-', # Read from pipe
|
| 762 |
+
'-c:v', 'libx264',
|
| 763 |
+
'-crf', '23',
|
| 764 |
+
'-pix_fmt', 'yuv420p',
|
| 765 |
+
'-movflags', '+faststart',
|
| 766 |
+
str(output_path)
|
| 767 |
+
]
|
| 768 |
+
|
| 769 |
+
# Start FFmpeg process with proper stderr handling
|
| 770 |
+
process = subprocess.Popen(
|
| 771 |
+
ffmpeg_cmd,
|
| 772 |
+
stdin=subprocess.PIPE,
|
| 773 |
+
stdout=subprocess.PIPE,
|
| 774 |
+
stderr=subprocess.PIPE,
|
| 775 |
+
bufsize=10**8 # Large buffer to prevent blocking
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
# Collect stderr in background to prevent pipe blocking
|
| 779 |
+
stderr_data = []
|
| 780 |
+
def read_stderr():
|
| 781 |
+
for line in process.stderr:
|
| 782 |
+
stderr_data.append(line)
|
| 783 |
+
|
| 784 |
+
stderr_thread = threading.Thread(target=read_stderr)
|
| 785 |
+
stderr_thread.daemon = True
|
| 786 |
+
stderr_thread.start()
|
| 787 |
+
|
| 788 |
+
# Write frames to FFmpeg
|
| 789 |
+
for pose_frame in tqdm(final_frames, desc="Writing frames"):
|
| 790 |
+
try:
|
| 791 |
+
# FFmpeg expects RGB format
|
| 792 |
+
process.stdin.write(pose_frame.tobytes())
|
| 793 |
+
except BrokenPipeError:
|
| 794 |
+
# FFmpeg died, check why
|
| 795 |
+
process.wait()
|
| 796 |
+
stderr_output = b''.join(stderr_data).decode('utf-8', errors='replace')
|
| 797 |
+
print(f"⚠️ FFmpeg died during write. Error output:")
|
| 798 |
+
print(stderr_output[-500:] if len(stderr_output) > 500 else stderr_output)
|
| 799 |
+
raise
|
| 800 |
+
|
| 801 |
+
# Close pipe and wait for FFmpeg to finish
|
| 802 |
+
process.stdin.close()
|
| 803 |
+
process.wait(timeout=30)
|
| 804 |
+
|
| 805 |
+
if process.returncode == 0:
|
| 806 |
+
print(f"✅ Video generated successfully with H.264 codec!")
|
| 807 |
+
else:
|
| 808 |
+
stderr_output = b''.join(stderr_data).decode('utf-8', errors='replace')
|
| 809 |
+
print(f"⚠️ FFmpeg failed with return code {process.returncode}")
|
| 810 |
+
print(f" Last 500 chars of error: {stderr_output[-500:] if len(stderr_output) > 500 else stderr_output}")
|
| 811 |
+
use_ffmpeg_pipe = False
|
| 812 |
+
except Exception as e:
|
| 813 |
+
print(f"⚠️ FFmpeg pipe method failed: {e}")
|
| 814 |
+
use_ffmpeg_pipe = False
|
| 815 |
|
| 816 |
+
# Fallback to OpenCV if FFmpeg pipe fails
|
| 817 |
+
if not use_ffmpeg_pipe:
|
| 818 |
+
print("⚠️ Falling back to OpenCV writer...")
|
| 819 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 820 |
+
video_writer = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
|
| 821 |
+
|
| 822 |
+
if not video_writer.isOpened():
|
| 823 |
+
print("❌ Unable to create video file")
|
| 824 |
+
return False
|
| 825 |
+
|
| 826 |
+
for pose_frame in tqdm(final_frames, desc="Writing frames"):
|
| 827 |
+
pose_frame_bgr = cv2.cvtColor(pose_frame, cv2.COLOR_RGB2BGR)
|
| 828 |
+
video_writer.write(pose_frame_bgr)
|
| 829 |
+
|
| 830 |
+
video_writer.release()
|
| 831 |
+
print(f"✅ Video generated successfully!")
|
| 832 |
|
|
|
|
| 833 |
print(f" 📁 File: {output_path}")
|
| 834 |
print(f" 📊 {len(final_frames)} frames, {fps}fps, {width}x{height}")
|
| 835 |
if output_path.exists():
|
|
|
|
| 1055 |
help='Hide torso lines from neck to hips (set to black). Choices: true/false (default: false)')
|
| 1056 |
parser.add_argument('--ref-image-path', type=str, default=None,
|
| 1057 |
help='Reference image path for head alignment')
|
| 1058 |
+
parser.add_argument('--draw-style', type=str, choices=['controlnext', 'openpose'], default='controlnext',
|
| 1059 |
+
help='Drawing style for pose visualization. controlnext: advanced features with confidence-based coloring. openpose: simpler classic style. (default: controlnext)')
|
| 1060 |
|
| 1061 |
args = parser.parse_args()
|
| 1062 |
|
|
|
|
| 1084 |
|
| 1085 |
if args.smoothing != 'none':
|
| 1086 |
print(f"🌊 Using {args.smoothing} smoothing ({args.smoothing_frames} frames)")
|
| 1087 |
+
|
| 1088 |
if args.scale_x != 1.0 or args.scale_y != 1.0:
|
| 1089 |
print(f"📏 Using progressive scaling: X={args.scale_x}, Y={args.scale_y}")
|
| 1090 |
|
| 1091 |
+
if args.draw_style != 'controlnext':
|
| 1092 |
+
print(f"🎨 Using {args.draw_style} drawing style")
|
| 1093 |
+
|
| 1094 |
success = qa_system.generate_video_from_glosses(
|
| 1095 |
gloss_list, output_file, args.fps, args.width, args.height,
|
| 1096 |
args.smoothing_frames, args.smoothing, args.npz_interpolation,
|
| 1097 |
args.scale_x, args.scale_y, args.hide_torso_lines == 'true',
|
| 1098 |
+
args.ref_image_path, args.draw_style
|
| 1099 |
)
|
| 1100 |
|
| 1101 |
if not success:
|
train_end2end.py
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
End-to-end training script for StableSigner (Prompt/Text -> Gloss -> Pose MoE).
|
| 4 |
+
|
| 5 |
+
Highlights:
|
| 6 |
+
- Fine-tunes a T5-style model (SLUL) to map prompts/text to gloss sequences.
|
| 7 |
+
- Adds a learnable Pose Mixture-of-Experts head that selects a pose (NPZ/video id)
|
| 8 |
+
for the predicted gloss; candidates can come from dataset annotations or the
|
| 9 |
+
existing pose dict (via SignLanguageQA in text2pose.py).
|
| 10 |
+
- Supports a simple Semantic-Aware Gloss Masking (SAGM-like) auxiliary loss.
|
| 11 |
+
|
| 12 |
+
Expected dataset format (json/jsonl):
|
| 13 |
+
[
|
| 14 |
+
{
|
| 15 |
+
"prompt": "The students will study in the library tomorrow.",
|
| 16 |
+
"gloss": "STUDENT LIBRARY STUDY TOMORROW",
|
| 17 |
+
"video_id": "12345", # ground-truth pose id
|
| 18 |
+
"candidate_video_ids": ["12345", "67890"] # optional; will fallback to pose dict lookup
|
| 19 |
+
},
|
| 20 |
+
...
|
| 21 |
+
]
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import json
|
| 26 |
+
import math
|
| 27 |
+
import os
|
| 28 |
+
from dataclasses import dataclass
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
from typing import Dict, List, Optional
|
| 31 |
+
|
| 32 |
+
import torch
|
| 33 |
+
import torch.nn as nn
|
| 34 |
+
from torch.utils.data import DataLoader, Dataset
|
| 35 |
+
from transformers import (
|
| 36 |
+
AdamW,
|
| 37 |
+
AutoModelForSeq2SeqLM,
|
| 38 |
+
AutoTokenizer,
|
| 39 |
+
get_linear_schedule_with_warmup,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
import text2pose as text2pose_module
|
| 43 |
+
from text2pose import SignLanguageQA
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# ---------------------------- Data utilities ---------------------------- #
|
| 47 |
+
class PromptGlossPoseDataset(Dataset):
|
| 48 |
+
"""Simple dataset wrapper for prompt->gloss with optional pose supervision."""
|
| 49 |
+
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
examples: List[dict],
|
| 53 |
+
tokenizer: AutoTokenizer,
|
| 54 |
+
pose_vocab: Dict[str, int],
|
| 55 |
+
signqa: Optional[SignLanguageQA],
|
| 56 |
+
max_input_length: int = 256,
|
| 57 |
+
max_target_length: int = 64,
|
| 58 |
+
max_candidates: int = 8,
|
| 59 |
+
):
|
| 60 |
+
self.examples = examples
|
| 61 |
+
self.tokenizer = tokenizer
|
| 62 |
+
self.pose_vocab = pose_vocab
|
| 63 |
+
self.signqa = signqa
|
| 64 |
+
self.max_input_length = max_input_length
|
| 65 |
+
self.max_target_length = max_target_length
|
| 66 |
+
self.max_candidates = max_candidates
|
| 67 |
+
|
| 68 |
+
def __len__(self):
|
| 69 |
+
return len(self.examples)
|
| 70 |
+
|
| 71 |
+
def _expand_candidates(self, gloss: str, provided: Optional[List[str]]) -> List[str]:
|
| 72 |
+
if provided:
|
| 73 |
+
return provided[: self.max_candidates]
|
| 74 |
+
if self.signqa is None:
|
| 75 |
+
return []
|
| 76 |
+
return self.signqa.find_gloss_videos(gloss)[: self.max_candidates]
|
| 77 |
+
|
| 78 |
+
def __getitem__(self, idx):
|
| 79 |
+
item = self.examples[idx]
|
| 80 |
+
prompt = item["prompt"]
|
| 81 |
+
gloss = item["gloss"]
|
| 82 |
+
video_id = item.get("video_id")
|
| 83 |
+
|
| 84 |
+
# Tokenize prompt and gloss
|
| 85 |
+
model_inputs = self.tokenizer(
|
| 86 |
+
prompt,
|
| 87 |
+
truncation=True,
|
| 88 |
+
max_length=self.max_input_length,
|
| 89 |
+
return_tensors=None,
|
| 90 |
+
)
|
| 91 |
+
with self.tokenizer.as_target_tokenizer():
|
| 92 |
+
labels = self.tokenizer(
|
| 93 |
+
gloss,
|
| 94 |
+
truncation=True,
|
| 95 |
+
max_length=self.max_target_length,
|
| 96 |
+
return_tensors=None,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
candidates = self._expand_candidates(gloss, item.get("candidate_video_ids"))
|
| 100 |
+
candidate_ids = [self.pose_vocab.get(cid, -1) for cid in candidates]
|
| 101 |
+
# Pad/trim candidates
|
| 102 |
+
if len(candidate_ids) < self.max_candidates:
|
| 103 |
+
candidate_ids += [-1] * (self.max_candidates - len(candidate_ids))
|
| 104 |
+
else:
|
| 105 |
+
candidate_ids = candidate_ids[: self.max_candidates]
|
| 106 |
+
|
| 107 |
+
pose_label = -1
|
| 108 |
+
if video_id is not None and video_id in self.pose_vocab:
|
| 109 |
+
pose_label = self.pose_vocab[video_id]
|
| 110 |
+
elif candidates:
|
| 111 |
+
# Fall back to first candidate if ground truth is unknown
|
| 112 |
+
pose_label = self.pose_vocab.get(candidates[0], -1)
|
| 113 |
+
|
| 114 |
+
return {
|
| 115 |
+
"input_ids": torch.tensor(model_inputs["input_ids"], dtype=torch.long),
|
| 116 |
+
"attention_mask": torch.tensor(model_inputs["attention_mask"], dtype=torch.long),
|
| 117 |
+
"labels": torch.tensor(labels["input_ids"], dtype=torch.long),
|
| 118 |
+
"candidate_pose_ids": torch.tensor(candidate_ids, dtype=torch.long),
|
| 119 |
+
"pose_label": torch.tensor(pose_label, dtype=torch.long),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def collate_fn(batch, pad_token_id: int):
|
| 124 |
+
"""Pad variable-length fields and keep pose metadata."""
|
| 125 |
+
input_ids = [b["input_ids"] for b in batch]
|
| 126 |
+
attention_masks = [b["attention_mask"] for b in batch]
|
| 127 |
+
labels = [b["labels"] for b in batch]
|
| 128 |
+
candidate_pose_ids = torch.stack([b["candidate_pose_ids"] for b in batch], dim=0)
|
| 129 |
+
pose_labels = torch.stack([b["pose_label"] for b in batch], dim=0)
|
| 130 |
+
|
| 131 |
+
input_ids = torch.nn.utils.rnn.pad_sequence(
|
| 132 |
+
input_ids, batch_first=True, padding_value=pad_token_id
|
| 133 |
+
)
|
| 134 |
+
attention_masks = torch.nn.utils.rnn.pad_sequence(
|
| 135 |
+
attention_masks, batch_first=True, padding_value=0
|
| 136 |
+
)
|
| 137 |
+
labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=-100)
|
| 138 |
+
|
| 139 |
+
return {
|
| 140 |
+
"input_ids": input_ids,
|
| 141 |
+
"attention_mask": attention_masks,
|
| 142 |
+
"labels": labels,
|
| 143 |
+
"candidate_pose_ids": candidate_pose_ids,
|
| 144 |
+
"pose_label": pose_labels,
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# ---------------------------- Model ---------------------------- #
|
| 149 |
+
class PoseMoEModel(nn.Module):
|
| 150 |
+
"""T5-based text->gloss with a lightweight pose-selection MoE head."""
|
| 151 |
+
|
| 152 |
+
def __init__(
|
| 153 |
+
self,
|
| 154 |
+
base_model_name: str,
|
| 155 |
+
pose_vocab_size: int,
|
| 156 |
+
pose_hidden_size: Optional[int] = None,
|
| 157 |
+
pose_loss_weight: float = 1.0,
|
| 158 |
+
sagm_loss_weight: float = 0.1,
|
| 159 |
+
sagm_mask_ratio: float = 0.15,
|
| 160 |
+
):
|
| 161 |
+
super().__init__()
|
| 162 |
+
self.text_model = AutoModelForSeq2SeqLM.from_pretrained(base_model_name)
|
| 163 |
+
hidden_size = self.text_model.config.d_model
|
| 164 |
+
pose_hidden = pose_hidden_size or hidden_size
|
| 165 |
+
self.pose_embeddings = nn.Embedding(pose_vocab_size, pose_hidden)
|
| 166 |
+
self.pose_proj = nn.Linear(hidden_size, pose_hidden)
|
| 167 |
+
self.pose_loss_weight = pose_loss_weight
|
| 168 |
+
self.sagm_loss_weight = sagm_loss_weight
|
| 169 |
+
self.sagm_mask_ratio = sagm_mask_ratio
|
| 170 |
+
self.loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
|
| 171 |
+
|
| 172 |
+
def forward(
|
| 173 |
+
self,
|
| 174 |
+
input_ids,
|
| 175 |
+
attention_mask,
|
| 176 |
+
labels,
|
| 177 |
+
candidate_pose_ids,
|
| 178 |
+
pose_label,
|
| 179 |
+
):
|
| 180 |
+
outputs = self.text_model(
|
| 181 |
+
input_ids=input_ids,
|
| 182 |
+
attention_mask=attention_mask,
|
| 183 |
+
labels=labels,
|
| 184 |
+
output_hidden_states=True,
|
| 185 |
+
)
|
| 186 |
+
gloss_loss = outputs.loss
|
| 187 |
+
|
| 188 |
+
encoder_hidden = outputs.encoder_last_hidden_state
|
| 189 |
+
pooled = encoder_hidden.mean(dim=1) # simple pooling
|
| 190 |
+
|
| 191 |
+
# Pose gating
|
| 192 |
+
candidate_pose_ids = candidate_pose_ids.clone()
|
| 193 |
+
candidate_mask = candidate_pose_ids >= 0
|
| 194 |
+
candidate_pose_ids = torch.where(candidate_mask, candidate_pose_ids, torch.zeros_like(candidate_pose_ids))
|
| 195 |
+
|
| 196 |
+
pose_embed = self.pose_embeddings(candidate_pose_ids)
|
| 197 |
+
pooled_proj = self.pose_proj(pooled).unsqueeze(1)
|
| 198 |
+
pose_logits = torch.sum(pooled_proj * pose_embed, dim=-1)
|
| 199 |
+
pose_logits = pose_logits.masked_fill(~candidate_mask, -1e4)
|
| 200 |
+
|
| 201 |
+
pose_loss = torch.tensor(0.0, device=input_ids.device)
|
| 202 |
+
if pose_label is not None and pose_label.max() >= 0:
|
| 203 |
+
# Map absolute pose ids to positions within candidate list
|
| 204 |
+
label_positions = []
|
| 205 |
+
for i in range(candidate_pose_ids.size(0)):
|
| 206 |
+
target = int(pose_label[i].item())
|
| 207 |
+
if target < 0:
|
| 208 |
+
label_positions.append(-100)
|
| 209 |
+
continue
|
| 210 |
+
positions = (candidate_pose_ids[i] == target).nonzero(as_tuple=False)
|
| 211 |
+
label_positions.append(int(positions[0].item()) if len(positions) > 0 else -100)
|
| 212 |
+
label_positions = torch.tensor(label_positions, device=input_ids.device, dtype=torch.long)
|
| 213 |
+
if (label_positions != -100).any():
|
| 214 |
+
pose_loss = self.loss_fct(pose_logits, label_positions)
|
| 215 |
+
|
| 216 |
+
total_loss = gloss_loss + self.pose_loss_weight * pose_loss
|
| 217 |
+
sagm_loss = self.compute_sagm_loss(outputs.logits, labels)
|
| 218 |
+
total_loss = total_loss + self.sagm_loss_weight * sagm_loss
|
| 219 |
+
|
| 220 |
+
return {
|
| 221 |
+
"loss": total_loss,
|
| 222 |
+
"gloss_loss": gloss_loss.detach(),
|
| 223 |
+
"pose_loss": pose_loss.detach(),
|
| 224 |
+
"sagm_loss": sagm_loss.detach(),
|
| 225 |
+
"pose_logits": pose_logits,
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
def compute_sagm_loss(self, logits, labels):
|
| 229 |
+
"""Mask a subset of gloss tokens to enforce semantic robustness."""
|
| 230 |
+
if labels is None:
|
| 231 |
+
return torch.tensor(0.0, device=logits.device)
|
| 232 |
+
with torch.no_grad():
|
| 233 |
+
mask = (labels != -100) & (
|
| 234 |
+
torch.rand_like(labels.float(), device=labels.device) < self.sagm_mask_ratio
|
| 235 |
+
)
|
| 236 |
+
sagm_labels = torch.where(mask, labels, torch.full_like(labels, -100))
|
| 237 |
+
loss = self.loss_fct(logits.view(-1, logits.size(-1)), sagm_labels.view(-1))
|
| 238 |
+
return loss
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
# ---------------------------- Training helpers ---------------------------- #
|
| 242 |
+
@dataclass
|
| 243 |
+
class TrainConfig:
|
| 244 |
+
train_file: str
|
| 245 |
+
eval_file: Optional[str]
|
| 246 |
+
pose_json: str
|
| 247 |
+
pose_npz_dir: str
|
| 248 |
+
model_name: str
|
| 249 |
+
output_dir: str
|
| 250 |
+
batch_size: int
|
| 251 |
+
num_epochs: int
|
| 252 |
+
lr: float
|
| 253 |
+
warmup_ratio: float
|
| 254 |
+
weight_decay: float
|
| 255 |
+
max_input_len: int
|
| 256 |
+
max_target_len: int
|
| 257 |
+
max_candidates: int
|
| 258 |
+
pose_loss_weight: float
|
| 259 |
+
sagm_loss_weight: float
|
| 260 |
+
sagm_mask_ratio: float
|
| 261 |
+
grad_accum: int
|
| 262 |
+
save_steps: int
|
| 263 |
+
device: str
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def load_json_any(path: Path) -> List[dict]:
|
| 267 |
+
if path.suffix.lower() == ".jsonl":
|
| 268 |
+
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
|
| 269 |
+
data = json.loads(path.read_text())
|
| 270 |
+
if isinstance(data, dict):
|
| 271 |
+
return data.get("data", [])
|
| 272 |
+
return data
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def build_pose_vocab(examples: List[dict], signqa: SignLanguageQA) -> Dict[str, int]:
|
| 276 |
+
vocab = {}
|
| 277 |
+
for ex in examples:
|
| 278 |
+
if "video_id" in ex:
|
| 279 |
+
vocab.setdefault(str(ex["video_id"]), len(vocab))
|
| 280 |
+
gloss = ex.get("gloss", "")
|
| 281 |
+
for vid in signqa.find_gloss_videos(gloss):
|
| 282 |
+
if vid not in vocab:
|
| 283 |
+
vocab[vid] = len(vocab)
|
| 284 |
+
for vid in ex.get("candidate_video_ids", []) or []:
|
| 285 |
+
if vid not in vocab:
|
| 286 |
+
vocab[vid] = len(vocab)
|
| 287 |
+
return vocab
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def evaluate(model, data_loader, device):
|
| 291 |
+
model.eval()
|
| 292 |
+
total_loss = 0.0
|
| 293 |
+
steps = 0
|
| 294 |
+
with torch.no_grad():
|
| 295 |
+
for batch in data_loader:
|
| 296 |
+
batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
|
| 297 |
+
out = model(**batch)
|
| 298 |
+
total_loss += out["loss"].item()
|
| 299 |
+
steps += 1
|
| 300 |
+
model.train()
|
| 301 |
+
return total_loss / max(steps, 1)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def train(config: TrainConfig):
|
| 305 |
+
tokenizer = AutoTokenizer.from_pretrained(config.model_name)
|
| 306 |
+
text2pose_module.JSON_FILE = config.pose_json
|
| 307 |
+
text2pose_module.NPZ_DIR = config.pose_npz_dir
|
| 308 |
+
signqa = SignLanguageQA()
|
| 309 |
+
|
| 310 |
+
train_examples = load_json_any(Path(config.train_file))
|
| 311 |
+
eval_examples = load_json_any(Path(config.eval_file)) if config.eval_file else []
|
| 312 |
+
pose_vocab = build_pose_vocab(train_examples + eval_examples, signqa)
|
| 313 |
+
|
| 314 |
+
train_ds = PromptGlossPoseDataset(
|
| 315 |
+
train_examples,
|
| 316 |
+
tokenizer,
|
| 317 |
+
pose_vocab,
|
| 318 |
+
signqa,
|
| 319 |
+
max_input_length=config.max_input_len,
|
| 320 |
+
max_target_length=config.max_target_len,
|
| 321 |
+
max_candidates=config.max_candidates,
|
| 322 |
+
)
|
| 323 |
+
eval_ds = (
|
| 324 |
+
PromptGlossPoseDataset(
|
| 325 |
+
eval_examples,
|
| 326 |
+
tokenizer,
|
| 327 |
+
pose_vocab,
|
| 328 |
+
signqa,
|
| 329 |
+
max_input_length=config.max_input_len,
|
| 330 |
+
max_target_length=config.max_target_len,
|
| 331 |
+
max_candidates=config.max_candidates,
|
| 332 |
+
)
|
| 333 |
+
if eval_examples
|
| 334 |
+
else None
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
model = PoseMoEModel(
|
| 338 |
+
config.model_name,
|
| 339 |
+
pose_vocab_size=len(pose_vocab),
|
| 340 |
+
pose_loss_weight=config.pose_loss_weight,
|
| 341 |
+
sagm_loss_weight=config.sagm_loss_weight,
|
| 342 |
+
sagm_mask_ratio=config.sagm_mask_ratio,
|
| 343 |
+
).to(config.device)
|
| 344 |
+
|
| 345 |
+
train_loader = DataLoader(
|
| 346 |
+
train_ds,
|
| 347 |
+
batch_size=config.batch_size,
|
| 348 |
+
shuffle=True,
|
| 349 |
+
collate_fn=lambda b: collate_fn(b, tokenizer.pad_token_id),
|
| 350 |
+
)
|
| 351 |
+
eval_loader = (
|
| 352 |
+
DataLoader(
|
| 353 |
+
eval_ds,
|
| 354 |
+
batch_size=config.batch_size,
|
| 355 |
+
shuffle=False,
|
| 356 |
+
collate_fn=lambda b: collate_fn(b, tokenizer.pad_token_id),
|
| 357 |
+
)
|
| 358 |
+
if eval_ds
|
| 359 |
+
else None
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
num_update_steps = math.ceil(len(train_loader) / config.grad_accum) * config.num_epochs
|
| 363 |
+
warmup_steps = int(config.warmup_ratio * num_update_steps)
|
| 364 |
+
|
| 365 |
+
optimizer = AdamW(model.parameters(), lr=config.lr, weight_decay=config.weight_decay)
|
| 366 |
+
scheduler = get_linear_schedule_with_warmup(
|
| 367 |
+
optimizer, num_warmup_steps=warmup_steps, num_training_steps=num_update_steps
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
global_step = 0
|
| 371 |
+
for epoch in range(config.num_epochs):
|
| 372 |
+
for step, batch in enumerate(train_loader):
|
| 373 |
+
batch = {k: v.to(config.device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
|
| 374 |
+
outputs = model(**batch)
|
| 375 |
+
loss = outputs["loss"] / config.grad_accum
|
| 376 |
+
loss.backward()
|
| 377 |
+
|
| 378 |
+
if (step + 1) % config.grad_accum == 0:
|
| 379 |
+
optimizer.step()
|
| 380 |
+
scheduler.step()
|
| 381 |
+
optimizer.zero_grad()
|
| 382 |
+
global_step += 1
|
| 383 |
+
|
| 384 |
+
if global_step % 10 == 0:
|
| 385 |
+
print(
|
| 386 |
+
f"[Epoch {epoch+1}] step {global_step} | "
|
| 387 |
+
f"loss {outputs['loss'].item():.4f} | "
|
| 388 |
+
f"gloss {outputs['gloss_loss'].item():.4f} | "
|
| 389 |
+
f"pose {outputs['pose_loss'].item():.4f} | "
|
| 390 |
+
f"sagm {outputs['sagm_loss'].item():.4f}"
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
if config.save_steps and global_step % config.save_steps == 0:
|
| 394 |
+
save_dir = Path(config.output_dir) / f"checkpoint-{global_step}"
|
| 395 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 396 |
+
model.text_model.save_pretrained(save_dir)
|
| 397 |
+
tokenizer.save_pretrained(save_dir)
|
| 398 |
+
(save_dir / "pose_vocab.json").write_text(json.dumps(pose_vocab, indent=2))
|
| 399 |
+
|
| 400 |
+
if eval_loader:
|
| 401 |
+
eval_loss = evaluate(model, eval_loader, config.device)
|
| 402 |
+
print(f"[Epoch {epoch+1}] eval loss: {eval_loss:.4f}")
|
| 403 |
+
|
| 404 |
+
Path(config.output_dir).mkdir(parents=True, exist_ok=True)
|
| 405 |
+
model.text_model.save_pretrained(config.output_dir)
|
| 406 |
+
tokenizer.save_pretrained(config.output_dir)
|
| 407 |
+
(Path(config.output_dir) / "pose_vocab.json").write_text(json.dumps(pose_vocab, indent=2))
|
| 408 |
+
print(f"Training finished. Saved to {config.output_dir}")
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def parse_args() -> TrainConfig:
|
| 412 |
+
parser = argparse.ArgumentParser(description="Train StableSigner SLUL + Pose MoE")
|
| 413 |
+
parser.add_argument("--train-file", required=True, help="Path to train json/jsonl")
|
| 414 |
+
parser.add_argument("--eval-file", default=None, help="Optional eval json/jsonl")
|
| 415 |
+
parser.add_argument("--pose-json", default="pose_dict/WLASL_train.json", help="Pose mapping JSON")
|
| 416 |
+
parser.add_argument("--pose-npz-dir", default="pose_dict/WLASL_train", help="Pose NPZ directory (for future use)")
|
| 417 |
+
parser.add_argument("--model-name", default="google/flan-t5-small", help="HF model name or path")
|
| 418 |
+
parser.add_argument("--output-dir", default="outputs/slul_pose_moe", help="Where to save checkpoints")
|
| 419 |
+
parser.add_argument("--batch-size", type=int, default=4)
|
| 420 |
+
parser.add_argument("--num-epochs", type=int, default=3)
|
| 421 |
+
parser.add_argument("--lr", type=float, default=3e-4)
|
| 422 |
+
parser.add_argument("--warmup-ratio", type=float, default=0.03)
|
| 423 |
+
parser.add_argument("--weight-decay", type=float, default=0.01)
|
| 424 |
+
parser.add_argument("--max-input-len", type=int, default=256)
|
| 425 |
+
parser.add_argument("--max-target-len", type=int, default=64)
|
| 426 |
+
parser.add_argument("--max-candidates", type=int, default=8)
|
| 427 |
+
parser.add_argument("--pose-loss-weight", type=float, default=1.0)
|
| 428 |
+
parser.add_argument("--sagm-loss-weight", type=float, default=0.1)
|
| 429 |
+
parser.add_argument("--sagm-mask-ratio", type=float, default=0.15)
|
| 430 |
+
parser.add_argument("--grad-accum", type=int, default=1)
|
| 431 |
+
parser.add_argument("--save-steps", type=int, default=500)
|
| 432 |
+
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
|
| 433 |
+
args = parser.parse_args()
|
| 434 |
+
return TrainConfig(
|
| 435 |
+
train_file=args.train_file,
|
| 436 |
+
eval_file=args.eval_file,
|
| 437 |
+
pose_json=args.pose_json,
|
| 438 |
+
pose_npz_dir=args.pose_npz_dir,
|
| 439 |
+
model_name=args.model_name,
|
| 440 |
+
output_dir=args.output_dir,
|
| 441 |
+
batch_size=args.batch_size,
|
| 442 |
+
num_epochs=args.num_epochs,
|
| 443 |
+
lr=args.lr,
|
| 444 |
+
warmup_ratio=args.warmup_ratio,
|
| 445 |
+
weight_decay=args.weight_decay,
|
| 446 |
+
max_input_len=args.max_input_len,
|
| 447 |
+
max_target_len=args.max_target_len,
|
| 448 |
+
max_candidates=args.max_candidates,
|
| 449 |
+
pose_loss_weight=args.pose_loss_weight,
|
| 450 |
+
sagm_loss_weight=args.sagm_loss_weight,
|
| 451 |
+
sagm_mask_ratio=args.sagm_mask_ratio,
|
| 452 |
+
grad_accum=args.grad_accum,
|
| 453 |
+
save_steps=args.save_steps,
|
| 454 |
+
device=args.device,
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
if __name__ == "__main__":
|
| 459 |
+
cfg = parse_args()
|
| 460 |
+
train(cfg)
|
utils/__pycache__/npz_interpolation.cpython-312.pyc
ADDED
|
Binary file (9.28 kB). View file
|
|
|