FangSen9000 commited on
Commit
7e160a8
·
1 Parent(s): d7173b2

Remove SignX from main repo and ignore

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +1 -1
  2. plugins/SignX/.gitignore +0 -26
  3. plugins/SignX/README.md +0 -97
  4. plugins/SignX/eval/analyze_video2pose.py +0 -228
  5. plugins/SignX/eval/attention_analysis.py +0 -946
  6. plugins/SignX/eval/benchmark_smkd.sh +0 -141
  7. plugins/SignX/eval/extract_attention_keyframes.py +0 -198
  8. plugins/SignX/eval/generate_feature_mapping.py +0 -126
  9. plugins/SignX/eval/generate_gloss_frames.py +0 -232
  10. plugins/SignX/eval/generate_interactive_alignment.py +0 -670
  11. plugins/SignX/eval/good_videos_copy.sh +0 -87
  12. plugins/SignX/eval/metrics.py +0 -320
  13. plugins/SignX/eval/mscoco_rouge.py +0 -67
  14. plugins/SignX/eval/phoenix_cleanup.py +0 -90
  15. plugins/SignX/eval/pose_vit_dim_analysis.py +0 -442
  16. plugins/SignX/eval/regenerate_visualizations.py +0 -122
  17. plugins/SignX/eval/sacrebleu.py +0 -0
  18. plugins/SignX/eval/simple_benchmark.sh +0 -188
  19. plugins/SignX/eval/tiny_test_data_for_ASLLRP/README.md +0 -86
  20. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/171921.mp4 +0 -3
  21. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/173238.mp4 +0 -3
  22. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/173745.mp4 +0 -3
  23. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/23880856.mp4 +0 -3
  24. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/23881350.mp4 +0 -3
  25. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/31655975.mp4 +0 -3
  26. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/31657848.mp4 +0 -3
  27. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/3378265.mp4 +0 -3
  28. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/3381121.mp4 +0 -3
  29. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/4235359.mp4 +0 -3
  30. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/4236171.mp4 +0 -3
  31. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/50802118.mp4 +0 -3
  32. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/5597316.mp4 +0 -3
  33. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/6185086.mp4 +0 -3
  34. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/6185381.mp4 +0 -3
  35. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/619048.mp4 +0 -3
  36. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/629983.mp4 +0 -3
  37. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/634818.mp4 +0 -3
  38. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/63579.mp4 +0 -3
  39. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7454155.mp4 +0 -3
  40. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7566726.mp4 +0 -3
  41. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7569669.mp4 +0 -3
  42. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7701925.mp4 +0 -3
  43. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7710510.mp4 +0 -3
  44. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7981884.mp4 +0 -3
  45. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7982378.mp4 +0 -3
  46. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7983362.mp4 +0 -3
  47. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/83940254.mp4 +0 -3
  48. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/83940846.mp4 +0 -3
  49. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/83941734.mp4 +0 -3
  50. plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/8394388.mp4 +0 -3
.gitignore CHANGED
@@ -8,4 +8,4 @@ plugins/ASLLRP_info
8
  plugins/YouTubeASL
9
  plugins/SignX/smkd/work_dir
10
  plugins/SignX/smkd/youtubeasl
11
- plugins/StableSigner
 
8
  plugins/YouTubeASL
9
  plugins/SignX/smkd/work_dir
10
  plugins/SignX/smkd/youtubeasl
11
+ plugins/SignX/
plugins/SignX/.gitignore DELETED
@@ -1,26 +0,0 @@
1
- *.pyc
2
- *.so
3
- *.egg-info
4
- *.whl
5
- .ipynb_checkpoints
6
- .DS_Store
7
- .idea
8
- .vscode
9
- .envrc
10
- *.jpg
11
- *.npz
12
- *.xlsx
13
-
14
- checkpoints_asllrp第七次训练全pose协助2000
15
- checkpoints_asllrp第一次训练的基线
16
- checkpoints_csldaily
17
- checkpoints_dgs3-t
18
- checkpoints_phoenix
19
- doc/
20
-
21
- inference_output*
22
-
23
- smkd/history/
24
- training_asllrp
25
- training_dgs3-t
26
- training_phoenix
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/README.md DELETED
@@ -1,97 +0,0 @@
1
- # SLTUNET: A Simple Unified Model for Sign Language Translation (ICLR 2023)
2
-
3
- [**Paper**](https://openreview.net/forum?id=EBS4C77p_5S) |
4
- [**Highlights**](#paper-highlights) |
5
- [**Overview**](#model-visualization) |
6
- [**DGS3-T**](#dgs3-t) |
7
- [**Training&Eval**](#training-and-evaluation) |
8
- [**Model Performance**](#performance) |
9
- [**Citation**](#citation)
10
-
11
-
12
- * Update (2023/07/09): We release the trained model for phoenix and csldaily at [here](https://data.statmt.org/bzhang/iclr2023_sltunet/). See `infer.sh` for details.
13
-
14
-
15
- ## Paper Highlights
16
-
17
- Among thousands of languages globally, some are written, some are spoken, while some are signed.
18
- Sign languages are unique **natural** languages widely used in Deaf communities. They express
19
- meaning through hand gestures, body movements and facial expressions, and are often in a video form.
20
- We refer the readers to [Sign language Processing](https://research.sign.mt/) for a better understanding
21
- of sign languages.
22
-
23
- In this study, we aim at improving sign language translation, i.e. translating information from
24
- sign languages (in a video) to spoken languages (in text). We address the video-text modality gap and
25
- the training data scarcity issue via multi-task learning and unified modeling.
26
-
27
- Briefly,
28
- - We propose a simple unified model, SLTUNET, for SLT, and show that jointly modeling
29
- multiple SLT-related tasks benefits the translation.
30
- - We propose a set of optimization techniques for SLTUNET aiming at an improved trade-off
31
- between model capacity and regularization, which also helps SLT models for single tasks.
32
- - SLTUNET performs competitively to previous methods and yields the new state-of-the-art
33
- performance on CSL-Daily.
34
- - We use the DGS Corpus and propose [DGS3-T](#dgs3-t) for end-to-end SLT, with larger
35
- scale, richer topics and more significant challenges than existing datasets.
36
-
37
- ## Model Visualization
38
-
39
- ![Overview of ur proposal](model.png)
40
-
41
-
42
- ## DGS3-T
43
-
44
- * Similar to PHOENIX-2014T and CSL-Daily, DGS3-T is a dataset used for the study of SLT, consisting of sign videos and text translations.
45
-
46
- * Different from these previous datasets, DGS3-T is larger at scale, covering broader domains and topics with more signers.
47
-
48
- * DGS3-T represents more practical challenges in SLT. We encourage researchers to consider it for SLT research.
49
-
50
-
51
- **DGS3-T Licensing**
52
-
53
- DGS3-T is based on [the Public DGS Corpus](https://www.sign-lang.uni-hamburg.de/meinedgs/ling/license_en.html). The license of the Public DGS Corpus does not allow any computational research except if express
54
- permission is given by the University of Hamburg.
55
-
56
- **Constructing DGS3-T**
57
-
58
- Please check out [dgs3-t](./dgs3-t) for details.
59
-
60
- ## Requirement
61
-
62
- The source code is based on older tensorflow.
63
-
64
- - python==3.8
65
- - tensorflow==1.15
66
-
67
-
68
- ## Training and Evaluation
69
-
70
- Training includes two phrase: 1) pretrain sign embeddings; 2) train SLTUNet model.
71
-
72
- Please check out [example](./example) for details.
73
-
74
-
75
- ## Performance
76
-
77
- ![Resulst on Phoenix](phoenix.png)
78
-
79
- Check out [our paper](https://openreview.net/forum?id=EBS4C77p_5S) for more results on CSLDaily and DGS3-T.
80
-
81
- * Update (2023/04/02): note, for CSL-Daily, **we always adopt subword preprocessing (NOT character) for the target text
82
- and gloss sequence during training and inference**;
83
- We post-process the generated subword sequence into a character sequence at evaluation for char-level BLEU.
84
-
85
- ## Citation
86
-
87
- If you draw any inspiration from our study, please consider to cite our paper:
88
- ```
89
- @inproceedings{
90
- zhang2023sltunet,
91
- title={{SLTUNET}: A Simple Unified Model for Sign Language Translation},
92
- author={Biao Zhang and Mathias M{\"u}ller and Rico Sennrich},
93
- booktitle={The Eleventh International Conference on Learning Representations },
94
- year={2023},
95
- url={https://openreview.net/forum?id=EBS4C77p_5S}
96
- }
97
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/analyze_video2pose.py DELETED
@@ -1,228 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Analyze pose ViT features from video2text checkpoint outputs."""
3
-
4
- import argparse
5
- import json
6
- import os
7
- from pathlib import Path
8
-
9
- import cv2
10
- import matplotlib
11
-
12
- matplotlib.use("Agg")
13
- import matplotlib.pyplot as plt
14
- import numpy as np
15
- import torch
16
- from PIL import Image
17
- from torchvision import transforms
18
-
19
- from smkd.pretrained.video2text import (
20
- MultimodalPose2TextDiffusion,
21
- MultimodalVideo2TextDiffusion,
22
- )
23
-
24
- INPUT_DIMS = {
25
- "dwpose": 384,
26
- "mediapipe_pose": 258,
27
- "primedepth_depth": 576,
28
- "sapiens_segmentation": 576,
29
- "smplerx": 165,
30
- }
31
-
32
-
33
- def parse_args():
34
- parser = argparse.ArgumentParser(description="Pose-dimensional ablation via video2text checkpoint.")
35
- parser.add_argument("--video", required=True, help="Path to input video (mp4).")
36
- parser.add_argument(
37
- "--checkpoint",
38
- default="smkd/pretrained/video2text_checkpoint_epoch_14.pth",
39
- help="Path to video2text checkpoint.",
40
- )
41
- parser.add_argument(
42
- "--output-dir",
43
- default="pose_vit_feature_analysis",
44
- help="Directory to store extracted features/plots.",
45
- )
46
- parser.add_argument("--num-frames", type=int, default=32, help="Number of frames sampled from video.")
47
- parser.add_argument("--device", default="cuda", choices=["cuda", "cpu"], help="Torch device preference.")
48
- parser.add_argument("--topk", type=int, default=32, help="Top dimensions to visualize.")
49
- return parser.parse_args()
50
-
51
-
52
- def prepare_device(device_pref: str) -> torch.device:
53
- if device_pref == "cuda" and torch.cuda.is_available():
54
- return torch.device("cuda")
55
- return torch.device("cpu")
56
-
57
-
58
- def ensure_dir(path: str) -> Path:
59
- path_obj = Path(path)
60
- path_obj.mkdir(parents=True, exist_ok=True)
61
- return path_obj
62
-
63
-
64
- def load_video_frames(video_path: str, num_frames: int, transform) -> torch.Tensor:
65
- cap = cv2.VideoCapture(video_path)
66
- if not cap.isOpened():
67
- raise RuntimeError(f"Failed to open video: {video_path}")
68
-
69
- total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
70
- if total_frames <= 0:
71
- raise RuntimeError(f"No frames found in video: {video_path}")
72
-
73
- indices = np.linspace(0, max(total_frames - 1, 0), num=num_frames, dtype=np.int32)
74
- frames = []
75
-
76
- for idx in indices:
77
- cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx))
78
- ok, frame = cap.read()
79
- if not ok:
80
- continue
81
- frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
82
- frames.append(transform(Image.fromarray(frame)))
83
-
84
- cap.release()
85
-
86
- if not frames:
87
- raise RuntimeError(f"No decodable frames in video: {video_path}")
88
-
89
- while len(frames) < num_frames:
90
- frames.append(frames[-1].clone())
91
-
92
- return torch.stack(frames[:num_frames], dim=0)
93
-
94
-
95
- def compute_dimension_stats(pose_2048: torch.Tensor):
96
- with torch.no_grad():
97
- scores = pose_2048.abs().mean(dim=(0, 1))
98
- normalized = scores / (scores.max() + 1e-8)
99
- return scores.cpu().numpy(), normalized.cpu().numpy()
100
-
101
-
102
- def plot_top_dims(scores, top_indices, output_path):
103
- plt.figure(figsize=(max(8, len(top_indices) * 0.35), 4))
104
- plt.bar(range(len(top_indices)), scores[top_indices], color="#1f77b4")
105
- plt.xticks(range(len(top_indices)), [str(i) for i in top_indices], rotation=60)
106
- plt.ylabel("Mean |value|")
107
- plt.xlabel("Dimension")
108
- plt.title("Top pose dimensions")
109
- plt.tight_layout()
110
- plt.savefig(output_path, dpi=240)
111
- plt.close()
112
-
113
-
114
- def plot_heatmap(norm_scores, output_path):
115
- rows = 32
116
- usable = (norm_scores.shape[0] // rows) * rows
117
- reshaped = norm_scores[:usable].reshape(rows, -1)
118
- plt.figure(figsize=(12, 4))
119
- plt.imshow(reshaped, aspect="auto", cmap="magma")
120
- plt.colorbar(label="Normalized importance")
121
- plt.xlabel("Chunk index")
122
- plt.ylabel("Row")
123
- plt.title("Pose dimension importance heatmap")
124
- plt.tight_layout()
125
- plt.savefig(output_path, dpi=240)
126
- plt.close()
127
-
128
-
129
- def plot_cumulative(scores, output_path):
130
- sorted_scores = np.sort(scores)[::-1]
131
- cumsum = np.cumsum(sorted_scores)
132
- coverage = cumsum / cumsum[-1]
133
- dims = np.arange(1, len(sorted_scores) + 1)
134
- plt.figure(figsize=(8, 4))
135
- plt.plot(dims, coverage, color="#ff7f0e")
136
- plt.xlabel("Top-k dimensions")
137
- plt.ylabel("Cumulative coverage")
138
- plt.grid(alpha=0.3)
139
- plt.tight_layout()
140
- plt.savefig(output_path, dpi=240)
141
- plt.close()
142
- return coverage
143
-
144
-
145
- def save_csv(scores, norm_scores, output_path):
146
- with open(output_path, "w", encoding="utf-8") as handle:
147
- handle.write("dimension,score,normalized\n")
148
- for idx, (score, norm) in enumerate(zip(scores, norm_scores)):
149
- handle.write(f"{idx},{score:.8f},{norm:.6f}\n")
150
-
151
-
152
- def write_report(video_path, checkpoint, scores, norm_scores, coverage, top_indices, output_path):
153
- levels = [0.25, 0.5, 0.9]
154
- with open(output_path, "w", encoding="utf-8") as handle:
155
- handle.write("Pose ViT dimensional analysis\n")
156
- handle.write("=" * 60 + "\n\n")
157
- handle.write(f"Video : {video_path}\n")
158
- handle.write(f"Checkpoint : {checkpoint}\n")
159
- handle.write(f"Total dims : {scores.shape[0]}\n\n")
160
- handle.write("Top dimensions:\n")
161
- for rank, dim_idx in enumerate(top_indices, 1):
162
- handle.write(
163
- f"{rank:02d}. dim {dim_idx:04d} | score={scores[dim_idx]:.6f} "
164
- f"| normalized={norm_scores[dim_idx]:.4f}\n"
165
- )
166
- handle.write("\nCoverage milestones:\n")
167
- for level in levels:
168
- required = int(np.argmax(coverage >= level) + 1)
169
- handle.write(f" - Top {required:4d} dims explain {level:.0%} of energy\n")
170
- handle.write("\nScores computed as mean absolute activations on pose_2048.\n")
171
-
172
-
173
- def main():
174
- args = parse_args()
175
- video_path = os.path.abspath(args.video)
176
- checkpoint_path = os.path.abspath(args.checkpoint)
177
- output_dir = ensure_dir(args.output_dir)
178
-
179
- if not os.path.exists(video_path):
180
- raise FileNotFoundError(f"Video not found: {video_path}")
181
- if not os.path.exists(checkpoint_path):
182
- raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}")
183
-
184
- device = prepare_device(args.device)
185
- print(f"[INFO] Using device: {device}")
186
-
187
- pose2text = MultimodalPose2TextDiffusion(
188
- input_dims=INPUT_DIMS,
189
- hidden_dim=2048,
190
- device=device,
191
- codebook=None,
192
- )
193
- video2text = MultimodalVideo2TextDiffusion(
194
- pose2text_model=pose2text,
195
- device=device,
196
- )
197
-
198
- checkpoint = torch.load(checkpoint_path, map_location=device)
199
- load_result = video2text.load_state_dict(checkpoint["model_state_dict"], strict=False)
200
- if load_result.missing_keys:
201
- print(f"[WARN] Missing keys ({len(load_result.missing_keys)}): {load_result.missing_keys[:5]}...")
202
- if load_result.unexpected_keys:
203
- print(f"[WARN] Unexpected keys ({len(load_result.unexpected_keys)}): {load_result.unexpected_keys[:5]}...")
204
- video2text.eval()
205
-
206
- frame_transform = transforms.Compose(
207
- [
208
- transforms.Resize((224, 224)),
209
- transforms.ToTensor(),
210
- transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
211
- ]
212
- )
213
- frames = load_video_frames(video_path, args.num_frames, frame_transform)
214
- video_tensor = frames.unsqueeze(0).to(device)
215
-
216
- with torch.no_grad():
217
- pose_features = video2text.video2pose(video_tensor)
218
- concatenated = pose2text.pose_encoder(pose_features)
219
- B, F, D = concatenated.shape
220
- flattened = concatenated.reshape(B * F, D)
221
- pose_2048 = pose2text.dim_match(flattened).view(B, F, -1)
222
- pose_numpy = pose_2048.cpu().numpy()
223
-
224
- np.save(output_dir / "pose_2048.npy", pose_numpy)
225
- scores, norm_scores = compute_dimension_stats(pose_2048)
226
- save_csv(scores, norm_scores, output_dir / "dimension_scores.csv")
227
-
228
- topk = min(args.topk, scores.shape)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/attention_analysis.py DELETED
@@ -1,946 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Attention weight analysis and visualization helpers for SignX.
4
-
5
- Capabilities:
6
- 1. Parse attention weight tensors
7
- 2. Map each generated gloss to video frame ranges
8
- 3. Render visual assets (heatmaps, alignment plots, timelines)
9
- 4. Write detailed analysis reports
10
-
11
- Example:
12
- from eval.attention_analysis import AttentionAnalyzer
13
-
14
- analyzer = AttentionAnalyzer(
15
- attentions=attention_weights, # [time, batch, beam, src_len]
16
- translation="WORD1 WORD2 WORD3",
17
- video_frames=100
18
- )
19
-
20
- analyzer.generate_all_visualizations(output_dir="results/")
21
- """
22
-
23
- import os
24
- import io
25
- import json
26
- import shutil
27
- import subprocess
28
- import numpy as np
29
- from pathlib import Path
30
- from datetime import datetime
31
-
32
-
33
- class AttentionAnalyzer:
34
- """Analyze attention tensors and generate visual/debug artifacts."""
35
-
36
- def __init__(self, attentions, translation, video_frames, beam_sequences=None, beam_scores=None,
37
- video_path=None, original_video_fps=30, original_video_total_frames=None):
38
- """
39
- Args:
40
- attentions: numpy array, shape [time_steps, batch, beam, src_len]
41
- or [time_steps, src_len] (best beam already selected)
42
- translation: str, BPE-removed gloss sequence
43
- video_frames: int, number of SMKD feature frames
44
- beam_sequences: list, optional beam texts
45
- beam_scores: list, optional beam scores
46
- video_path: str, optional path to original video (for frame grabs)
47
- original_video_fps: int, FPS of original video (default 30)
48
- original_video_total_frames: optional exact frame count
49
- """
50
- self.attentions = attentions
51
- self.translation = translation
52
- self.words = translation.split()
53
- self.video_frames = video_frames
54
- self.beam_sequences = beam_sequences
55
- self.beam_scores = beam_scores
56
-
57
- # Video metadata
58
- self.video_path = video_path
59
- self.original_video_fps = original_video_fps
60
- self.original_video_total_frames = original_video_total_frames
61
- self._cv2_module = None
62
- self._cv2_checked = False
63
-
64
- # Auto-read metadata if only video path is given
65
- if video_path and original_video_total_frames is None:
66
- metadata = self._read_video_metadata()
67
- if metadata:
68
- self.original_video_total_frames = metadata.get('frames')
69
- if metadata.get('fps'):
70
- self.original_video_fps = metadata['fps']
71
- elif video_path:
72
- print(f"Warning: failed to parse video metadata; gloss-to-frame visualization may be misaligned ({video_path})")
73
-
74
- # Always operate on the best path (batch=0, beam=0)
75
- if len(attentions.shape) == 4:
76
- self.attn_best = attentions[:, 0, 0, :] # [time, src_len]
77
- elif len(attentions.shape) == 3:
78
- self.attn_best = attentions[:, 0, :] # [time, src_len]
79
- else:
80
- self.attn_best = attentions # [time, src_len]
81
-
82
- # Pre-compute gloss-to-frame ranges
83
- self.word_frame_ranges = self._compute_word_frame_ranges()
84
- self.frame_attention_strength = self._compute_frame_attention_strength()
85
-
86
- def _compute_word_frame_ranges(self):
87
- """
88
- Compute the dominant video frame range for each generated word.
89
-
90
- Returns:
91
- list of dict entries containing word, frame range, peak, and confidence.
92
- """
93
- word_ranges = []
94
-
95
- for word_idx, word in enumerate(self.words):
96
- if word_idx >= self.attn_best.shape[0]:
97
- # Out of range
98
- word_ranges.append({
99
- 'word': word,
100
- 'start_frame': 0,
101
- 'end_frame': 0,
102
- 'peak_frame': 0,
103
- 'avg_attention': 0.0,
104
- 'confidence': 'unknown'
105
- })
106
- continue
107
-
108
- attn_weights = self.attn_best[word_idx, :]
109
-
110
- # Peak frame for this word
111
- peak_frame = int(np.argmax(attn_weights))
112
- peak_weight = attn_weights[peak_frame]
113
-
114
- # Frames whose weight >= 90% of the peak
115
- threshold = peak_weight * 0.9
116
- significant_frames = np.where(attn_weights >= threshold)[0]
117
-
118
- if len(significant_frames) > 0:
119
- start_frame = int(significant_frames[0])
120
- end_frame = int(significant_frames[-1])
121
- avg_weight = float(attn_weights[significant_frames].mean())
122
- else:
123
- start_frame = peak_frame
124
- end_frame = peak_frame
125
- avg_weight = float(peak_weight)
126
-
127
- # Qualitative confidence bucket
128
- if avg_weight > 0.5:
129
- confidence = 'high'
130
- elif avg_weight > 0.2:
131
- confidence = 'medium'
132
- else:
133
- confidence = 'low'
134
-
135
- word_ranges.append({
136
- 'word': word,
137
- 'start_frame': start_frame,
138
- 'end_frame': end_frame,
139
- 'peak_frame': peak_frame,
140
- 'avg_attention': avg_weight,
141
- 'confidence': confidence
142
- })
143
-
144
- return word_ranges
145
-
146
- def _compute_frame_attention_strength(self):
147
- """Compute average attention per feature frame (normalized 0-1)."""
148
- if self.attn_best.size == 0:
149
- return np.zeros(self.video_frames, dtype=np.float32)
150
-
151
- if self.attn_best.ndim == 1:
152
- frame_strength = self.attn_best.copy()
153
- else:
154
- frame_strength = self.attn_best.mean(axis=0)
155
-
156
- if frame_strength.shape[0] != self.video_frames:
157
- frame_strength = np.resize(frame_strength, self.video_frames)
158
-
159
- max_val = frame_strength.max()
160
- if max_val > 0:
161
- frame_strength = frame_strength / max_val
162
- return frame_strength
163
-
164
- def _map_strength_to_original_frames(self, mapping_list, original_frame_count):
165
- """Map latent attention strength to original video frame resolution."""
166
- if not mapping_list or original_frame_count <= 0:
167
- return None
168
-
169
- orig_strength = np.zeros(original_frame_count, dtype=np.float32)
170
- counts = np.zeros(original_frame_count, dtype=np.float32)
171
-
172
- for feat_idx, mapping in enumerate(mapping_list):
173
- if feat_idx >= len(self.frame_attention_strength):
174
- break
175
- start = int(mapping.get('frame_start', 0))
176
- end = int(mapping.get('frame_end', start))
177
- end = max(end, start + 1)
178
- start = max(start, 0)
179
- end = min(end, original_frame_count)
180
- if start >= end:
181
- continue
182
- orig_strength[start:end] += self.frame_attention_strength[feat_idx]
183
- counts[start:end] += 1
184
-
185
- mask = counts > 0
186
- if mask.any():
187
- orig_strength[mask] = orig_strength[mask] / counts[mask]
188
-
189
- max_val = orig_strength.max()
190
- if max_val > 0:
191
- orig_strength = orig_strength / max_val
192
- return orig_strength
193
-
194
- def generate_all_visualizations(self, output_dir):
195
- """
196
- Generate every visualization artifact to the provided directory.
197
- """
198
- output_dir = Path(output_dir)
199
- output_dir.mkdir(parents=True, exist_ok=True)
200
-
201
- print(f"\nGenerating visualization assets in: {output_dir}")
202
-
203
- # 1. Attention heatmap
204
- self.plot_attention_heatmap(output_dir / "attention_heatmap.png")
205
-
206
- # 2. Frame alignment
207
- self.plot_frame_alignment(output_dir / "frame_alignment.png")
208
-
209
- # 3. JSON metadata
210
- self.save_alignment_data(output_dir / "frame_alignment.json")
211
-
212
- # 4. Text report
213
- self.save_text_report(output_dir / "analysis_report.txt")
214
-
215
- # 5. Raw numpy dump (for downstream tooling)
216
- np.save(output_dir / "attention_weights.npy", self.attentions)
217
-
218
- # 6. Gloss-to-Frames visualization (if video is available)
219
- # Write debug info to file
220
- debug_file = output_dir / "debug_video_path.txt"
221
- with open(debug_file, 'w') as f:
222
- f.write(f"video_path = {repr(self.video_path)}\n")
223
- f.write(f"video_path type = {type(self.video_path)}\n")
224
- f.write(f"video_path is None: {self.video_path is None}\n")
225
- f.write(f"bool(video_path): {bool(self.video_path)}\n")
226
-
227
- print(f"[DEBUG] video_path = {self.video_path}")
228
- if self.video_path:
229
- print(f"[DEBUG] Generating gloss-to-frames visualization with video: {self.video_path}")
230
- try:
231
- self.generate_gloss_to_frames_visualization(output_dir / "gloss_to_frames.png")
232
- print(f"[DEBUG] Successfully generated gloss_to_frames.png")
233
- except Exception as e:
234
- print(f"[DEBUG] Failed to generate gloss_to_frames.png: {e}")
235
- import traceback
236
- traceback.print_exc()
237
- else:
238
- print("[DEBUG] Skipping gloss-to-frames visualization (no video path provided)")
239
-
240
- print(f"✓ Wrote {len(list(output_dir.glob('*')))} file(s)")
241
-
242
- def plot_attention_heatmap(self, output_path):
243
- """Render the attention heatmap (image + PDF copy)."""
244
- try:
245
- import matplotlib
246
- matplotlib.use('Agg')
247
- import matplotlib.pyplot as plt
248
- except ImportError:
249
- print(" Skipping heatmap: matplotlib is not available")
250
- return
251
-
252
- fig, ax = plt.subplots(figsize=(14, 8))
253
-
254
- # Heatmap
255
- im = ax.imshow(self.attn_best.T, cmap='hot', aspect='auto',
256
- interpolation='nearest', origin='lower')
257
-
258
- # Axis labels
259
- ax.set_xlabel('Generated Word Index', fontsize=13)
260
- ax.set_ylabel('Video Frame Index', fontsize=13)
261
- ax.set_title('Cross-Attention Weights\n(Decoder → Video Frames)',
262
- fontsize=15, pad=20, fontweight='bold')
263
-
264
- # Word labels on the x-axis
265
- if len(self.words) <= self.attn_best.shape[0]:
266
- ax.set_xticks(range(len(self.words)))
267
- ax.set_xticklabels(self.words, rotation=45, ha='right', fontsize=10)
268
-
269
- # Color bar
270
- cbar = plt.colorbar(im, ax=ax, label='Attention Weight', fraction=0.046, pad=0.04)
271
- cbar.ax.tick_params(labelsize=10)
272
-
273
- plt.tight_layout()
274
- plt.savefig(output_path, dpi=150, bbox_inches='tight')
275
- # also save PDF copy for high-res usage
276
- pdf_path = Path(output_path).with_suffix('.pdf')
277
- plt.savefig(str(pdf_path), format='pdf', bbox_inches='tight')
278
- plt.close()
279
-
280
- print(f" ✓ {output_path.name} (PDF copy saved)")
281
-
282
- def plot_frame_alignment(self, output_path):
283
- """Render the frame-alignment charts (full + compact)."""
284
- try:
285
- import matplotlib
286
- matplotlib.use('Agg')
287
- import matplotlib.pyplot as plt
288
- import matplotlib.patches as patches
289
- from matplotlib.gridspec import GridSpec
290
- except ImportError:
291
- print(" Skipping alignment plot: matplotlib is not available")
292
- return
293
-
294
- output_path = Path(output_path)
295
-
296
- # Try to load feature-to-frame mapping
297
- feature_mapping = None
298
- output_dir = output_path.parent
299
- mapping_file = output_dir / "feature_frame_mapping.json"
300
- if mapping_file.exists():
301
- try:
302
- with open(mapping_file, 'r') as f:
303
- feature_mapping = json.load(f)
304
- except Exception as e:
305
- print(f" Warning: Failed to load feature mapping: {e}")
306
-
307
- if self.word_frame_ranges:
308
- max_feat_end = max(w['end_frame'] for w in self.word_frame_ranges)
309
- else:
310
- max_feat_end = self.video_frames - 1
311
- latent_full_limit = self.video_frames + 2
312
- latent_short_limit = max(min(latent_full_limit, max_feat_end + 2), 5)
313
-
314
- original_frame_count = None
315
- mapping_list = None
316
- orig_full_limit = None
317
- orig_short_limit = None
318
- pixel_strength_curve = None
319
- if feature_mapping:
320
- original_frame_count = feature_mapping.get('original_frame_count', self.video_frames)
321
- mapping_list = feature_mapping.get('mapping', [])
322
- orig_full_limit = original_frame_count + 2
323
- if mapping_list:
324
- idx = min(max_feat_end, len(mapping_list) - 1)
325
- orig_short_limit = mapping_list[idx]['frame_end'] + 2
326
- pixel_strength_curve = self._map_strength_to_original_frames(mapping_list, original_frame_count)
327
-
328
- def render_alignment(out_path, latent_xlim_end, orig_xlim_end=None):
329
- if feature_mapping:
330
- fig = plt.figure(figsize=(18, 9))
331
- gs = GridSpec(3, 1, height_ratios=[4, 1, 1], hspace=0.32)
332
- else:
333
- fig = plt.figure(figsize=(18, 7.5))
334
- gs = GridSpec(2, 1, height_ratios=[4, 1], hspace=0.32)
335
-
336
- # === Top plot: word-to-frame alignment ===
337
- ax1 = fig.add_subplot(gs[0])
338
- colors = plt.cm.tab20(np.linspace(0, 1, max(len(self.words), 20)))
339
-
340
- for i, word_info in enumerate(self.word_frame_ranges):
341
- start = word_info['start_frame']
342
- end = word_info['end_frame']
343
- word = word_info['word']
344
- confidence = word_info['confidence']
345
- alpha = 0.9 if confidence == 'high' else 0.7 if confidence == 'medium' else 0.5
346
-
347
- rect = patches.Rectangle(
348
- (start, i), end - start + 1, 0.8,
349
- linewidth=2, edgecolor='black',
350
- facecolor=colors[i % 20], alpha=alpha
351
- )
352
- ax1.add_patch(rect)
353
-
354
- ax1.text(start + (end - start) / 2, i + 0.4, word,
355
- ha='center', va='center', fontsize=11,
356
- fontweight='bold', color='white',
357
- bbox=dict(boxstyle='round,pad=0.3', facecolor='black', alpha=0.5))
358
-
359
- peak = word_info['peak_frame']
360
- ax1.plot(peak, i + 0.4, 'r*', markersize=15, markeredgecolor='yellow',
361
- markeredgewidth=1.5)
362
-
363
- ax1.set_xlim(-2, latent_xlim_end)
364
- ax1.set_ylim(-0.5, len(self.words))
365
- ax1.set_xlabel('')
366
- ax1.set_ylabel('')
367
- ax1.set_title('Word-to-Frame Alignment\n(based on attention peaks, ★ = peak frame)',
368
- fontsize=15, pad=15, fontweight='bold')
369
- ax1.grid(True, alpha=0.3, axis='x', linestyle='--')
370
- ax1.set_yticks(range(len(self.words)))
371
- ax1.set_yticklabels([w['word'] for w in self.word_frame_ranges], fontsize=10)
372
-
373
- # === Middle plot: latent timeline ===
374
- ax2 = fig.add_subplot(gs[1])
375
- ax2.barh(0, self.video_frames, height=0.6, color='lightgray',
376
- edgecolor='black', linewidth=2)
377
- for i, word_info in enumerate(self.word_frame_ranges):
378
- start = word_info['start_frame']
379
- end = word_info['end_frame']
380
- confidence = word_info['confidence']
381
- alpha = 0.9 if confidence == 'high' else 0.7 if confidence == 'medium' else 0.5
382
- ax2.barh(0, end - start + 1, left=start, height=0.6,
383
- color=colors[i % 20], alpha=alpha, edgecolor='black', linewidth=0.5)
384
-
385
- ax2.set_xlim(-2, latent_xlim_end)
386
- ax2.set_ylim(-0.4, 0.4)
387
- ax2.set_xlabel('')
388
- ax2.set_yticks([0])
389
- ax2.set_yticklabels(['Latent Space'], fontsize=11, fontweight='bold')
390
- ax2.tick_params(axis='y', length=0)
391
- ax2.set_title('Latent Feature Timeline', fontsize=13, fontweight='bold')
392
- ax2.grid(True, alpha=0.3, axis='x', linestyle='--')
393
-
394
- if self.frame_attention_strength is not None and len(self.frame_attention_strength) >= self.video_frames:
395
- latent_curve_x = np.arange(self.video_frames)
396
- latent_curve_y = self.frame_attention_strength[:self.video_frames] * 0.6 - 0.3
397
- ax2.plot(latent_curve_x, latent_curve_y, color='#E53935', linewidth=1.5, alpha=0.9)
398
-
399
- timeline_axes = [ax2]
400
-
401
- if feature_mapping:
402
- ax3 = fig.add_subplot(gs[2])
403
- ax3.barh(0, original_frame_count, height=0.6, color='lightgray',
404
- edgecolor='black', linewidth=2)
405
-
406
- for i, word_info in enumerate(self.word_frame_ranges):
407
- feat_start = word_info['start_frame']
408
- feat_end = word_info['end_frame']
409
- confidence = word_info['confidence']
410
- alpha = 0.9 if confidence == 'high' else 0.7 if confidence == 'medium' else 0.5
411
- if mapping_list and feat_start < len(mapping_list) and feat_end < len(mapping_list):
412
- orig_start = mapping_list[feat_start]['frame_start']
413
- orig_end = mapping_list[feat_end]['frame_end']
414
- ax3.barh(0, orig_end - orig_start, left=orig_start, height=0.6,
415
- color=colors[i % 20], alpha=alpha, edgecolor='black', linewidth=0.5)
416
-
417
- ax3_xlim = orig_xlim_end if orig_xlim_end is not None else original_frame_count + 2
418
- ax3.set_xlim(-2, ax3_xlim)
419
- ax3.set_ylim(-0.4, 0.4)
420
- ax3.set_xlabel('')
421
- ax3.set_yticks([0])
422
- ax3.set_yticklabels(['Pixel Space'], fontsize=11, fontweight='bold')
423
- ax3.tick_params(axis='y', length=0)
424
- ax3.set_title(f'Original Video Timeline ({original_frame_count} frames, '
425
- f'{feature_mapping["downsampling_ratio"]:.2f}x downsampling)',
426
- fontsize=13, fontweight='bold')
427
- ax3.grid(True, alpha=0.3, axis='x', linestyle='--')
428
-
429
- if pixel_strength_curve is not None and len(pixel_strength_curve) >= original_frame_count:
430
- pixel_curve_x = np.arange(original_frame_count)
431
- pixel_curve_y = pixel_strength_curve[:original_frame_count] * 0.6 - 0.3
432
- ax3.plot(pixel_curve_x, pixel_curve_y, color='#E53935', linewidth=1.5, alpha=0.9)
433
- timeline_axes.append(ax3)
434
-
435
- plt.tight_layout()
436
- fig.canvas.draw()
437
-
438
- ax1_pos = ax1.get_position()
439
- renderer = fig.canvas.get_renderer()
440
- ytick_extents = [tick.get_window_extent(renderer) for tick in ax1.get_yticklabels() if tick.get_text()]
441
- fig_width_px = fig.get_size_inches()[0] * fig.dpi
442
- if ytick_extents:
443
- min_x_px = min(ext.x0 for ext in ytick_extents)
444
- else:
445
- min_x_px = ax1_pos.x0 * fig_width_px
446
- line_x = max(0.01, (min_x_px / fig_width_px) - 0.01)
447
- gw_center = 0.5 * (ax1_pos.y0 + ax1_pos.y1)
448
- timeline_bounds = [ax.get_position() for ax in timeline_axes]
449
- timeline_center = 0.5 * (min(pos.y0 for pos in timeline_bounds) + max(pos.y1 for pos in timeline_bounds))
450
- fig.text(line_x, gw_center, 'Generated Word', rotation='vertical',
451
- ha='right', va='center', fontsize=12, fontweight='bold')
452
- fig.text(line_x, timeline_center, 'Timeline', rotation='vertical',
453
- ha='right', va='center', fontsize=12, fontweight='bold')
454
-
455
- png_path = Path(out_path)
456
- plt.savefig(str(png_path), dpi=150, bbox_inches='tight')
457
- pdf_path = png_path.with_suffix('.pdf')
458
- plt.savefig(str(pdf_path), format='pdf', bbox_inches='tight')
459
- plt.close()
460
-
461
- print(f" ✓ {png_path.name} (PDF copy saved)")
462
-
463
- render_alignment(output_path, latent_full_limit, orig_full_limit)
464
-
465
- if latent_short_limit < latent_full_limit - 1e-6:
466
- short_path = output_path.with_name("frame_alignment_short.png")
467
- render_alignment(short_path, latent_short_limit, orig_short_limit if orig_short_limit else orig_full_limit)
468
-
469
- def save_alignment_data(self, output_path):
470
- """Persist frame-alignment metadata to JSON."""
471
- data = {
472
- 'translation': self.translation,
473
- 'words': self.words,
474
- 'total_video_frames': self.video_frames,
475
- 'frame_ranges': self.word_frame_ranges,
476
- 'statistics': {
477
- 'avg_confidence': np.mean([w['avg_attention'] for w in self.word_frame_ranges]),
478
- 'high_confidence_words': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'high'),
479
- 'medium_confidence_words': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'medium'),
480
- 'low_confidence_words': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'low'),
481
- }
482
- }
483
-
484
- with open(output_path, 'w', encoding='utf-8') as f:
485
- json.dump(data, f, indent=2, ensure_ascii=False)
486
-
487
- print(f" ✓ {output_path.name}")
488
-
489
- def save_text_report(self, output_path):
490
- """Write a plain-text report (used for analysis_report.txt)."""
491
- with open(output_path, 'w', encoding='utf-8') as f:
492
- f.write("=" * 80 + "\n")
493
- f.write(" Sign Language Recognition - Attention Analysis Report\n")
494
- f.write("=" * 80 + "\n\n")
495
-
496
- f.write(f"Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
497
-
498
- f.write("Translation:\n")
499
- f.write("-" * 80 + "\n")
500
- f.write(f"{self.translation}\n\n")
501
-
502
- f.write("Video info:\n")
503
- f.write("-" * 80 + "\n")
504
- f.write(f"Total feature frames: {self.video_frames}\n")
505
- f.write(f"Word count: {len(self.words)}\n\n")
506
-
507
- f.write("Attention tensor:\n")
508
- f.write("-" * 80 + "\n")
509
- f.write(f"Shape: {self.attentions.shape}\n")
510
- f.write(f" - Decoder steps: {self.attentions.shape[0]}\n")
511
- if len(self.attentions.shape) >= 3:
512
- f.write(f" - Batch size: {self.attentions.shape[1]}\n")
513
- if len(self.attentions.shape) >= 4:
514
- f.write(f" - Beam size: {self.attentions.shape[2]}\n")
515
- f.write(f" - Source length: {self.attentions.shape[3]}\n")
516
- f.write("\n")
517
-
518
- f.write("Word-to-frame details:\n")
519
- f.write("=" * 80 + "\n")
520
- f.write(f"{'No.':<5} {'Word':<20} {'Frames':<15} {'Peak':<8} {'Attn':<8} {'Conf':<10}\n")
521
- f.write("-" * 80 + "\n")
522
-
523
- for i, w in enumerate(self.word_frame_ranges):
524
- frame_range = f"{w['start_frame']}-{w['end_frame']}"
525
- f.write(f"{i+1:<5} {w['word']:<20} {frame_range:<15} "
526
- f"{w['peak_frame']:<8} {w['avg_attention']:<8.3f} {w['confidence']:<10}\n")
527
-
528
- f.write("\n" + "=" * 80 + "\n")
529
-
530
- # Summary
531
- stats = {
532
- 'avg_confidence': np.mean([w['avg_attention'] for w in self.word_frame_ranges]),
533
- 'high': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'high'),
534
- 'medium': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'medium'),
535
- 'low': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'low'),
536
- }
537
-
538
- f.write("\nSummary:\n")
539
- f.write("-" * 80 + "\n")
540
- f.write(f"Average attention weight: {stats['avg_confidence']:.3f}\n")
541
- f.write(f"High-confidence words: {stats['high']} ({stats['high']/len(self.words)*100:.1f}%)\n")
542
- f.write(f"Medium-confidence words: {stats['medium']} ({stats['medium']/len(self.words)*100:.1f}%)\n")
543
- f.write(f"Low-confidence words: {stats['low']} ({stats['low']/len(self.words)*100:.1f}%)\n")
544
- f.write("\n" + "=" * 80 + "\n")
545
-
546
- print(f" ✓ {output_path.name}")
547
-
548
-
549
- def _map_feature_frame_to_original(self, feature_frame_idx):
550
- """
551
- Map a SMKD feature frame index back to the original video frame index.
552
-
553
- Args:
554
- feature_frame_idx: Zero-based feature frame index
555
-
556
- Returns:
557
- int: Original frame index, or None if unavailable.
558
- """
559
- if self.original_video_total_frames is None:
560
- return None
561
-
562
- # Approximate downsampling ratio between latent frames and original frames
563
- downsample_ratio = self.original_video_total_frames / self.video_frames
564
-
565
- # Map latent index to original frame index
566
- original_frame_idx = int(feature_frame_idx * downsample_ratio)
567
-
568
- return min(original_frame_idx, self.original_video_total_frames - 1)
569
-
570
- def _extract_video_frames(self, frame_indices):
571
- """
572
- Extract the requested original video frames (best-effort).
573
-
574
- Args:
575
- frame_indices: list[int] of original frame IDs to load
576
-
577
- Returns:
578
- dict mapping frame index to numpy array (BGR).
579
- """
580
- if not self.video_path:
581
- return {}
582
-
583
- cv2 = self._get_cv2_module()
584
- if cv2 is not None:
585
- return self._extract_frames_with_cv2(cv2, frame_indices)
586
-
587
- return self._extract_frames_with_ffmpeg(frame_indices)
588
-
589
- def _get_cv2_module(self):
590
- """Lazy-load cv2 and cache the import outcome."""
591
- if self._cv2_checked:
592
- return self._cv2_module
593
-
594
- try:
595
- import cv2
596
- self._cv2_module = cv2
597
- except ImportError:
598
- self._cv2_module = None
599
- finally:
600
- self._cv2_checked = True
601
-
602
- if self._cv2_module is None:
603
- print("Warning: opencv-python is missing; falling back to ffmpeg grabs")
604
- return self._cv2_module
605
-
606
- def _extract_frames_with_cv2(self, cv2, frame_indices):
607
- """Extract frames via OpenCV if available."""
608
- frames = {}
609
- cap = cv2.VideoCapture(self.video_path)
610
-
611
- if not cap.isOpened():
612
- print(f"Warning: Cannot open video file: {self.video_path}")
613
- return {}
614
-
615
- for frame_idx in sorted(frame_indices):
616
- cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
617
- ret, frame = cap.read()
618
- if ret:
619
- frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
620
- frames[frame_idx] = frame_rgb
621
-
622
- cap.release()
623
- return frames
624
-
625
- def _extract_frames_with_ffmpeg(self, frame_indices):
626
- """Extract frames via ffmpeg + Pillow (OpenCV fallback)."""
627
- if shutil.which("ffmpeg") is None:
628
- print("Warning: ffmpeg not found; cannot extract frames")
629
- return {}
630
-
631
- try:
632
- from PIL import Image
633
- except ImportError:
634
- print("Warning: Pillow not installed; cannot decode ffmpeg output")
635
- return {}
636
-
637
- frames = {}
638
- for frame_idx in sorted(frame_indices):
639
- cmd = [
640
- "ffmpeg",
641
- "-v", "error",
642
- "-i", str(self.video_path),
643
- "-vf", f"select=eq(n\\,{frame_idx})",
644
- "-vframes", "1",
645
- "-f", "image2pipe",
646
- "-vcodec", "png",
647
- "-"
648
- ]
649
- try:
650
- result = subprocess.run(
651
- cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
652
- )
653
- if not result.stdout:
654
- continue
655
- image = Image.open(io.BytesIO(result.stdout)).convert("RGB")
656
- frames[frame_idx] = np.array(image)
657
- except subprocess.CalledProcessError as e:
658
- print(f"Warning: ffmpeg failed to extract frame {frame_idx}: {e}")
659
- except Exception as ex:
660
- print(f"Warning: failed to decode frame {frame_idx}: {ex}")
661
-
662
- if frames:
663
- print(f" ✓ Extracted {len(frames)} frame(s) via ffmpeg")
664
- else:
665
- print(" ⓘ ffmpeg did not return any frames")
666
- return frames
667
-
668
- def generate_gloss_to_frames_visualization(self, output_path):
669
- """
670
- Create the gloss-to-frames visualization:
671
- Column 1: gloss text
672
- Column 2: relative time + frame indices
673
- Column 3: representative video thumbnails
674
- """
675
- if not self.video_path:
676
- print(" ⓘ Skipping gloss-to-frames visualization (no video path provided)")
677
- return
678
-
679
- try:
680
- import matplotlib.pyplot as plt
681
- import matplotlib.gridspec as gridspec
682
- except ImportError:
683
- print("Warning: matplotlib not installed")
684
- return
685
-
686
- # Load feature-to-frame mapping if available
687
- feature_mapping = None
688
- output_dir = Path(output_path).parent
689
- mapping_file = output_dir / "feature_frame_mapping.json"
690
- if mapping_file.exists():
691
- try:
692
- with open(mapping_file, 'r') as f:
693
- mapping_data = json.load(f)
694
- feature_mapping = mapping_data['mapping']
695
- except Exception as e:
696
- print(f" Warning: Failed to load feature mapping: {e}")
697
-
698
- # Collect every original frame we need to grab
699
- all_original_frames = set()
700
- for word_info in self.word_frame_ranges:
701
- # Feature frame range
702
- start_feat = word_info['start_frame']
703
- end_feat = word_info['end_frame']
704
-
705
- # Map the feature range onto original video frames
706
- if feature_mapping:
707
- # Use the precomputed mapping data
708
- for feat_idx in range(start_feat, end_feat + 1):
709
- if feat_idx < len(feature_mapping):
710
- # Pull every original frame for that feature segment
711
- feat_info = feature_mapping[feat_idx]
712
- for orig_idx in range(feat_info['frame_start'], feat_info['frame_end']):
713
- all_original_frames.add(orig_idx)
714
- else:
715
- # Fallback: assume uniform downsampling
716
- for feat_idx in range(start_feat, end_feat + 1):
717
- orig_idx = self._map_feature_frame_to_original(feat_idx)
718
- if orig_idx is not None:
719
- all_original_frames.add(orig_idx)
720
-
721
- # Extract the necessary frames
722
- print(f" Extracting {len(all_original_frames)} original video frame(s)...")
723
- video_frames_dict = self._extract_video_frames(list(all_original_frames))
724
-
725
- if not video_frames_dict:
726
- print(" ⓘ No video frames extracted, skipping visualization")
727
- return
728
-
729
- # Create figure (4 columns: Gloss | Feature Index | Peak Frame | Full Span)
730
- n_words = len(self.words)
731
- fig = plt.figure(figsize=(28, 3 * n_words))
732
- gs = gridspec.GridSpec(n_words, 4, width_ratios=[1.5, 1.5, 2.5, 8], hspace=0.3, wspace=0.2)
733
-
734
- for row_idx, (word, word_info) in enumerate(zip(self.words, self.word_frame_ranges)):
735
- # Column 1: Gloss label
736
- ax_gloss = fig.add_subplot(gs[row_idx, 0])
737
- ax_gloss.text(0.5, 0.5, word, fontsize=24, weight='bold',
738
- ha='center', va='center', wrap=True)
739
- ax_gloss.axis('off')
740
-
741
- # Column 2: Feature index info
742
- ax_feature = fig.add_subplot(gs[row_idx, 1])
743
-
744
- # Feature frame details
745
- feat_start = word_info['start_frame']
746
- feat_end = word_info['end_frame']
747
- feat_peak = word_info['peak_frame']
748
-
749
- feature_text = f"SMKD Feature Index\n"
750
- feature_text += f"{'='*20}\n\n"
751
- feature_text += f"Range:\n {feat_start} → {feat_end}\n\n"
752
- feature_text += f"Peak:\n {feat_peak}\n\n"
753
- feature_text += f"Count:\n {feat_end - feat_start + 1} features"
754
-
755
- ax_feature.text(0.5, 0.5, feature_text, fontsize=11, family='monospace',
756
- va='center', ha='center',
757
- bbox=dict(boxstyle='round,pad=0.8', facecolor='lightblue',
758
- edgecolor='darkblue', linewidth=2, alpha=0.7))
759
- ax_feature.axis('off')
760
-
761
- # Column 3: Original frames for the peak feature
762
- ax_peak_frames = fig.add_subplot(gs[row_idx, 2])
763
-
764
- peak_frames_to_show = []
765
- orig_peak_start, orig_peak_end = None, None
766
- if feature_mapping and feat_peak is not None and feat_peak < len(feature_mapping):
767
- # Use detailed mapping to determine the original frame span
768
- peak_info = feature_mapping[feat_peak]
769
- orig_peak_start = peak_info['frame_start']
770
- orig_peak_end = peak_info['frame_end']
771
-
772
- # Show each original frame linked to the peak feature range
773
- for orig_idx in range(orig_peak_start, orig_peak_end):
774
- if orig_idx in video_frames_dict:
775
- peak_frames_to_show.append(video_frames_dict[orig_idx])
776
-
777
- if peak_frames_to_show:
778
- # Horizontally stitch frames
779
- combined_peak = np.hstack(peak_frames_to_show)
780
- ax_peak_frames.imshow(combined_peak)
781
-
782
- # Add caption
783
- ax_peak_frames.text(0.5, -0.05, f"Peak Feature {feat_peak}\nFrames {orig_peak_start}-{orig_peak_end-1} ({len(peak_frames_to_show)} frames)",
784
- ha='center', va='top', transform=ax_peak_frames.transAxes,
785
- fontsize=10, weight='bold', color='red',
786
- bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7))
787
- else:
788
- ax_peak_frames.text(0.5, 0.5, "No peak frames",
789
- ha='center', va='center', transform=ax_peak_frames.transAxes)
790
-
791
- ax_peak_frames.axis('off')
792
-
793
- # Column 4: All frames covered by the gloss span
794
- ax_all_frames = fig.add_subplot(gs[row_idx, 3])
795
-
796
- all_frames_to_show = []
797
- orig_start, orig_end = None, None
798
- if feature_mapping:
799
- # Determine range via mapping
800
- if feat_start < len(feature_mapping) and feat_end < len(feature_mapping):
801
- orig_start = feature_mapping[feat_start]['frame_start']
802
- orig_end = feature_mapping[feat_end]['frame_end']
803
-
804
- # Collect every frame in the span
805
- for orig_idx in range(orig_start, orig_end):
806
- if orig_idx in video_frames_dict:
807
- all_frames_to_show.append(video_frames_dict[orig_idx])
808
-
809
- if all_frames_to_show:
810
- # Stitch all frames horizontally
811
- combined_all = np.hstack(all_frames_to_show)
812
- ax_all_frames.imshow(combined_all)
813
-
814
- # Add caption showing total
815
- frame_count = len(all_frames_to_show)
816
- ax_all_frames.text(0.5, -0.05, f"All Frames ({frame_count} frames)\nRange: {orig_start}-{orig_end-1}",
817
- ha='center', va='top', transform=ax_all_frames.transAxes,
818
- fontsize=10, weight='bold', color='blue',
819
- bbox=dict(boxstyle='round,pad=0.3', facecolor='lightblue', alpha=0.7))
820
- else:
821
- ax_all_frames.text(0.5, 0.5, "No frames available",
822
- ha='center', va='center', transform=ax_all_frames.transAxes)
823
-
824
- ax_all_frames.axis('off')
825
-
826
- plt.suptitle(f"Three-Layer Alignment: Gloss ↔ Feature Index ↔ Original Frames\nTranslation: {self.translation}",
827
- fontsize=16, weight='bold', y=0.995)
828
-
829
- plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white')
830
- plt.close()
831
-
832
- print(f" ✓ {Path(output_path).name}")
833
-
834
- def _read_video_metadata(self):
835
- """Attempt to read the original video's frame count and FPS."""
836
- metadata = self._read_metadata_with_cv2()
837
- if metadata:
838
- return metadata
839
- return self._read_metadata_with_ffprobe()
840
-
841
- def _read_metadata_with_cv2(self):
842
- cv2 = self._get_cv2_module()
843
- if cv2 is None:
844
- return None
845
-
846
- cap = cv2.VideoCapture(self.video_path)
847
- if not cap.isOpened():
848
- return None
849
-
850
- total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
851
- fps = cap.get(cv2.CAP_PROP_FPS)
852
- cap.release()
853
-
854
- if total_frames <= 0:
855
- return None
856
-
857
- return {'frames': total_frames, 'fps': fps or self.original_video_fps}
858
-
859
- def _read_metadata_with_ffprobe(self):
860
- if shutil.which("ffprobe") is None:
861
- return None
862
-
863
- cmd = [
864
- "ffprobe",
865
- "-v", "error",
866
- "-select_streams", "v:0",
867
- "-show_entries", "stream=nb_frames,r_frame_rate,avg_frame_rate,duration",
868
- "-of", "json",
869
- str(self.video_path)
870
- ]
871
-
872
- try:
873
- result = subprocess.run(
874
- cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
875
- )
876
- except subprocess.CalledProcessError:
877
- return None
878
-
879
- try:
880
- info = json.loads(result.stdout)
881
- except json.JSONDecodeError:
882
- return None
883
-
884
- streams = info.get("streams") or []
885
- if not streams:
886
- return None
887
-
888
- stream = streams[0]
889
- total_frames = stream.get("nb_frames")
890
- fps = stream.get("avg_frame_rate") or stream.get("r_frame_rate")
891
- duration = stream.get("duration")
892
-
893
- fps_value = self._parse_ffprobe_fps(fps)
894
- total_frames_value = None
895
-
896
- if isinstance(total_frames, str) and total_frames.isdigit():
897
- total_frames_value = int(total_frames)
898
-
899
- if total_frames_value is None and duration and fps_value:
900
- try:
901
- total_frames_value = int(round(float(duration) * fps_value))
902
- except ValueError:
903
- total_frames_value = None
904
-
905
- if total_frames_value is None:
906
- return None
907
-
908
- return {'frames': total_frames_value, 'fps': fps_value or self.original_video_fps}
909
-
910
- @staticmethod
911
- def _parse_ffprobe_fps(rate_str):
912
- """Parse an ffprobe frame-rate string such as '30000/1001'."""
913
- if not rate_str or rate_str in ("0/0", "0"):
914
- return None
915
-
916
- if "/" in rate_str:
917
- num, denom = rate_str.split("/", 1)
918
- try:
919
- num = float(num)
920
- denom = float(denom)
921
- if denom == 0:
922
- return None
923
- return num / denom
924
- except ValueError:
925
- return None
926
-
927
- try:
928
- return float(rate_str)
929
- except ValueError:
930
- return None
931
-
932
-
933
- def analyze_from_numpy_file(attention_file, translation, video_frames, output_dir):
934
- """
935
- Load attention weights from a .npy file and generate visualization assets.
936
-
937
- Args:
938
- attention_file: Path to the numpy file
939
- translation: Clean translation string
940
- video_frames: Number of SMKD feature frames
941
- output_dir: Destination directory for outputs
942
- """
943
- attentions = np.load(attention_file)
944
- analyzer = AttentionAnalyzer(attentions, translation, video_frames)
945
- analyzer.generate_all_visualizations(output_dir)
946
- return analyzer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/benchmark_smkd.sh DELETED
@@ -1,141 +0,0 @@
1
- #!/bin/bash
2
- # 测试 SMKD 视频特征提取的效率 (包含 pose 协助)
3
- set -e
4
-
5
- GREEN='\033[0;32m'
6
- BLUE='\033[0;34m'
7
- NC='\033[0m'
8
-
9
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
10
- PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
11
-
12
- echo ""
13
- echo "======================================================================"
14
- echo " SMKD Feature Extraction Benchmark (with Pose Assistance)"
15
- echo "======================================================================"
16
- echo ""
17
-
18
- # 激活conda
19
- CONDA_BASE=$(conda info --base 2>/dev/null || echo "")
20
- source "${CONDA_BASE}/etc/profile.d/conda.sh"
21
-
22
- # 切换到 PyTorch 环境
23
- conda activate signx-slt
24
-
25
- if [ $? -ne 0 ]; then
26
- echo "错误: 无法激活 signx-slt 环境"
27
- exit 1
28
- fi
29
-
30
- # 使用测试集视频进行基准测试
31
- TEST_VIDEO_DIR="${PROJECT_ROOT}/eval/tiny_test_data/videos"
32
-
33
- if [ ! -d "$TEST_VIDEO_DIR" ]; then
34
- echo "错误: 测试视频目录不存在: $TEST_VIDEO_DIR"
35
- exit 1
36
- fi
37
-
38
- # 获取所有测试视频
39
- TEST_VIDEOS=($(ls ${TEST_VIDEO_DIR}/*.mp4 2>/dev/null | head -10))
40
- NUM_VIDEOS=${#TEST_VIDEOS[@]}
41
-
42
- if [ $NUM_VIDEOS -eq 0 ]; then
43
- echo "错误: 未找到测试视频"
44
- exit 1
45
- fi
46
-
47
- echo "找到 $NUM_VIDEOS 个测试视频"
48
- echo ""
49
-
50
- # 创建临时视频列表文件
51
- TEMP_DIR=$(mktemp -d)
52
- VIDEO_LIST_FILE="$TEMP_DIR/video_list.txt"
53
-
54
- for video in "${TEST_VIDEOS[@]}"; do
55
- echo "$video" >> "$VIDEO_LIST_FILE"
56
- done
57
-
58
- FEATURE_OUTPUT="$TEMP_DIR/features.h5"
59
-
60
- # 配置文件(使用禁用 pose assistance 的配置)
61
- SMKD_CONFIG="${PROJECT_ROOT}/smkd/asllrp_baseline_benchmark.yaml"
62
- SMKD_MODEL="${PROJECT_ROOT}/smkd/work_dir第一次训练的基线/asllrp_smkd/best_model.pt"
63
- GLOSS_DICT="${PROJECT_ROOT}/smkd/asllrp/gloss_dict.npy"
64
-
65
- cd "$PROJECT_ROOT"
66
-
67
- echo -e "${BLUE}开始 SMKD 特征提取基准测试...${NC}"
68
- echo ""
69
-
70
- # 记录GPU功耗(后台进程)
71
- nvidia-smi --query-gpu=power.draw --format=csv,noheader,nounits -l 1 > /tmp/power_smkd.log &
72
- POWER_PID=$!
73
-
74
- # 测量特征提取时间
75
- START=$(date +%s.%N)
76
-
77
- python -c "
78
- import sys
79
- import os
80
- sys.path.insert(0, 'smkd')
81
-
82
- from smkd.sign_embedder import SignEmbedding
83
- import h5py
84
- import numpy as np
85
-
86
- print(' 加载 SMKD 模型...')
87
- embedder = SignEmbedding(
88
- cfg='$SMKD_CONFIG',
89
- gloss_path='$GLOSS_DICT',
90
- sign_video_path='$VIDEO_LIST_FILE',
91
- model_path='$SMKD_MODEL',
92
- gpu_id='0',
93
- batch_size=1
94
- )
95
-
96
- print(' 提取特征...')
97
- features = embedder.embed()
98
-
99
- print(' 保存特征到 h5 文件...')
100
- with h5py.File('$FEATURE_OUTPUT', 'w') as hf:
101
- for key, feature in features.items():
102
- hf.create_dataset(key, data=feature)
103
-
104
- print(' ✓ 特征提取完成')
105
- print(' 特征数量:', len(features))
106
- "
107
-
108
- END=$(date +%s.%N)
109
-
110
- # 停止功耗监控
111
- kill $POWER_PID 2>/dev/null || true
112
-
113
- # 计算结果
114
- SMKD_TIME=$(echo "$END - $START" | bc)
115
- SMKD_POWER=$(awk '{ sum += $1; n++ } END { if (n > 0) print sum / n }' /tmp/power_smkd.log)
116
- SMKD_FPS=$(echo "scale=2; $NUM_VIDEOS / $SMKD_TIME" | bc)
117
-
118
- echo ""
119
- echo -e "${GREEN}✓ SMKD 特征提取完成${NC}"
120
- echo " 处理视频数: $NUM_VIDEOS"
121
- echo " 总时间: ${SMKD_TIME}s"
122
- echo " 平均功耗: ${SMKD_POWER}W"
123
- echo " FPS: $SMKD_FPS"
124
- echo ""
125
-
126
- # 清理
127
- rm -rf "$TEMP_DIR"
128
- rm -f /tmp/power_smkd.log
129
-
130
- echo "======================================================================"
131
- echo " SMKD Benchmark Results"
132
- echo "======================================================================"
133
- echo ""
134
- echo "Configuration: SMKD (视频→特征, 包含 Pose 协助)"
135
- echo "Videos: $NUM_VIDEOS"
136
- echo "Time: ${SMKD_TIME}s"
137
- echo "FPS: $SMKD_FPS"
138
- echo "Power: ${SMKD_POWER}W"
139
- echo ""
140
- echo -e "${GREEN}✓ Benchmark complete!${NC}"
141
- echo ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/extract_attention_keyframes.py DELETED
@@ -1,198 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Extract peak-feature keyframes and overlay attention heatmaps on the video frames.
4
- """
5
-
6
- import os
7
- import sys
8
- import cv2
9
- import numpy as np
10
- import json
11
- from pathlib import Path
12
- import matplotlib.pyplot as plt
13
- from matplotlib import cm
14
-
15
- def apply_attention_heatmap(frame, attention_weight, alpha=0.5):
16
- """
17
- Overlay a synthetic attention heatmap on top of a video frame.
18
-
19
- Args:
20
- frame: Original frame (H, W, 3)
21
- attention_weight: Scalar attention weight in [0, 1]
22
- alpha: Heatmap opacity
23
-
24
- Returns:
25
- Frame with the attention heatmap blended in.
26
- """
27
- h, w = frame.shape[:2]
28
-
29
- # Create a simple center-weighted Gaussian heatmap
30
- y, x = np.ogrid[:h, :w]
31
- center_y, center_x = h // 2, w // 2
32
-
33
- # High attention weight = tighter Gaussian
34
- sigma = min(h, w) / 3 * (1.5 - attention_weight)
35
- gaussian = np.exp(-((x - center_x)**2 + (y - center_y)**2) / (2 * sigma**2))
36
-
37
- # Normalize to [0, 1]
38
- gaussian = (gaussian - gaussian.min()) / (gaussian.max() - gaussian.min() + 1e-8)
39
-
40
- # Apply the attention weight
41
- heatmap = gaussian * attention_weight
42
-
43
- colormap = cm.get_cmap('jet')
44
- heatmap_colored = colormap(heatmap)[:, :, :3] * 255
45
- heatmap_colored = heatmap_colored.astype(np.uint8)
46
-
47
- result = cv2.addWeighted(frame, 1-alpha, heatmap_colored, alpha, 0)
48
-
49
- return result
50
-
51
-
52
- def extract_keyframes_with_attention(sample_dir, video_path):
53
- """
54
- Extract peak-feature keyframes and overlay the attention visualization.
55
-
56
- Args:
57
- sample_dir: Sample directory path (e.g., detailed_xxx/sample_0)
58
- video_path: Original video path
59
- """
60
- sample_dir = Path(sample_dir)
61
-
62
- print(f"\nProcessing sample: {sample_dir.name}")
63
-
64
- # 检查必要文件
65
- mapping_file = sample_dir / "feature_frame_mapping.json"
66
- weights_file = sample_dir / "attention_weights.npy"
67
-
68
- if not mapping_file.exists():
69
- print(f" ⚠ Mapping file not found: {mapping_file}")
70
- return
71
-
72
- if not weights_file.exists():
73
- print(f" ⚠ Attention weights missing: {weights_file}")
74
- return
75
-
76
- if not os.path.exists(video_path):
77
- print(f" ⚠ Video file not found: {video_path}")
78
- return
79
-
80
- # 加载映射和注意力权重
81
- with open(mapping_file, 'r') as f:
82
- mapping_data = json.load(f)
83
-
84
- attention_weights = np.load(weights_file)
85
-
86
- # Create output directory
87
- keyframes_dir = sample_dir / "attention_keyframes"
88
- keyframes_dir.mkdir(exist_ok=True)
89
-
90
- print(f" Feature count: {mapping_data['feature_count']}")
91
- print(f" Original frame count: {mapping_data['original_frame_count']}")
92
- print(f" Attention weight shape: {attention_weights.shape}")
93
-
94
- # 打开视频
95
- cap = cv2.VideoCapture(video_path)
96
- if not cap.isOpened():
97
- print(f" ✗ Failed to open video: {video_path}")
98
- return
99
-
100
- total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
101
- print(f" Total video frames: {total_frames}")
102
-
103
- # 构建特征索引到帧的映射(使用中间帧)
104
- feature_to_frame = {}
105
- for item in mapping_data['mapping']:
106
- feature_idx = item['feature_index']
107
- frame_start = item['frame_start']
108
- frame_end = item['frame_end']
109
- mid_frame = (frame_start + frame_end) // 2
110
- feature_to_frame[feature_idx] = mid_frame
111
-
112
- num_glosses = attention_weights.shape[0] if len(attention_weights.shape) > 1 else 0
113
-
114
- if num_glosses == 0:
115
- print(" ⚠ Invalid attention weight dimensions")
116
- cap.release()
117
- return
118
-
119
- saved_count = 0
120
-
121
- for gloss_idx in range(num_glosses):
122
- gloss_attention = attention_weights[gloss_idx] # shape: (num_features,)
123
-
124
- peak_feature_idx = np.argmax(gloss_attention)
125
- peak_attention = gloss_attention[peak_feature_idx]
126
-
127
- if peak_feature_idx not in feature_to_frame:
128
- print(f" ⚠ Gloss {gloss_idx}: feature {peak_feature_idx} missing frame mapping")
129
- continue
130
-
131
- frame_idx = feature_to_frame[peak_feature_idx]
132
-
133
- cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
134
- ret, frame = cap.read()
135
-
136
- if not ret:
137
- print(f" ⚠ Gloss {gloss_idx}: unable to read frame {frame_idx}")
138
- continue
139
-
140
- frame_with_attention = apply_attention_heatmap(frame, peak_attention, alpha=0.4)
141
-
142
- text = f"Gloss {gloss_idx} | Feature {peak_feature_idx} | Frame {frame_idx}"
143
- attention_text = f"Attention: {peak_attention:.3f}"
144
-
145
- cv2.rectangle(frame_with_attention, (0, 0), (frame.shape[1], 60), (0, 0, 0), -1)
146
- cv2.putText(frame_with_attention, text, (10, 25),
147
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
148
- cv2.putText(frame_with_attention, attention_text, (10, 50),
149
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
150
-
151
- output_filename = f"keyframe_{gloss_idx:03d}_feat{peak_feature_idx}_frame{frame_idx}_att{peak_attention:.3f}.jpg"
152
- output_path = keyframes_dir / output_filename
153
-
154
- cv2.imwrite(str(output_path), frame_with_attention)
155
- saved_count += 1
156
-
157
- cap.release()
158
-
159
- print(f" ✓ Saved {saved_count} keyframes to: {keyframes_dir}")
160
-
161
- # Create index file
162
- index_file = keyframes_dir / "keyframes_index.txt"
163
- with open(index_file, 'w') as f:
164
- f.write("Attention Keyframe Index\n")
165
- f.write(f"=" * 60 + "\n\n")
166
- f.write(f"Sample directory: {sample_dir}\n")
167
- f.write(f"Video path: {video_path}\n")
168
- f.write(f"Total keyframes: {saved_count}\n\n")
169
- f.write("Keyframe list:\n")
170
- f.write(f"-" * 60 + "\n")
171
-
172
- for gloss_idx in range(num_glosses):
173
- gloss_attention = attention_weights[gloss_idx]
174
- peak_feature_idx = np.argmax(gloss_attention)
175
- peak_attention = gloss_attention[peak_feature_idx]
176
-
177
- if peak_feature_idx in feature_to_frame:
178
- frame_idx = feature_to_frame[peak_feature_idx]
179
- filename = f"keyframe_{gloss_idx:03d}_feat{peak_feature_idx}_frame{frame_idx}_att{peak_attention:.3f}.jpg"
180
- f.write(f"Gloss {gloss_idx:3d}: {filename}\n")
181
-
182
- print(f" ✓ Index file written: {index_file}")
183
-
184
-
185
- def main():
186
- if len(sys.argv) < 3:
187
- print("Usage: python extract_attention_keyframes.py <sample_dir> <video_path>")
188
- print("Example: python extract_attention_keyframes.py detailed_xxx/sample_0 video.mp4")
189
- sys.exit(1)
190
-
191
- sample_dir = sys.argv[1]
192
- video_path = sys.argv[2]
193
-
194
- extract_keyframes_with_attention(sample_dir, video_path)
195
-
196
-
197
- if __name__ == "__main__":
198
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/generate_feature_mapping.py DELETED
@@ -1,126 +0,0 @@
1
- #!/usr/bin/env python
2
- """
3
- Generate a feature-to-frame mapping file for SignX inference outputs.
4
-
5
- Usage:
6
- python generate_feature_mapping.py <sample_dir> <video_path>
7
-
8
- Example:
9
- python generate_feature_mapping.py detailed_prediction_20251226_155113/sample_000 \\
10
- eval/tiny_test_data/videos/632051.mp4
11
- """
12
-
13
- import sys
14
- import os
15
- import json
16
- import numpy as np
17
- from pathlib import Path
18
-
19
- def generate_feature_mapping(sample_dir, video_path):
20
- """Create the feature-to-frame mapping JSON for a given sample directory."""
21
- sample_dir = Path(sample_dir)
22
-
23
- # Check if attention_weights.npy exists
24
- attn_file = sample_dir / "attention_weights.npy"
25
- if not attn_file.exists():
26
- print(f"Error: missing attention_weights.npy: {attn_file}")
27
- return False
28
-
29
- # Load attention weights to get feature count
30
- attn_weights = np.load(attn_file)
31
- # Handle both 2D (time, features) and 3D (time, beam, features) shapes
32
- if attn_weights.ndim == 2:
33
- feature_count = attn_weights.shape[1] # Shape: (time, features) - inference mode
34
- elif attn_weights.ndim == 3:
35
- feature_count = attn_weights.shape[2] # Shape: (time, beam, features) - beam search
36
- else:
37
- print(f"Error: unexpected attention_weights shape: {attn_weights.shape}")
38
- return False
39
-
40
- print(f"Feature count: {feature_count}")
41
-
42
- # Get original frame count from video
43
- try:
44
- import cv2
45
- cap = cv2.VideoCapture(str(video_path))
46
- if not cap.isOpened():
47
- print(f"Error: failed to open video file: {video_path}")
48
- return False
49
-
50
- original_frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
51
- fps = cap.get(cv2.CAP_PROP_FPS)
52
- cap.release()
53
-
54
- print(f"Original frames: {original_frame_count}, FPS: {fps}")
55
-
56
- except ImportError:
57
- print("Warning: OpenCV not available, falling back to estimates")
58
- # Assume 30 fps and approximate the frame count from features
59
- original_frame_count = feature_count * 3 # default 3x downsampling
60
- fps = 30.0
61
-
62
- # Calculate uniform mapping: feature i -> frames [start, end]
63
- frame_mapping = []
64
- for feat_idx in range(feature_count):
65
- start_frame = int(feat_idx * original_frame_count / feature_count)
66
- end_frame = int((feat_idx + 1) * original_frame_count / feature_count)
67
- frame_mapping.append({
68
- "feature_index": feat_idx,
69
- "frame_start": start_frame,
70
- "frame_end": end_frame,
71
- "frame_count": end_frame - start_frame
72
- })
73
-
74
- # Save mapping
75
- mapping_data = {
76
- "original_frame_count": original_frame_count,
77
- "feature_count": feature_count,
78
- "downsampling_ratio": original_frame_count / feature_count,
79
- "fps": fps,
80
- "mapping": frame_mapping
81
- }
82
-
83
- output_file = sample_dir / "feature_frame_mapping.json"
84
- with open(output_file, 'w') as f:
85
- json.dump(mapping_data, f, indent=2)
86
-
87
- print(f"\n✓ Mapping file written: {output_file}")
88
- print(f" Original frames: {original_frame_count}")
89
- print(f" Feature count: {feature_count}")
90
- print(f" Downsampling ratio: {mapping_data['downsampling_ratio']:.2f}x")
91
-
92
- # Print sample mappings
93
- print("\nSample mappings:")
94
- for i in range(min(3, len(frame_mapping))):
95
- mapping = frame_mapping[i]
96
- print(f" Feature {mapping['feature_index']}: frames {mapping['frame_start']}-{mapping['frame_end']} "
97
- f"({mapping['frame_count']} frames)")
98
- if len(frame_mapping) > 3:
99
- print(" ...")
100
- mapping = frame_mapping[-1]
101
- print(f" Feature {mapping['feature_index']}: frames {mapping['frame_start']}-{mapping['frame_end']} "
102
- f"({mapping['frame_count']} frames)")
103
-
104
- return True
105
-
106
- if __name__ == "__main__":
107
- if len(sys.argv) != 3:
108
- print("Usage: python generate_feature_mapping.py <sample_dir> <video_path>")
109
- print("\nExample:")
110
- print(" python generate_feature_mapping.py detailed_prediction_20251226_155113/sample_000 \\")
111
- print(" eval/tiny_test_data/videos/632051.mp4")
112
- sys.exit(1)
113
-
114
- sample_dir = sys.argv[1]
115
- video_path = sys.argv[2]
116
-
117
- if not os.path.exists(sample_dir):
118
- print(f"Error: sample directory not found: {sample_dir}")
119
- sys.exit(1)
120
-
121
- if not os.path.exists(video_path):
122
- print(f"Error: video file not found: {video_path}")
123
- sys.exit(1)
124
-
125
- success = generate_feature_mapping(sample_dir, video_path)
126
- sys.exit(0 if success else 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/generate_gloss_frames.py DELETED
@@ -1,232 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- 后处理脚本:从已有的详细分析结果生成 gloss-to-frames 可视化
4
- 使用方法:
5
- python generate_gloss_frames.py <detailed_prediction_dir> <video_path>
6
-
7
- 例如:
8
- python generate_gloss_frames.py detailed_prediction_20251225_170455 ./eval/tiny_test_data/videos/666.mp4
9
- """
10
-
11
- import sys
12
- import json
13
- import numpy as np
14
- import cv2
15
- from pathlib import Path
16
- import matplotlib.pyplot as plt
17
- import matplotlib.patches as mpatches
18
- import matplotlib.font_manager as fm
19
-
20
- # 设置中文字体支持
21
- plt.rcParams['font.sans-serif'] = ['WenQuanYi Micro Hei', 'DejaVu Sans'] # Linux中文字体
22
- plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
23
-
24
- def extract_video_frames(video_path, frame_indices):
25
- """从视频中提取指定索引的帧"""
26
- cap = cv2.VideoCapture(video_path)
27
- total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
28
-
29
- frames = {}
30
- for idx in frame_indices:
31
- if idx >= total_frames:
32
- idx = total_frames - 1
33
- cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
34
- ret, frame = cap.read()
35
- if ret:
36
- # BGR to RGB
37
- frames[idx] = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
38
-
39
- cap.release()
40
- return frames, total_frames
41
-
42
- def generate_gloss_to_frames_visualization(sample_dir, video_path, output_path):
43
- """生成 gloss-to-frames 可视化"""
44
-
45
- sample_dir = Path(sample_dir)
46
-
47
- # 1. 读取对齐数据
48
- with open(sample_dir / "frame_alignment.json", 'r') as f:
49
- alignment_data = json.load(f)
50
-
51
- # 2. 读取翻译结果
52
- with open(sample_dir / "translation.txt", 'r') as f:
53
- lines = f.readlines()
54
- gloss_sequence = None
55
- for line in lines:
56
- if line.startswith('Clean:'):
57
- gloss_sequence = line.replace('Clean:', '').strip()
58
- break
59
-
60
- if not gloss_sequence:
61
- print("无法找到翻译结果")
62
- return
63
-
64
- glosses = gloss_sequence.split()
65
- print(f"Gloss序列: {glosses}")
66
-
67
- # 3. 获取视频信息
68
- cap = cv2.VideoCapture(str(video_path))
69
- total_video_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
70
- fps = cap.get(cv2.CAP_PROP_FPS)
71
- cap.release()
72
-
73
- print(f"视频总帧数: {total_video_frames}, FPS: {fps}")
74
-
75
- # 4. 从对齐数据中提取每个gloss的特征帧范围
76
- gloss_frames_info = []
77
-
78
- # 获取特征帧总数(从 attention weights 的 shape 推断)
79
- attention_weights = np.load(sample_dir / "attention_weights.npy")
80
- total_feature_frames = attention_weights.shape[1] # shape: [time, src_len, beam]
81
-
82
- # 计算映射到原始视频帧
83
- # 原始帧索引 = 特征帧索引 * (总视频帧数 / 总特征帧数)
84
- scale_factor = total_video_frames / total_feature_frames
85
-
86
- for gloss_data in alignment_data['frame_ranges']:
87
- gloss = gloss_data['word']
88
- start_feat_frame = gloss_data['start_frame']
89
- peak_feat_frame = gloss_data['peak_frame']
90
- end_feat_frame = gloss_data['end_frame']
91
-
92
- # 映射到原始视频帧
93
- start_video_frame = int(start_feat_frame * scale_factor)
94
- peak_video_frame = int(peak_feat_frame * scale_factor)
95
- end_video_frame = int(end_feat_frame * scale_factor)
96
-
97
- # 计算相对时间 (%)
98
- relative_time_start = (start_feat_frame / total_feature_frames) * 100
99
- relative_time_end = (end_feat_frame / total_feature_frames) * 100
100
-
101
- gloss_frames_info.append({
102
- 'gloss': gloss,
103
- 'feature_frames': (start_feat_frame, peak_feat_frame, end_feat_frame),
104
- 'video_frames': (start_video_frame, peak_video_frame, end_video_frame),
105
- 'relative_time': (relative_time_start, relative_time_end),
106
- 'total_feature_frames': total_feature_frames,
107
- 'confidence': gloss_data.get('confidence', 'unknown'),
108
- 'avg_attention': gloss_data.get('avg_attention', 0.0)
109
- })
110
-
111
- # 5. 提取所需的视频帧
112
- all_frame_indices = set()
113
- for info in gloss_frames_info:
114
- all_frame_indices.update(info['video_frames'])
115
-
116
- print(f"提取 {len(all_frame_indices)} 个视频帧...")
117
- video_frames, _ = extract_video_frames(str(video_path), sorted(all_frame_indices))
118
-
119
- # 6. 生成可视化
120
- num_glosses = len(gloss_frames_info)
121
- fig = plt.figure(figsize=(16, num_glosses * 2.5))
122
-
123
- for i, info in enumerate(gloss_frames_info):
124
- gloss = info['gloss']
125
- feat_start, feat_peak, feat_end = info['feature_frames']
126
- vid_start, vid_peak, vid_end = info['video_frames']
127
- rel_start, rel_end = info['relative_time']
128
- total_feat = info['total_feature_frames']
129
-
130
- # 创建3列布局:Gloss | 时间信息 | 帧图像
131
-
132
- # 列1:Gloss文本
133
- ax_text = plt.subplot(num_glosses, 3, i*3 + 1)
134
- ax_text.text(0.5, 0.5, gloss,
135
- fontsize=20, fontweight='bold',
136
- ha='center', va='center')
137
- ax_text.axis('off')
138
-
139
- # 列2:时间和帧信息
140
- ax_info = plt.subplot(num_glosses, 3, i*3 + 2)
141
- confidence = info.get('confidence', 'unknown')
142
- avg_attn = info.get('avg_attention', 0.0)
143
-
144
- # 置信度颜色
145
- conf_colors = {'high': 'green', 'medium': 'orange', 'low': 'red', 'unknown': 'gray'}
146
- conf_color = conf_colors.get(confidence, 'gray')
147
-
148
- info_text = f"""Feature idx: {feat_start} -> {feat_peak} -> {feat_end}
149
- Rel. time: {rel_start:.1f}% -> {rel_end:.1f}%
150
- Video frame: {vid_start} -> {vid_peak} -> {vid_end}
151
-
152
- Total features: {total_feat}
153
- Total frames: {total_video_frames}
154
-
155
- Confidence: {confidence.upper()}
156
- Attention: {avg_attn:.3f}"""
157
-
158
- ax_info.text(0.05, 0.5, info_text,
159
- fontsize=9, family='monospace',
160
- ha='left', va='center')
161
- # 添加置信度颜色条
162
- ax_info.add_patch(mpatches.Rectangle((0.85, 0.2), 0.1, 0.6,
163
- facecolor=conf_color, alpha=0.3))
164
- ax_info.axis('off')
165
-
166
- # 列3:视频帧(Start | Peak | End)横向拼接
167
- ax_frames = plt.subplot(num_glosses, 3, i*3 + 3)
168
-
169
- # 获取三个关键帧
170
- frames_to_show = []
171
- labels = []
172
- for idx, label in [(vid_start, 'Start'), (vid_peak, 'Peak'), (vid_end, 'End')]:
173
- if idx in video_frames:
174
- frames_to_show.append(video_frames[idx])
175
- labels.append(f"{label}\n(#{idx})")
176
-
177
- if frames_to_show:
178
- # 调整帧大小
179
- frame_height = 120
180
- resized_frames = []
181
- for frame in frames_to_show:
182
- h, w = frame.shape[:2]
183
- new_w = int(w * frame_height / h)
184
- resized = cv2.resize(frame, (new_w, frame_height))
185
- resized_frames.append(resized)
186
-
187
- # 横向拼接
188
- combined = np.hstack(resized_frames)
189
- ax_frames.imshow(combined)
190
-
191
- # 添加标签
192
- x_pos = 0
193
- for j, (frame, label) in enumerate(zip(resized_frames, labels)):
194
- w = frame.shape[1]
195
- ax_frames.text(x_pos + w//2, -10, label,
196
- ha='center', va='bottom',
197
- fontsize=9, fontweight='bold')
198
- x_pos += w
199
-
200
- ax_frames.axis('off')
201
-
202
- plt.tight_layout()
203
- plt.savefig(output_path, dpi=150, bbox_inches='tight')
204
- print(f"✓ 已生成可视化: {output_path}")
205
- plt.close()
206
-
207
- if __name__ == "__main__":
208
- if len(sys.argv) != 3:
209
- print("使用方法: python generate_gloss_frames.py <detailed_prediction_dir> <video_path>")
210
- print("例如: python generate_gloss_frames.py detailed_prediction_20251225_170455 ./eval/tiny_test_data/videos/666.mp4")
211
- sys.exit(1)
212
-
213
- detailed_dir = Path(sys.argv[1])
214
- video_path = sys.argv[2]
215
-
216
- if not detailed_dir.exists():
217
- print(f"错误: 目录不存在: {detailed_dir}")
218
- sys.exit(1)
219
-
220
- if not Path(video_path).exists():
221
- print(f"错误: 视频文件不存在: {video_path}")
222
- sys.exit(1)
223
-
224
- # 处理所有样本
225
- sample_dirs = sorted([d for d in detailed_dir.iterdir() if d.is_dir()])
226
-
227
- for sample_dir in sample_dirs:
228
- print(f"\n处理 {sample_dir.name}...")
229
- output_path = sample_dir / "gloss_to_frames.png"
230
- generate_gloss_to_frames_visualization(sample_dir, video_path, output_path)
231
-
232
- print(f"\n✓ 完成!共处理 {len(sample_dirs)} 个样本")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/generate_interactive_alignment.py DELETED
@@ -1,670 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Generate an interactive HTML visualization for the gloss-to-feature alignment.
4
- This mirrors the frame_alignment.png layout but lets viewers adjust confidence thresholds.
5
-
6
- Usage:
7
- python generate_interactive_alignment.py <sample_dir>
8
-
9
- Example:
10
- python generate_interactive_alignment.py detailed_prediction_20251226_022246/sample_000
11
- """
12
-
13
- import sys
14
- import json
15
- import numpy as np
16
- from pathlib import Path
17
-
18
- def generate_interactive_html(sample_dir, output_path):
19
- """Create the interactive alignment HTML for the given sample directory."""
20
-
21
- sample_dir = Path(sample_dir)
22
-
23
- # 1. Load attention weights
24
- attention_weights = np.load(sample_dir / "attention_weights.npy")
25
- # Handle both 2D (inference mode) and 3D (beam search) shapes
26
- if attention_weights.ndim == 2:
27
- attn_weights = attention_weights # [time_steps, src_len] - already 2D
28
- elif attention_weights.ndim == 3:
29
- attn_weights = attention_weights[:, :, 0] # [time_steps, src_len] - take beam 0
30
- else:
31
- raise ValueError(f"Unexpected attention weights shape: {attention_weights.shape}")
32
-
33
- # 2. Load translation output
34
- with open(sample_dir / "translation.txt", 'r') as f:
35
- lines = f.readlines()
36
- gloss_sequence = None
37
- for line in lines:
38
- if line.startswith('Clean:'):
39
- gloss_sequence = line.replace('Clean:', '').strip()
40
- break
41
-
42
- if not gloss_sequence:
43
- print("Error: translation text not found")
44
- return
45
-
46
- glosses = gloss_sequence.split()
47
- num_glosses = len(glosses)
48
- num_features = attn_weights.shape[1]
49
-
50
- print(f"Gloss sequence: {glosses}")
51
- print(f"Feature count: {num_features}")
52
- print(f"Attention shape: {attn_weights.shape}")
53
-
54
- # 3. Convert attention weights to JSON (only keep the num_glosses rows – ignore padding)
55
- attn_data = []
56
- for word_idx in range(min(num_glosses, attn_weights.shape[0])):
57
- weights = attn_weights[word_idx, :].tolist()
58
- attn_data.append({
59
- 'word': glosses[word_idx],
60
- 'word_idx': word_idx,
61
- 'weights': weights
62
- })
63
-
64
- # 4. Build the HTML payload
65
- html_content = f"""<!DOCTYPE html>
66
- <html lang="en">
67
- <head>
68
- <meta charset="UTF-8">
69
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
70
- <title>Interactive Word-Frame Alignment</title>
71
- <style>
72
- body {{
73
- font-family: 'Arial', sans-serif;
74
- margin: 20px;
75
- background-color: #f5f5f5;
76
- }}
77
- .container {{
78
- max-width: 1800px;
79
- margin: 0 auto;
80
- background-color: white;
81
- padding: 30px;
82
- border-radius: 8px;
83
- box-shadow: 0 2px 10px rgba(0,0,0,0.1);
84
- }}
85
- h1 {{
86
- color: #333;
87
- border-bottom: 3px solid #4CAF50;
88
- padding-bottom: 10px;
89
- margin-bottom: 20px;
90
- }}
91
- .stats {{
92
- background-color: #E3F2FD;
93
- padding: 15px;
94
- border-radius: 5px;
95
- margin-bottom: 20px;
96
- border-left: 4px solid #2196F3;
97
- font-size: 14px;
98
- }}
99
- .controls {{
100
- background-color: #f9f9f9;
101
- padding: 20px;
102
- border-radius: 5px;
103
- margin-bottom: 30px;
104
- border: 1px solid #ddd;
105
- }}
106
- .control-group {{
107
- margin-bottom: 15px;
108
- }}
109
- label {{
110
- font-weight: bold;
111
- display: inline-block;
112
- width: 250px;
113
- color: #555;
114
- }}
115
- input[type="range"] {{
116
- width: 400px;
117
- vertical-align: middle;
118
- }}
119
- .value-display {{
120
- display: inline-block;
121
- width: 80px;
122
- font-family: monospace;
123
- font-size: 14px;
124
- color: #2196F3;
125
- font-weight: bold;
126
- }}
127
- .reset-btn {{
128
- margin-top: 15px;
129
- padding: 10px 25px;
130
- background-color: #2196F3;
131
- color: white;
132
- border: none;
133
- border-radius: 5px;
134
- cursor: pointer;
135
- font-size: 14px;
136
- font-weight: bold;
137
- }}
138
- .reset-btn:hover {{
139
- background-color: #1976D2;
140
- }}
141
- canvas {{
142
- border: 1px solid #999;
143
- display: block;
144
- margin: 20px auto;
145
- background: white;
146
- }}
147
- .legend {{
148
- margin-top: 20px;
149
- padding: 15px;
150
- background-color: #fff;
151
- border: 1px solid #ddd;
152
- border-radius: 5px;
153
- }}
154
- .legend-item {{
155
- display: inline-block;
156
- margin-right: 25px;
157
- font-size: 13px;
158
- margin-bottom: 10px;
159
- }}
160
- .color-box {{
161
- display: inline-block;
162
- width: 30px;
163
- height: 15px;
164
- margin-right: 8px;
165
- vertical-align: middle;
166
- border: 1px solid #666;
167
- }}
168
- .info-panel {{
169
- margin-top: 20px;
170
- padding: 15px;
171
- background-color: #f9f9f9;
172
- border-radius: 5px;
173
- border: 1px solid #ddd;
174
- }}
175
- .confidence {{
176
- display: inline-block;
177
- padding: 3px 10px;
178
- border-radius: 10px;
179
- font-weight: bold;
180
- font-size: 11px;
181
- text-transform: uppercase;
182
- }}
183
- .confidence.high {{
184
- background-color: #4CAF50;
185
- color: white;
186
- }}
187
- .confidence.medium {{
188
- background-color: #FF9800;
189
- color: white;
190
- }}
191
- .confidence.low {{
192
- background-color: #f44336;
193
- color: white;
194
- }}
195
- </style>
196
- </head>
197
- <body>
198
- <div class="container">
199
- <h1>🎯 Interactive Word-to-Frame Alignment Visualizer</h1>
200
-
201
- <div class="stats">
202
- <strong>Translation:</strong> {' '.join(glosses)}<br>
203
- <strong>Total Words:</strong> {num_glosses} |
204
- <strong>Total Features:</strong> {num_features}
205
- </div>
206
-
207
- <div class="controls">
208
- <h3>⚙️ Threshold Controls</h3>
209
-
210
- <div class="control-group">
211
- <label for="peak-threshold">Peak Threshold (% of max):</label>
212
- <input type="range" id="peak-threshold" min="1" max="100" value="90" step="1">
213
- <span class="value-display" id="peak-threshold-value">90%</span>
214
- <br>
215
- <small style="margin-left: 255px; color: #666;">
216
- A frame is considered “significant” if its attention ≥ (peak × threshold%)
217
- </small>
218
- </div>
219
-
220
- <div class="control-group">
221
- <label for="confidence-high">High Confidence (avg attn >):</label>
222
- <input type="range" id="confidence-high" min="0" max="100" value="50" step="1">
223
- <span class="value-display" id="confidence-high-value">0.50</span>
224
- </div>
225
-
226
- <div class="control-group">
227
- <label for="confidence-medium">Medium Confidence (avg attn >):</label>
228
- <input type="range" id="confidence-medium" min="0" max="100" value="20" step="1">
229
- <span class="value-display" id="confidence-medium-value">0.20</span>
230
- </div>
231
-
232
- <button class="reset-btn" onclick="resetDefaults()">
233
- Reset to Defaults
234
- </button>
235
- </div>
236
-
237
- <div>
238
- <h3>Word-to-Frame Alignment</h3>
239
- <p style="color: #666; font-size: 13px;">
240
- Each word appears as a colored block. Width = frame span, ★ = peak frame, waveform = attention trace.
241
- </p>
242
- <canvas id="alignment-canvas" width="1600" height="600"></canvas>
243
-
244
- <h3 style="margin-top: 30px;">Timeline Progress Bar</h3>
245
- <canvas id="timeline-canvas" width="1600" height="100"></canvas>
246
-
247
- <div class="legend">
248
- <strong>Legend:</strong><br><br>
249
- <div class="legend-item">
250
- <span class="confidence high">High</span>
251
- <span class="confidence medium">Medium</span>
252
- <span class="confidence low">Low</span>
253
- Confidence Levels (opacity reflects confidence)
254
- </div>
255
- <div class="legend-item">
256
- <span style="color: red; font-size: 20px;">★</span>
257
- Peak Frame (highest attention)
258
- </div>
259
- <div class="legend-item">
260
- <span style="color: blue;">━</span>
261
- Attention Waveform (within word region)
262
- </div>
263
- </div>
264
- </div>
265
-
266
- <div class="info-panel">
267
- <h3>Alignment Details</h3>
268
- <div id="alignment-details"></div>
269
- </div>
270
- </div>
271
-
272
- <script>
273
- // Attention data from Python
274
- const attentionData = {json.dumps(attn_data, ensure_ascii=False)};
275
- const numGlosses = {num_glosses};
276
- const numFeatures = {num_features};
277
-
278
- // Colors for different words (matching matplotlib tab20)
279
- const colors = [
280
- '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
281
- '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf',
282
- '#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#c5b0d5',
283
- '#c49c94', '#f7b6d2', '#c7c7c7', '#dbdb8d', '#9edae5'
284
- ];
285
-
286
- // Get controls
287
- const peakThresholdSlider = document.getElementById('peak-threshold');
288
- const peakThresholdValue = document.getElementById('peak-threshold-value');
289
- const confidenceHighSlider = document.getElementById('confidence-high');
290
- const confidenceHighValue = document.getElementById('confidence-high-value');
291
- const confidenceMediumSlider = document.getElementById('confidence-medium');
292
- const confidenceMediumValue = document.getElementById('confidence-medium-value');
293
- const alignmentCanvas = document.getElementById('alignment-canvas');
294
- const timelineCanvas = document.getElementById('timeline-canvas');
295
- const alignmentCtx = alignmentCanvas.getContext('2d');
296
- const timelineCtx = timelineCanvas.getContext('2d');
297
-
298
- // Update displays when sliders change
299
- peakThresholdSlider.oninput = function() {{
300
- peakThresholdValue.textContent = this.value + '%';
301
- updateVisualization();
302
- }};
303
-
304
- confidenceHighSlider.oninput = function() {{
305
- confidenceHighValue.textContent = (this.value / 100).toFixed(2);
306
- updateVisualization();
307
- }};
308
-
309
- confidenceMediumSlider.oninput = function() {{
310
- confidenceMediumValue.textContent = (this.value / 100).toFixed(2);
311
- updateVisualization();
312
- }};
313
-
314
- function resetDefaults() {{
315
- peakThresholdSlider.value = 90;
316
- confidenceHighSlider.value = 50;
317
- confidenceMediumSlider.value = 20;
318
- peakThresholdValue.textContent = '90%';
319
- confidenceHighValue.textContent = '0.50';
320
- confidenceMediumValue.textContent = '0.20';
321
- updateVisualization();
322
- }}
323
-
324
- function calculateAlignment(weights, peakThreshold) {{
325
- // Find peak
326
- let peakIdx = 0;
327
- let peakWeight = weights[0];
328
- for (let i = 1; i < weights.length; i++) {{
329
- if (weights[i] > peakWeight) {{
330
- peakWeight = weights[i];
331
- peakIdx = i;
332
- }}
333
- }}
334
-
335
- // Find significant frames
336
- const threshold = peakWeight * (peakThreshold / 100);
337
- let startIdx = peakIdx;
338
- let endIdx = peakIdx;
339
- let sumWeight = 0;
340
- let count = 0;
341
-
342
- for (let i = 0; i < weights.length; i++) {{
343
- if (weights[i] >= threshold) {{
344
- if (i < startIdx) startIdx = i;
345
- if (i > endIdx) endIdx = i;
346
- sumWeight += weights[i];
347
- count++;
348
- }}
349
- }}
350
-
351
- const avgWeight = count > 0 ? sumWeight / count : peakWeight;
352
-
353
- return {{
354
- startIdx: startIdx,
355
- endIdx: endIdx,
356
- peakIdx: peakIdx,
357
- peakWeight: peakWeight,
358
- avgWeight: avgWeight,
359
- threshold: threshold
360
- }};
361
- }}
362
-
363
- function getConfidenceLevel(avgWeight, highThreshold, mediumThreshold) {{
364
- if (avgWeight > highThreshold) return 'high';
365
- if (avgWeight > mediumThreshold) return 'medium';
366
- return 'low';
367
- }}
368
-
369
- function drawAlignmentChart() {{
370
- const peakThreshold = parseInt(peakThresholdSlider.value);
371
- const highThreshold = parseInt(confidenceHighSlider.value) / 100;
372
- const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;
373
-
374
- // Canvas dimensions
375
- const width = alignmentCanvas.width;
376
- const height = alignmentCanvas.height;
377
- const leftMargin = 180;
378
- const rightMargin = 50;
379
- const topMargin = 60;
380
- const bottomMargin = 80;
381
-
382
- const plotWidth = width - leftMargin - rightMargin;
383
- const plotHeight = height - topMargin - bottomMargin;
384
-
385
- const rowHeight = plotHeight / numGlosses;
386
- const featureWidth = plotWidth / numFeatures;
387
-
388
- // Clear canvas
389
- alignmentCtx.clearRect(0, 0, width, height);
390
-
391
- // Draw title
392
- alignmentCtx.fillStyle = '#333';
393
- alignmentCtx.font = 'bold 18px Arial';
394
- alignmentCtx.textAlign = 'center';
395
- alignmentCtx.fillText('Word-to-Frame Alignment', width / 2, 30);
396
- alignmentCtx.font = '13px Arial';
397
- alignmentCtx.fillText('(based on attention peaks, ★ = peak frame)', width / 2, 48);
398
-
399
- // Calculate alignments
400
- const alignments = [];
401
- for (let wordIdx = 0; wordIdx < numGlosses; wordIdx++) {{
402
- const data = attentionData[wordIdx];
403
- const alignment = calculateAlignment(data.weights, peakThreshold);
404
- alignment.word = data.word;
405
- alignment.wordIdx = wordIdx;
406
- alignment.weights = data.weights;
407
- alignments.push(alignment);
408
- }}
409
-
410
- // Draw grid
411
- alignmentCtx.strokeStyle = '#e0e0e0';
412
- alignmentCtx.lineWidth = 0.5;
413
- for (let i = 0; i <= numFeatures; i++) {{
414
- const x = leftMargin + i * featureWidth;
415
- alignmentCtx.beginPath();
416
- alignmentCtx.moveTo(x, topMargin);
417
- alignmentCtx.lineTo(x, topMargin + plotHeight);
418
- alignmentCtx.stroke();
419
- }}
420
-
421
- // Draw word regions
422
- for (let wordIdx = 0; wordIdx < numGlosses; wordIdx++) {{
423
- const alignment = alignments[wordIdx];
424
- const confidence = getConfidenceLevel(alignment.avgWeight, highThreshold, mediumThreshold);
425
- const y = topMargin + wordIdx * rowHeight;
426
-
427
- // Alpha based on confidence
428
- const alpha = confidence === 'high' ? 0.9 : confidence === 'medium' ? 0.7 : 0.5;
429
-
430
- // Draw rectangle for word region
431
- const startX = leftMargin + alignment.startIdx * featureWidth;
432
- const rectWidth = (alignment.endIdx - alignment.startIdx + 1) * featureWidth;
433
-
434
- alignmentCtx.fillStyle = colors[wordIdx % 20];
435
- alignmentCtx.globalAlpha = alpha;
436
- alignmentCtx.fillRect(startX, y, rectWidth, rowHeight * 0.8);
437
- alignmentCtx.globalAlpha = 1.0;
438
-
439
- // Draw border
440
- alignmentCtx.strokeStyle = '#000';
441
- alignmentCtx.lineWidth = 2;
442
- alignmentCtx.strokeRect(startX, y, rectWidth, rowHeight * 0.8);
443
-
444
- // Draw attention waveform inside rectangle
445
- alignmentCtx.strokeStyle = 'rgba(0, 0, 255, 0.8)';
446
- alignmentCtx.lineWidth = 1.5;
447
- alignmentCtx.beginPath();
448
- for (let i = alignment.startIdx; i <= alignment.endIdx; i++) {{
449
- const x = leftMargin + i * featureWidth + featureWidth / 2;
450
- const weight = alignment.weights[i];
451
- const maxWeight = alignment.peakWeight;
452
- const normalizedWeight = weight / (maxWeight * 1.2); // Scale for visibility
453
- const waveY = y + rowHeight * 0.8 - (normalizedWeight * rowHeight * 0.6);
454
-
455
- if (i === alignment.startIdx) {{
456
- alignmentCtx.moveTo(x, waveY);
457
- }} else {{
458
- alignmentCtx.lineTo(x, waveY);
459
- }}
460
- }}
461
- alignmentCtx.stroke();
462
-
463
- // Draw word label
464
- const labelX = startX + rectWidth / 2;
465
- const labelY = y + rowHeight * 0.4;
466
-
467
- alignmentCtx.fillStyle = 'rgba(0, 0, 0, 0.7)';
468
- alignmentCtx.fillRect(labelX - 60, labelY - 12, 120, 24);
469
- alignmentCtx.fillStyle = '#fff';
470
- alignmentCtx.font = 'bold 13px Arial';
471
- alignmentCtx.textAlign = 'center';
472
- alignmentCtx.textBaseline = 'middle';
473
- alignmentCtx.fillText(alignment.word, labelX, labelY);
474
-
475
- // Mark peak frame with star
476
- const peakX = leftMargin + alignment.peakIdx * featureWidth + featureWidth / 2;
477
- const peakY = y + rowHeight * 0.4;
478
-
479
- // Draw star
480
- alignmentCtx.fillStyle = '#ff0000';
481
- alignmentCtx.strokeStyle = '#ffff00';
482
- alignmentCtx.lineWidth = 1.5;
483
- alignmentCtx.font = '20px Arial';
484
- alignmentCtx.textAlign = 'center';
485
- alignmentCtx.strokeText('★', peakX, peakY);
486
- alignmentCtx.fillText('★', peakX, peakY);
487
-
488
- // Y-axis label (word names)
489
- alignmentCtx.fillStyle = '#333';
490
- alignmentCtx.font = '12px Arial';
491
- alignmentCtx.textAlign = 'right';
492
- alignmentCtx.textBaseline = 'middle';
493
- alignmentCtx.fillText(alignment.word, leftMargin - 10, y + rowHeight * 0.4);
494
- }}
495
-
496
- // Draw horizontal grid lines
497
- alignmentCtx.strokeStyle = '#ccc';
498
- alignmentCtx.lineWidth = 0.5;
499
- for (let i = 0; i <= numGlosses; i++) {{
500
- const y = topMargin + i * rowHeight;
501
- alignmentCtx.beginPath();
502
- alignmentCtx.moveTo(leftMargin, y);
503
- alignmentCtx.lineTo(leftMargin + plotWidth, y);
504
- alignmentCtx.stroke();
505
- }}
506
-
507
- // Draw axes
508
- alignmentCtx.strokeStyle = '#000';
509
- alignmentCtx.lineWidth = 2;
510
- alignmentCtx.strokeRect(leftMargin, topMargin, plotWidth, plotHeight);
511
-
512
- // X-axis labels (frame indices)
513
- alignmentCtx.fillStyle = '#000';
514
- alignmentCtx.font = '11px Arial';
515
- alignmentCtx.textAlign = 'center';
516
- alignmentCtx.textBaseline = 'top';
517
- for (let i = 0; i < numFeatures; i++) {{
518
- const x = leftMargin + i * featureWidth + featureWidth / 2;
519
- alignmentCtx.fillText(i.toString(), x, topMargin + plotHeight + 10);
520
- }}
521
-
522
- // Axis titles
523
- alignmentCtx.fillStyle = '#333';
524
- alignmentCtx.font = 'bold 14px Arial';
525
- alignmentCtx.textAlign = 'center';
526
- alignmentCtx.fillText('Feature Frame Index', leftMargin + plotWidth / 2, height - 20);
527
-
528
- alignmentCtx.save();
529
- alignmentCtx.translate(30, topMargin + plotHeight / 2);
530
- alignmentCtx.rotate(-Math.PI / 2);
531
- alignmentCtx.fillText('Generated Word', 0, 0);
532
- alignmentCtx.restore();
533
-
534
- return alignments;
535
- }}
536
-
537
- function drawTimeline(alignments) {{
538
- const highThreshold = parseInt(confidenceHighSlider.value) / 100;
539
- const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;
540
-
541
- const width = timelineCanvas.width;
542
- const height = timelineCanvas.height;
543
- const leftMargin = 180;
544
- const rightMargin = 50;
545
- const plotWidth = width - leftMargin - rightMargin;
546
- const featureWidth = plotWidth / numFeatures;
547
-
548
- // Clear canvas
549
- timelineCtx.clearRect(0, 0, width, height);
550
-
551
- // Background bar
552
- timelineCtx.fillStyle = '#ddd';
553
- timelineCtx.fillRect(leftMargin, 30, plotWidth, 40);
554
- timelineCtx.strokeStyle = '#000';
555
- timelineCtx.lineWidth = 2;
556
- timelineCtx.strokeRect(leftMargin, 30, plotWidth, 40);
557
-
558
- // Draw word regions on timeline
559
- for (let wordIdx = 0; wordIdx < alignments.length; wordIdx++) {{
560
- const alignment = alignments[wordIdx];
561
- const confidence = getConfidenceLevel(alignment.avgWeight, highThreshold, mediumThreshold);
562
- const alpha = confidence === 'high' ? 0.9 : confidence === 'medium' ? 0.7 : 0.5;
563
-
564
- const startX = leftMargin + alignment.startIdx * featureWidth;
565
- const rectWidth = (alignment.endIdx - alignment.startIdx + 1) * featureWidth;
566
-
567
- timelineCtx.fillStyle = colors[wordIdx % 20];
568
- timelineCtx.globalAlpha = alpha;
569
- timelineCtx.fillRect(startX, 30, rectWidth, 40);
570
- timelineCtx.globalAlpha = 1.0;
571
- timelineCtx.strokeStyle = '#000';
572
- timelineCtx.lineWidth = 0.5;
573
- timelineCtx.strokeRect(startX, 30, rectWidth, 40);
574
- }}
575
-
576
- // Title
577
- timelineCtx.fillStyle = '#333';
578
- timelineCtx.font = 'bold 13px Arial';
579
- timelineCtx.textAlign = 'left';
580
- timelineCtx.fillText('Timeline Progress Bar', leftMargin, 20);
581
- }}
582
-
583
- function updateDetailsPanel(alignments, highThreshold, mediumThreshold) {{
584
- const panel = document.getElementById('alignment-details');
585
- let html = '<table style="width: 100%; border-collapse: collapse;">';
586
- html += '<tr style="background: #f0f0f0; font-weight: bold;">';
587
- html += '<th style="padding: 8px; border: 1px solid #ddd;">Word</th>';
588
- html += '<th style="padding: 8px; border: 1px solid #ddd;">Feature Range</th>';
589
- html += '<th style="padding: 8px; border: 1px solid #ddd;">Peak</th>';
590
- html += '<th style="padding: 8px; border: 1px solid #ddd;">Span</th>';
591
- html += '<th style="padding: 8px; border: 1px solid #ddd;">Avg Attention</th>';
592
- html += '<th style="padding: 8px; border: 1px solid #ddd;">Confidence</th>';
593
- html += '</tr>';
594
-
595
- for (const align of alignments) {{
596
- const confidence = getConfidenceLevel(align.avgWeight, highThreshold, mediumThreshold);
597
- const span = align.endIdx - align.startIdx + 1;
598
-
599
- html += '<tr>';
600
- html += `<td style="padding: 8px; border: 1px solid #ddd;"><strong>${{align.word}}</strong></td>`;
601
- html += `<td style="padding: 8px; border: 1px solid #ddd;">${{align.startIdx}} → ${{align.endIdx}}</td>`;
602
- html += `<td style="padding: 8px; border: 1px solid #ddd;">${{align.peakIdx}}</td>`;
603
- html += `<td style="padding: 8px; border: 1px solid #ddd;">${{span}}</td>`;
604
- html += `<td style="padding: 8px; border: 1px solid #ddd;">${{align.avgWeight.toFixed(4)}}</td>`;
605
- html += `<td style="padding: 8px; border: 1px solid #ddd;"><span class="confidence ${{confidence}}">${{confidence}}</span></td>`;
606
- html += '</tr>';
607
- }}
608
-
609
- html += '</table>';
610
- panel.innerHTML = html;
611
- }}
612
-
613
- function updateVisualization() {{
614
- const alignments = drawAlignmentChart();
615
- drawTimeline(alignments);
616
- const highThreshold = parseInt(confidenceHighSlider.value) / 100;
617
- const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;
618
- updateDetailsPanel(alignments, highThreshold, mediumThreshold);
619
- }}
620
-
621
- // Event listeners for sliders
622
- peakSlider.addEventListener('input', function() {{
623
- peakValue.textContent = peakSlider.value + '%';
624
- updateVisualization();
625
- }});
626
-
627
- confidenceHighSlider.addEventListener('input', function() {{
628
- const val = parseInt(confidenceHighSlider.value) / 100;
629
- confidenceHighValue.textContent = val.toFixed(2);
630
- updateVisualization();
631
- }});
632
-
633
- confidenceMediumSlider.addEventListener('input', function() {{
634
- const val = parseInt(confidenceMediumSlider.value) / 100;
635
- confidenceMediumValue.textContent = val.toFixed(2);
636
- updateVisualization();
637
- }});
638
-
639
- // Initial visualization
640
- updateVisualization();
641
- </script>
642
- </body>
643
- </html>
644
- """
645
-
646
- # 5. Write the HTML file
647
- with open(output_path, 'w', encoding='utf-8') as f:
648
- f.write(html_content)
649
-
650
- print(f"✓ Interactive HTML generated: {output_path}")
651
- print(" Open this file in a browser and use the sliders to adjust thresholds.")
652
-
653
- if __name__ == "__main__":
654
- if len(sys.argv) != 2:
655
- print("Usage: python generate_interactive_alignment.py <sample_dir>")
656
- print("Example: python generate_interactive_alignment.py detailed_prediction_20251226_022246/sample_000")
657
- sys.exit(1)
658
-
659
- sample_dir = Path(sys.argv[1])
660
-
661
- if not sample_dir.exists():
662
- print(f"Error: directory not found: {sample_dir}")
663
- sys.exit(1)
664
-
665
- output_path = sample_dir / "interactive_alignment.html"
666
- generate_interactive_html(sample_dir, output_path)
667
-
668
- print("\nUsage:")
669
- print(f" Open in a browser: {output_path.absolute()}")
670
- print(" Move the sliders to preview different threshold settings in real time.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/good_videos_copy.sh DELETED
@@ -1,87 +0,0 @@
1
- #!/bin/bash
2
- # 执行前请确保目标目录可写:SignX/eval/tiny_test_data/good_videos
3
- set -e
4
-
5
- DEST="/research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/SignX/eval/tiny_test_data/good_videos"
6
- SRC_BASE="/research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/ASLLRP_utterances_results"
7
-
8
- mkdir -p "$DEST"
9
-
10
- cp "$SRC_BASE/7710510/crop_original_video.mp4" "$DEST/7710510.mp4"
11
- cp "$SRC_BASE/97999512/crop_original_video.mp4" "$DEST/97999512.mp4"
12
- cp "$SRC_BASE/7566726/crop_original_video.mp4" "$DEST/7566726.mp4"
13
- cp "$SRC_BASE/629983/crop_original_video.mp4" "$DEST/629983.mp4"
14
- cp "$SRC_BASE/619048/crop_original_video.mp4" "$DEST/619048.mp4"
15
- cp "$SRC_BASE/171921/crop_original_video.mp4" "$DEST/171921.mp4"
16
- cp "$SRC_BASE/6185381/crop_original_video.mp4" "$DEST/6185381.mp4"
17
- cp "$SRC_BASE/83940846/crop_original_video.mp4" "$DEST/83940846.mp4"
18
- cp "$SRC_BASE/63579/crop_original_video.mp4" "$DEST/63579.mp4"
19
- cp "$SRC_BASE/83940254/crop_original_video.mp4" "$DEST/83940254.mp4"
20
- cp "$SRC_BASE/6185086/crop_original_video.mp4" "$DEST/6185086.mp4"
21
- cp "$SRC_BASE/83941734/crop_original_video.mp4" "$DEST/83941734.mp4"
22
- cp "$SRC_BASE/7982378/crop_original_video.mp4" "$DEST/7982378.mp4"
23
- cp "$SRC_BASE/31655975/crop_original_video.mp4" "$DEST/31655975.mp4"
24
- cp "$SRC_BASE/7454155/crop_original_video.mp4" "$DEST/7454155.mp4"
25
- cp "$SRC_BASE/3381121/crop_original_video.mp4" "$DEST/3381121.mp4"
26
- cp "$SRC_BASE/23880856/crop_original_video.mp4" "$DEST/23880856.mp4"
27
- cp "$SRC_BASE/3378265/crop_original_video.mp4" "$DEST/3378265.mp4"
28
- cp "$SRC_BASE/7701925/crop_original_video.mp4" "$DEST/7701925.mp4"
29
- cp "$SRC_BASE/4236171/crop_original_video.mp4" "$DEST/4236171.mp4"
30
- cp "$SRC_BASE/8394388/crop_original_video.mp4" "$DEST/8394388.mp4"
31
- cp "$SRC_BASE/634818/crop_original_video.mp4" "$DEST/634818.mp4"
32
- cp "$SRC_BASE/173745/crop_original_video.mp4" "$DEST/173745.mp4"
33
- cp "$SRC_BASE/7569669/crop_original_video.mp4" "$DEST/7569669.mp4"
34
- cp "$SRC_BASE/50802118/crop_original_video.mp4" "$DEST/50802118.mp4"
35
- cp "$SRC_BASE/4235359/crop_original_video.mp4" "$DEST/4235359.mp4"
36
- cp "$SRC_BASE/842226/crop_original_video.mp4" "$DEST/842226.mp4"
37
- cp "$SRC_BASE/7981884/crop_original_video.mp4" "$DEST/7981884.mp4"
38
- cp "$SRC_BASE/31657848/crop_original_video.mp4" "$DEST/31657848.mp4"
39
- cp "$SRC_BASE/7983362/crop_original_video.mp4" "$DEST/7983362.mp4"
40
- cp "$SRC_BASE/5597316/crop_original_video.mp4" "$DEST/5597316.mp4"
41
- cp "$SRC_BASE/173238/crop_original_video.mp4" "$DEST/173238.mp4"
42
- cp "$SRC_BASE/843240/crop_original_video.mp4" "$DEST/843240.mp4"
43
- cp "$SRC_BASE/23881350/crop_original_video.mp4" "$DEST/23881350.mp4"
44
-
45
-
46
-
47
- - Sample 4 (7710510): NIGHT IX FATHER ARRIVE fs-LATE
48
- - Sample 7 (97999512): #NO IX-1p NOT GO-OUT
49
- - Sample 11 (7566726): MAYBE POSS CAR HERE
50
- - Sample 15 (629983): IX FINISH WORK WHEN IX
51
- - Sample 26 (619048): IF STUDENT IX HEAR/LISTEN TEACH+AGENT FUTURE LEARN SOMETHING/ONE
52
- - Sample 33 (171921): IX-1p NOT LIKE PINEAPPLE fs-CREAM+CHEESE IX-1p
53
- - Sample 38 (6185381): MOTHER SICK HOW part:indef
54
- - Sample 40 (83940846, 83940945): DEPART WHO
55
- - Sample 43 (63579): IX-1p WORK
56
- - Sample 45 (83940254): SWIM fs-BEACH IX WHO IX
57
- - Sample 53 (6185086): WHO MUST PAY EVERY-MONTH/RENT
58
- - Sample 58 (83941734, 83943314): FRIEND IX DEPART CAMP
59
- - Sample 61 (7982378): IX-1p PROCEED TAKE-UP #BBQ GROUP/TOGETHER
60
- - Sample 64 (31655975): IX-1p SCL:U-L"person passed out" DRUNK
61
- PAST+NIGHT QMwg
62
- - Sample 68 (7454155, 8397543): BUY CAR WHO part:indef
63
- - Sample 74 (3381121): BOX/ROOM IX NOT-YET ARRIVE IX SHOULD CONTACT
64
- ns-fs-FEDEX
65
- - Sample 81 (23880856): #IF RAIN IX-1p DEPART part:indef
66
- - Sample 86 (3378265): #IF IX NOT BORE IX-1p FUTURE READ IX-1p
67
- part:indef
68
- - Sample 87 (7701925, 7709712): IX-1p GO-OUT SWIM fs-BEACH
69
- - Sample 92 (4236171, 61835108): FRIEND WANT BUY PLAID VOLUNTEER/SHIRT
70
- - Sample 94 (8394388): FRIEND GO-OUT TOGETHER/GO-STEADY
71
- - Sample 107 (634818): FRIEND IX-pl PARTY GOOD/THANK-YOU
72
- - Sample 118 (173745, 173746, 26827222): CAR BREAK-DOWN
73
- - Sample 133 (7569669): POSS-1p FRIEND TELL IX BORN ns-CHICAGO
74
- - Sample 150 (50802118): IX ns-fs-JOHN HAVE DIFFERENT CAR
75
- - Sample 167 (4235359): WHO ASK FOR DIRECT
76
- - Sample 172 (842226): FRIEND LOVE SURF-INTERNET REALLY+WORK QMwg
77
- - Sample 179 (7981884): IX TEND CHAT WITH IX-pl-2
78
- - Sample 184 (31657848): MOTHER SICK QMwg
79
- - Sample 187 (7983362): FATHER FINISH MOW GRASS
80
- - Sample 192 (5597316): SOMETHING/ONE BUY CAR WHO part:indef
81
- - Sample 199 (173238): #NO IX-1p USE CORRECT KEY
82
- - Sample 206 (843240): #HS IX GO-OUT WHERE IX
83
- - Sample 208 (23881350): HAPPEN RAIN IX-1p STAY HOME
84
-
85
-
86
- echo "复制完成:34 个视频"
87
- echo "如需额外的同义 key,可将上面命令中的目录替换为 83940945、83943314、7709712、61835108、173746、26827222、8397543 等再运行一次。"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/metrics.py DELETED
@@ -1,320 +0,0 @@
1
- # coding: utf-8
2
- """
3
- This module holds various MT evaluation metrics.
4
- """
5
-
6
- import argparse
7
- import sacrebleu
8
- import mscoco_rouge
9
- import numpy as np
10
- import phoenix_cleanup as phoenix_utils
11
-
12
- WER_COST_DEL = 3
13
- WER_COST_INS = 3
14
- WER_COST_SUB = 4
15
-
16
-
17
- def chrf(references, hypotheses):
18
- """
19
- Character F-score from sacrebleu
20
-
21
- :param hypotheses: list of hypotheses (strings)
22
- :param references: list of references (strings)
23
- :return:
24
- """
25
- return (
26
- sacrebleu.corpus_chrf(hypotheses=hypotheses, references=references).score * 100
27
- )
28
-
29
-
30
- def bleu(references, hypotheses):
31
- """
32
- Raw corpus BLEU from sacrebleu (without tokenization)
33
-
34
- :param hypotheses: list of hypotheses (strings)
35
- :param references: list of references (strings)
36
- :return:
37
- """
38
- bleu_scores = sacrebleu.raw_corpus_bleu(
39
- sys_stream=hypotheses, ref_streams=[references]
40
- ).scores
41
- scores = {}
42
- for n in range(len(bleu_scores)):
43
- scores["bleu" + str(n + 1)] = bleu_scores[n]
44
- return scores
45
-
46
-
47
- def sableu(references, hypotheses, tokenizer):
48
- """
49
- Sacrebleu (with tokenization)
50
-
51
- :param hypotheses: list of hypotheses (strings)
52
- :param references: list of references (strings)
53
- :return:
54
- """
55
- bleu_scores = sacrebleu.corpus_bleu(
56
- sys_stream=hypotheses, ref_streams=[references], tokenize=tokenizer,
57
- ).scores
58
- scores = {}
59
- for n in range(len(bleu_scores)):
60
- scores["bleu" + str(n + 1)] = bleu_scores[n]
61
- return scores
62
-
63
-
64
- def token_accuracy(references, hypotheses, level="word"):
65
- """
66
- Compute the accuracy of hypothesis tokens: correct tokens / all tokens
67
- Tokens are correct if they appear in the same position in the reference.
68
-
69
- :param hypotheses: list of hypotheses (strings)
70
- :param references: list of references (strings)
71
- :param level: segmentation level, either "word", "bpe", or "char"
72
- :return:
73
- """
74
- correct_tokens = 0
75
- all_tokens = 0
76
- split_char = " " if level in ["word", "bpe"] else ""
77
- assert len(hypotheses) == len(references)
78
- for hyp, ref in zip(hypotheses, references):
79
- all_tokens += len(hyp)
80
- for h_i, r_i in zip(hyp.split(split_char), ref.split(split_char)):
81
- # min(len(h), len(r)) tokens considered
82
- if h_i == r_i:
83
- correct_tokens += 1
84
- return (correct_tokens / all_tokens) * 100 if all_tokens > 0 else 0.0
85
-
86
-
87
- def sequence_accuracy(references, hypotheses):
88
- """
89
- Compute the accuracy of hypothesis tokens: correct tokens / all tokens
90
- Tokens are correct if they appear in the same position in the reference.
91
-
92
- :param hypotheses: list of hypotheses (strings)
93
- :param references: list of references (strings)
94
- :return:
95
- """
96
- assert len(hypotheses) == len(references)
97
- correct_sequences = sum(
98
- [1 for (hyp, ref) in zip(hypotheses, references) if hyp == ref]
99
- )
100
- return (correct_sequences / len(hypotheses)) * 100 if hypotheses else 0.0
101
-
102
-
103
- def rouge(references, hypotheses):
104
- rouge_score = 0
105
- n_seq = len(hypotheses)
106
-
107
- for h, r in zip(hypotheses, references):
108
- rouge_score += mscoco_rouge.calc_score(hypotheses=[h], references=[r]) / n_seq
109
-
110
- return rouge_score * 100
111
-
112
-
113
- def wer_list(references, hypotheses):
114
- total_error = total_del = total_ins = total_sub = total_ref_len = 0
115
-
116
- for r, h in zip(references, hypotheses):
117
- res = wer_single(r=r, h=h)
118
- total_error += res["num_err"]
119
- total_del += res["num_del"]
120
- total_ins += res["num_ins"]
121
- total_sub += res["num_sub"]
122
- total_ref_len += res["num_ref"]
123
-
124
- wer = (total_error / total_ref_len) * 100
125
- del_rate = (total_del / total_ref_len) * 100
126
- ins_rate = (total_ins / total_ref_len) * 100
127
- sub_rate = (total_sub / total_ref_len) * 100
128
-
129
- return {
130
- "wer": wer,
131
- "del_rate": del_rate,
132
- "ins_rate": ins_rate,
133
- "sub_rate": sub_rate,
134
- }
135
-
136
-
137
- def wer_single(r, h):
138
- r = r.strip().split()
139
- h = h.strip().split()
140
- edit_distance_matrix = edit_distance(r=r, h=h)
141
- alignment, alignment_out = get_alignment(r=r, h=h, d=edit_distance_matrix)
142
-
143
- num_cor = np.sum([s == "C" for s in alignment])
144
- num_del = np.sum([s == "D" for s in alignment])
145
- num_ins = np.sum([s == "I" for s in alignment])
146
- num_sub = np.sum([s == "S" for s in alignment])
147
- num_err = num_del + num_ins + num_sub
148
- num_ref = len(r)
149
-
150
- return {
151
- "alignment": alignment,
152
- "alignment_out": alignment_out,
153
- "num_cor": num_cor,
154
- "num_del": num_del,
155
- "num_ins": num_ins,
156
- "num_sub": num_sub,
157
- "num_err": num_err,
158
- "num_ref": num_ref,
159
- }
160
-
161
-
162
- def edit_distance(r, h):
163
- """
164
- Original Code from https://github.com/zszyellow/WER-in-python/blob/master/wer.py
165
- This function is to calculate the edit distance of reference sentence and the hypothesis sentence.
166
- Main algorithm used is dynamic programming.
167
- Attributes:
168
- r -> the list of words produced by splitting reference sentence.
169
- h -> the list of words produced by splitting hypothesis sentence.
170
- """
171
- d = np.zeros((len(r) + 1) * (len(h) + 1), dtype=np.uint8).reshape(
172
- (len(r) + 1, len(h) + 1)
173
- )
174
- for i in range(len(r) + 1):
175
- for j in range(len(h) + 1):
176
- if i == 0:
177
- # d[0][j] = j
178
- d[0][j] = j * WER_COST_INS
179
- elif j == 0:
180
- d[i][0] = i * WER_COST_DEL
181
- for i in range(1, len(r) + 1):
182
- for j in range(1, len(h) + 1):
183
- if r[i - 1] == h[j - 1]:
184
- d[i][j] = d[i - 1][j - 1]
185
- else:
186
- substitute = d[i - 1][j - 1] + WER_COST_SUB
187
- insert = d[i][j - 1] + WER_COST_INS
188
- delete = d[i - 1][j] + WER_COST_DEL
189
- d[i][j] = min(substitute, insert, delete)
190
- return d
191
-
192
-
193
- def get_alignment(r, h, d):
194
- """
195
- Original Code from https://github.com/zszyellow/WER-in-python/blob/master/wer.py
196
- This function is to get the list of steps in the process of dynamic programming.
197
- Attributes:
198
- r -> the list of words produced by splitting reference sentence.
199
- h -> the list of words produced by splitting hypothesis sentence.
200
- d -> the matrix built when calculating the editing distance of h and r.
201
- """
202
- x = len(r)
203
- y = len(h)
204
- max_len = 3 * (x + y)
205
-
206
- alignlist = []
207
- align_ref = ""
208
- align_hyp = ""
209
- alignment = ""
210
-
211
- while True:
212
- if (x <= 0 and y <= 0) or (len(alignlist) > max_len):
213
- break
214
- elif x >= 1 and y >= 1 and d[x][y] == d[x - 1][y - 1] and r[x - 1] == h[y - 1]:
215
- align_hyp = " " + h[y - 1] + align_hyp
216
- align_ref = " " + r[x - 1] + align_ref
217
- alignment = " " * (len(r[x - 1]) + 1) + alignment
218
- alignlist.append("C")
219
- x = max(x - 1, 0)
220
- y = max(y - 1, 0)
221
- elif x >= 1 and y >= 1 and d[x][y] == d[x - 1][y - 1] + WER_COST_SUB:
222
- ml = max(len(h[y - 1]), len(r[x - 1]))
223
- align_hyp = " " + h[y - 1].ljust(ml) + align_hyp
224
- align_ref = " " + r[x - 1].ljust(ml) + align_ref
225
- alignment = " " + "S" + " " * (ml - 1) + alignment
226
- alignlist.append("S")
227
- x = max(x - 1, 0)
228
- y = max(y - 1, 0)
229
- elif y >= 1 and d[x][y] == d[x][y - 1] + WER_COST_INS:
230
- align_hyp = " " + h[y - 1] + align_hyp
231
- align_ref = " " + "*" * len(h[y - 1]) + align_ref
232
- alignment = " " + "I" + " " * (len(h[y - 1]) - 1) + alignment
233
- alignlist.append("I")
234
- x = max(x, 0)
235
- y = max(y - 1, 0)
236
- else:
237
- align_hyp = " " + "*" * len(r[x - 1]) + align_hyp
238
- align_ref = " " + r[x - 1] + align_ref
239
- alignment = " " + "D" + " " * (len(r[x - 1]) - 1) + alignment
240
- alignlist.append("D")
241
- x = max(x - 1, 0)
242
- y = max(y, 0)
243
-
244
- align_ref = align_ref[1:]
245
- align_hyp = align_hyp[1:]
246
- alignment = alignment[1:]
247
-
248
- return (
249
- alignlist[::-1],
250
- {"align_ref": align_ref, "align_hyp": align_hyp, "alignment": alignment},
251
- )
252
-
253
-
254
- if __name__ == "__main__":
255
-
256
- arg_parser = argparse.ArgumentParser(
257
- description="SLTUnet Evaluator: quality evaluation for sign language translation",
258
- formatter_class=argparse.RawDescriptionHelpFormatter,
259
- )
260
- arg_parser.add_argument(
261
- "--task",
262
- "-t",
263
- choices=["slt", "slr"],
264
- type=str,
265
- default=None,
266
- required=True,
267
- help="the task for evaluation, either sign language translation (slt) or sign langauge recognition (slr)",
268
- )
269
- arg_parser.add_argument(
270
- "--hypothesis",
271
- "-hyp",
272
- type=str,
273
- default=None,
274
- required=True,
275
- help="Model output or system generation.",
276
- )
277
-
278
- arg_parser.add_argument(
279
- "--reference",
280
- "-ref",
281
- type=str,
282
- default=None,
283
- required=True,
284
- help="Gold reference",
285
- )
286
- arg_parser.add_argument(
287
- "--tokenize",
288
- "-tok",
289
- choices=sacrebleu.TOKENIZERS.keys(),
290
- default="13a",
291
- help="tokenization method to use",
292
- )
293
- arg_parser.add_argument(
294
- "--phoenix",
295
- default=False,
296
- action="store_true",
297
- help="Perform evaluation for Phoenix 2014T (special preprocessing will be applied to glosses)",
298
- )
299
-
300
- args = arg_parser.parse_args()
301
-
302
- references = [l.strip() for l in open(args.reference, 'r')]
303
- hypotheses = [l.strip() for l in open(args.hypothesis, 'r')]
304
-
305
- if args.task == "slr": # sign language recognition requires WER
306
- if args.phoenix:
307
- references = [phoenix_utils.clean_phoenix_2014_trans(r) for r in references]
308
- hypotheses = [phoenix_utils.clean_phoenix_2014_trans(h) for h in hypotheses]
309
-
310
- print('Wer', wer_list(references, hypotheses))
311
- else:
312
- if args.tokenize == "none": # default result
313
- print('BLEU', bleu(references, hypotheses))
314
- print('Rouge', rouge(references, hypotheses))
315
- else: # sacrebleu
316
- print('Signature: BLEU+case.mixed+numrefs.1+smooth.exp+tok.%s+version.1.4.2' % args.tokenize)
317
- print('BLEU', sableu(references, hypotheses, args.tokenize))
318
- print('Signature: chrF2+case.mixed+numchars.6+numrefs.1+space.False+version.1.4.2')
319
- print('Chrf', chrf(references, hypotheses))
320
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/mscoco_rouge.py DELETED
@@ -1,67 +0,0 @@
1
- #!/usr/bin/env python
2
- #
3
- # File Name : mscoco_rouge.py
4
- #
5
- # Description : Computes ROUGE-L metric as described by Lin and Hovey (2004)
6
- #
7
- # Creation Date : 2015-01-07 06:03
8
- # Author : Ramakrishna Vedantam <vrama91@vt.edu>
9
-
10
-
11
- def my_lcs(string, sub):
12
- """
13
- Calculates longest common subsequence for a pair of tokenized strings
14
- :param string : list of str : tokens from a string split using whitespace
15
- :param sub : list of str : shorter string, also split using whitespace
16
- :returns: length (list of int): length of the longest common subsequence between the two strings
17
-
18
- Note: my_lcs only gives length of the longest common subsequence, not the actual LCS
19
- """
20
- if len(string) < len(sub):
21
- sub, string = string, sub
22
-
23
- lengths = [[0 for i in range(0, len(sub) + 1)] for j in range(0, len(string) + 1)]
24
-
25
- for j in range(1, len(sub) + 1):
26
- for i in range(1, len(string) + 1):
27
- if string[i - 1] == sub[j - 1]:
28
- lengths[i][j] = lengths[i - 1][j - 1] + 1
29
- else:
30
- lengths[i][j] = max(lengths[i - 1][j], lengths[i][j - 1])
31
-
32
- return lengths[len(string)][len(sub)]
33
-
34
-
35
- def calc_score(hypotheses, references, beta=1.2):
36
- """
37
- Compute ROUGE-L score given one candidate and references for an image
38
- :param hypotheses: str : candidate sentence to be evaluated
39
- :param references: list of str : COCO reference sentences for the particular image to be evaluated
40
- :returns score: int (ROUGE-L score for the candidate evaluated against references)
41
- """
42
- assert len(hypotheses) == 1
43
- assert len(references) > 0
44
- prec = []
45
- rec = []
46
-
47
- # split into tokens
48
- token_c = hypotheses[0].split(" ")
49
-
50
- for reference in references:
51
- # split into tokens
52
- token_r = reference.split(" ")
53
- # compute the longest common subsequence
54
- lcs = my_lcs(token_r, token_c)
55
- prec.append(lcs / float(len(token_c)))
56
- rec.append(lcs / float(len(token_r)))
57
-
58
- prec_max = max(prec)
59
- rec_max = max(rec)
60
-
61
- if prec_max != 0 and rec_max != 0:
62
- score = ((1 + beta ** 2) * prec_max * rec_max) / float(
63
- rec_max + beta ** 2 * prec_max
64
- )
65
- else:
66
- score = 0.0
67
- return score
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/phoenix_cleanup.py DELETED
@@ -1,90 +0,0 @@
1
- from itertools import groupby
2
- import re
3
-
4
-
5
- def clean_phoenix_2014(prediction):
6
- # TODO (Cihan): Python version of the evaluation script provided
7
- # by the phoenix2014 dataset (not phoenix2014t). This should work
8
- # as intended but further tests are required to make sure it is
9
- # consistent with the bash/sed based clean up script.
10
-
11
- prediction = prediction.strip()
12
- prediction = re.sub(r"loc-", "", prediction)
13
- prediction = re.sub(r"cl-", "", prediction)
14
- prediction = re.sub(r"qu-", "", prediction)
15
- prediction = re.sub(r"poss-", "", prediction)
16
- prediction = re.sub(r"lh-", "", prediction)
17
- prediction = re.sub(r"S0NNE", "SONNE", prediction)
18
- prediction = re.sub(r"HABEN2", "HABEN", prediction)
19
- prediction = re.sub(r"__EMOTION__", "", prediction)
20
- prediction = re.sub(r"__PU__", "", prediction)
21
- prediction = re.sub(r"__LEFTHAND__", "", prediction)
22
- prediction = re.sub(r"WIE AUSSEHEN", "WIE-AUSSEHEN", prediction)
23
- prediction = re.sub(r"ZEIGEN ", "ZEIGEN-BILDSCHIRM ", prediction)
24
- prediction = re.sub(r"ZEIGEN$", "ZEIGEN-BILDSCHIRM", prediction)
25
- prediction = re.sub(r"^([A-Z]) ([A-Z][+ ])", r"\1+\2", prediction)
26
- prediction = re.sub(r"[ +]([A-Z]) ([A-Z]) ", r" \1+\2 ", prediction)
27
- prediction = re.sub(r"([ +][A-Z]) ([A-Z][ +])", r"\1+\2", prediction)
28
- prediction = re.sub(r"([ +][A-Z]) ([A-Z][ +])", r"\1+\2", prediction)
29
- prediction = re.sub(r"([ +][A-Z]) ([A-Z][ +])", r"\1+\2", prediction)
30
- prediction = re.sub(r"([ +]SCH) ([A-Z][ +])", r"\1+\2", prediction)
31
- prediction = re.sub(r"([ +]NN) ([A-Z][ +])", r"\1+\2", prediction)
32
- prediction = re.sub(r"([ +][A-Z]) (NN[ +])", r"\1+\2", prediction)
33
- prediction = re.sub(r"([ +][A-Z]) ([A-Z])$", r"\1+\2", prediction)
34
- prediction = re.sub(r"([A-Z][A-Z])RAUM", r"\1", prediction)
35
- prediction = re.sub(r"-PLUSPLUS", "", prediction)
36
- prediction = re.sub(r" +", " ", prediction)
37
- prediction = re.sub(r"(?<![\w-])(\b[A-Z]+(?![\w-])) \1(?![\w-])", r"\1", prediction)
38
- prediction = re.sub(r"(?<![\w-])(\b[A-Z]+(?![\w-])) \1(?![\w-])", r"\1", prediction)
39
- prediction = re.sub(r"(?<![\w-])(\b[A-Z]+(?![\w-])) \1(?![\w-])", r"\1", prediction)
40
- prediction = re.sub(r"(?<![\w-])(\b[A-Z]+(?![\w-])) \1(?![\w-])", r"\1", prediction)
41
- prediction = re.sub(r" +", " ", prediction)
42
-
43
- assert not re.search("__LEFTHAND__", prediction)
44
- assert not re.search("__EPENTHESIS__", prediction)
45
- assert not re.search("__EMOTION__", prediction)
46
-
47
- # Remove white spaces and repetitions
48
- prediction = " ".join(
49
- " ".join(i[0] for i in groupby(prediction.split(" "))).split()
50
- )
51
- prediction = prediction.strip()
52
-
53
- return prediction
54
-
55
-
56
- def clean_phoenix_2014_trans(prediction):
57
-
58
- prediction = prediction.strip()
59
- prediction = re.sub(r"__LEFTHAND__", "", prediction)
60
- prediction = re.sub(r"__EPENTHESIS__", "", prediction)
61
- prediction = re.sub(r"__EMOTION__", "", prediction)
62
- prediction = re.sub(r"\b__[^_ ]*__\b", "", prediction)
63
- prediction = re.sub(r"\bloc-([^ ]*)\b", r"\1", prediction)
64
- prediction = re.sub(r"\bcl-([^ ]*)\b", r"\1", prediction)
65
- prediction = re.sub(r"\b([^ ]*)-PLUSPLUS\b", r"\1", prediction)
66
- prediction = re.sub(r"\b([A-Z][A-Z]*)RAUM\b", r"\1", prediction)
67
- prediction = re.sub(r"WIE AUSSEHEN", "WIE-AUSSEHEN", prediction)
68
- prediction = re.sub(r"^([A-Z]) ([A-Z][+ ])", r"\1+\2", prediction)
69
- prediction = re.sub(r"[ +]([A-Z]) ([A-Z]) ", r" \1+\2 ", prediction)
70
- prediction = re.sub(r"([ +][A-Z]) ([A-Z][ +])", r"\1+\2", prediction)
71
- prediction = re.sub(r"([ +][A-Z]) ([A-Z][ +])", r"\1+\2", prediction)
72
- prediction = re.sub(r"([ +][A-Z]) ([A-Z][ +])", r"\1+\2", prediction)
73
- prediction = re.sub(r"([ +]SCH) ([A-Z][ +])", r"\1+\2", prediction)
74
- prediction = re.sub(r"([ +]NN) ([A-Z][ +])", r"\1+\2", prediction)
75
- prediction = re.sub(r"([ +][A-Z]) (NN[ +])", r"\1+\2", prediction)
76
- prediction = re.sub(r"([ +][A-Z]) ([A-Z])$", r"\1+\2", prediction)
77
- prediction = re.sub(r" +", " ", prediction)
78
- prediction = re.sub(r"(?<![\w-])(\b[A-Z]+(?![\w-])) \1(?![\w-])", r"\1", prediction)
79
- prediction = re.sub(r"(?<![\w-])(\b[A-Z]+(?![\w-])) \1(?![\w-])", r"\1", prediction)
80
- prediction = re.sub(r"(?<![\w-])(\b[A-Z]+(?![\w-])) \1(?![\w-])", r"\1", prediction)
81
- prediction = re.sub(r"(?<![\w-])(\b[A-Z]+(?![\w-])) \1(?![\w-])", r"\1", prediction)
82
- prediction = re.sub(r" +", " ", prediction)
83
-
84
- # Remove white spaces and repetitions
85
- prediction = " ".join(
86
- " ".join(i[0] for i in groupby(prediction.split(" "))).split()
87
- )
88
- prediction = prediction.strip()
89
-
90
- return prediction
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/pose_vit_dim_analysis.py DELETED
@@ -1,442 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Pose ViT dimensional importance analysis.
4
-
5
- This script mimics the pose-assist (video2pose → pad-to-2048) pipeline used in Sign-X:
6
- 1. Load the ViT-based video2pose encoder and the PadMatch+LayerNorm projection from
7
- the video2text checkpoint (e.g., video2text_checkpoint_epoch_14.pth).
8
- 2. Sample frames from a given video, extract per-frame pose representations,
9
- and project them to 2048 dimensions.
10
- 3. Compute simple importance scores (mean absolute activation per dimension),
11
- then export CSV/plots/report summarising the dominant pose dimensions.
12
- """
13
-
14
- import argparse
15
- import json
16
- import os
17
- import pickle
18
- import sys
19
- import types
20
- from pathlib import Path
21
-
22
- import cv2
23
- import matplotlib
24
-
25
- matplotlib.use("Agg")
26
- import matplotlib.pyplot as plt # noqa: E402
27
- import numpy as np # noqa: E402
28
- import torch # noqa: E402
29
- import torch.nn as nn # noqa: E402
30
- from PIL import Image # noqa: E402
31
- from torchvision import transforms # noqa: E402
32
- try:
33
- import timm # noqa: E402
34
- except ImportError as exc:
35
- raise ImportError("timm is required for ViT backbone. Please install timm.") from exc
36
-
37
-
38
- INPUT_DIMS = {
39
- "dwpose": 384,
40
- "mediapipe_pose": 258,
41
- "primedepth_depth": 576,
42
- "sapiens_segmentation": 576,
43
- "smplerx": 165,
44
- }
45
- POSE_TYPE_ORDER = ["dwpose", "mediapipe_pose", "primedepth_depth", "sapiens_segmentation", "smplerx"]
46
-
47
-
48
- class CodeBook: # noqa: D401 - Dummy placeholder so torch.load can unpickle checkpoints.
49
- """Placeholder CodeBook to satisfy torch.load when checkpoints store this object."""
50
-
51
- def __init__(self, *args, **kwargs):
52
- self.vocab_size = kwargs.get("vocab_size", 0)
53
-
54
-
55
- class Video2Pose(nn.Module):
56
- """Minimal replica of the pose-assist encoder (ViT + temporal attention + per-type projection)."""
57
-
58
- def __init__(self, input_dims):
59
- super().__init__()
60
- self.backbone = timm.create_model("vit_base_patch16_224", pretrained=True, num_classes=0)
61
- self.temporal_attention = nn.MultiheadAttention(768, num_heads=8)
62
- self.temporal_norm = nn.LayerNorm(768)
63
- self.projections = nn.ModuleDict({pose: nn.Linear(768, dim) for pose, dim in input_dims.items()})
64
-
65
- def forward(self, x):
66
- # x: [B, F, 3, H, W]
67
- B, F, C, H, W = x.shape
68
- features = self.backbone(x.view(B * F, C, H, W)) # [B*F, 768]
69
- features = features.view(B, F, -1).transpose(0, 1) # [F, B, 768]
70
- attended, _ = self.temporal_attention(features, features, features)
71
- attended = self.temporal_norm(attended).transpose(0, 1) # [B, F, 768]
72
- return {pose: proj(attended) for pose, proj in self.projections.items()}
73
-
74
-
75
- class PadMatch(nn.Module):
76
- """Pad features to hidden_dim and apply LayerNorm (weights loaded from checkpoint)."""
77
-
78
- def __init__(self, input_dim, hidden_dim):
79
- super().__init__()
80
- self.input_dim = input_dim
81
- self.hidden_dim = hidden_dim
82
- self.pad = hidden_dim - input_dim
83
- if self.pad < 0:
84
- raise ValueError(f"hidden_dim {hidden_dim} must be >= input_dim {input_dim}")
85
- self.layer_norm = nn.LayerNorm(hidden_dim)
86
-
87
- def forward(self, x):
88
- if self.pad > 0:
89
- x = nn.functional.pad(x, (0, self.pad), "constant", 0.0)
90
- return self.layer_norm(x)
91
-
92
-
93
- def parse_args():
94
- parser = argparse.ArgumentParser(description="Pose ViT dimensional analysis (video2pose → 2048D).")
95
- parser.add_argument("--video", required=True, help="Path to input video (.mp4).")
96
- parser.add_argument(
97
- "--checkpoint",
98
- default="smkd/pretrained/video2text_checkpoint_epoch_14.pth",
99
- help="Path to video2text checkpoint containing video2pose weights.",
100
- )
101
- parser.add_argument(
102
- "--output-dir",
103
- default="pose_vit_feature_analysis",
104
- help="Directory to store feature dumps, plots, and summary.",
105
- )
106
- parser.add_argument("--num-frames", type=int, default=32, help="Frames sampled uniformly from the video.")
107
- parser.add_argument("--device", choices=["cuda", "cpu"], default="cuda", help="Torch device preference.")
108
- parser.add_argument("--topk", type=int, default=32, help="Number of top dimensions to visualise.")
109
- return parser.parse_args()
110
-
111
-
112
- def prepare_device(pref: str) -> torch.device:
113
- if pref == "cuda" and torch.cuda.is_available():
114
- return torch.device("cuda")
115
- return torch.device("cpu")
116
-
117
-
118
- def ensure_dir(path: str) -> Path:
119
- dst = Path(path)
120
- dst.mkdir(parents=True, exist_ok=True)
121
- return dst
122
-
123
-
124
- def load_checkpoint(checkpoint_path: str, device: torch.device):
125
- """Load checkpoint with safe unpickling fallback."""
126
- try:
127
- ckpt = torch.load(checkpoint_path, map_location=device, weights_only=True)
128
- except (TypeError, AttributeError, pickle.UnpicklingError):
129
- torch.serialization.add_safe_globals([CodeBook])
130
- ckpt = torch.load(checkpoint_path, map_location=device, weights_only=False)
131
-
132
- if isinstance(ckpt, dict) and "model_state_dict" in ckpt:
133
- return ckpt["model_state_dict"]
134
- return ckpt
135
-
136
-
137
- def load_video2pose_weights(model: Video2Pose, state_dict):
138
- sub_state = {k.replace("video2pose.", "", 1): v for k, v in state_dict.items() if k.startswith("video2pose.")}
139
- missing, unexpected = model.load_state_dict(sub_state, strict=False)
140
- if missing:
141
- print(f"[WARN] Missing video2pose keys ({len(missing)}): {missing[:5]}...")
142
- if unexpected:
143
- print(f"[WARN] Unexpected video2pose keys ({len(unexpected)}): {unexpected[:5]}...")
144
-
145
-
146
- def load_padmatch_weights(projector: PadMatch, state_dict):
147
- sub_state = {
148
- k.replace("pose2text.dim_match.", "", 1): v
149
- for k, v in state_dict.items()
150
- if k.startswith("pose2text.dim_match.")
151
- }
152
- ln_state = {}
153
- if "1.weight" in sub_state:
154
- ln_state["weight"] = sub_state["1.weight"]
155
- if "1.bias" in sub_state:
156
- ln_state["bias"] = sub_state["1.bias"]
157
- if ln_state:
158
- projector.layer_norm.load_state_dict(ln_state, strict=False)
159
- if "1.weight" not in sub_state or "1.bias" not in sub_state:
160
- print("[WARN] LayerNorm weights not found in checkpoint; using default initialisation.")
161
-
162
-
163
- def load_and_process_video(video_path: str, num_frames: int):
164
- cap = cv2.VideoCapture(video_path)
165
- if not cap.isOpened():
166
- raise RuntimeError(f"Unable to open video {video_path}")
167
-
168
- total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
169
- if total <= 0:
170
- raise RuntimeError(f"No frames found in video {video_path}")
171
-
172
- indices = np.linspace(0, max(total - 1, 0), num=num_frames, dtype=np.int32)
173
- transform = transforms.Compose(
174
- [
175
- transforms.Resize((224, 224)),
176
- transforms.ToTensor(),
177
- transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
178
- ]
179
- )
180
-
181
- frames = []
182
- for idx in indices:
183
- cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx))
184
- ok, frame = cap.read()
185
- if not ok:
186
- continue
187
- frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
188
- frames.append(transform(Image.fromarray(frame)))
189
-
190
- cap.release()
191
-
192
- if not frames:
193
- raise RuntimeError(f"Failed to decode frames from {video_path}")
194
-
195
- while len(frames) < num_frames:
196
- frames.append(frames[-1].clone())
197
-
198
- return torch.stack(frames[:num_frames], dim=0) # [F, 3, 224, 224]
199
-
200
-
201
- def compute_importance(pose_2048: torch.Tensor):
202
- with torch.no_grad():
203
- scores = pose_2048.abs().mean(dim=(0, 1)).cpu().numpy()
204
- normalized = scores / (scores.max() + 1e-8)
205
- return scores, normalized
206
-
207
-
208
- def plot_top_dimensions(scores, top_indices, output_path):
209
- plt.figure(figsize=(max(8, len(top_indices) * 0.35), 4))
210
- plt.bar(range(len(top_indices)), scores[top_indices], color="#1f77b4")
211
- plt.xticks(range(len(top_indices)), [str(i) for i in top_indices], rotation=60)
212
- plt.ylabel("Mean |activation|")
213
- plt.xlabel("Dimension")
214
- plt.title("Top pose dimensions")
215
- plt.tight_layout()
216
- plt.savefig(output_path, dpi=240)
217
- plt.close()
218
-
219
-
220
- def plot_heatmap(normalized_scores, output_path):
221
- # Only use the actual pose dimensions (excluding padding)
222
- total_pose_dims = sum(INPUT_DIMS.values()) # 1959
223
- rows = 32
224
- cols = int(np.ceil(total_pose_dims / rows)) # 62 columns needed
225
-
226
- # Only use real pose features, not padding
227
- heat_data = normalized_scores[:total_pose_dims]
228
- # Pad to fill the rectangle if needed
229
- needed = rows * cols
230
- if len(heat_data) < needed:
231
- heat_data = np.pad(heat_data, (0, needed - len(heat_data)), constant_values=0)
232
- heat = heat_data.reshape(rows, cols)
233
-
234
- # Calculate pose type boundaries
235
- boundaries = []
236
- cumsum = 0
237
- for pose_type in POSE_TYPE_ORDER:
238
- cumsum += INPUT_DIMS[pose_type]
239
- boundaries.append(cumsum)
240
- # boundaries = [384, 642, 1218, 1794, 1959]
241
-
242
- # Adjust figure size to reduce right-side whitespace
243
- fig, ax = plt.subplots(figsize=(12, 6))
244
- im = ax.imshow(heat, aspect="auto", cmap="magma", extent=[0, cols, rows, 0])
245
-
246
- # Set limits to avoid extra space
247
- ax.set_xlim(0, cols)
248
- ax.set_ylim(rows, 0) # Invert y-axis
249
-
250
- # Draw red lines to separate pose types
251
- # Convert dimension index to (row, col) in the heatmap
252
- for boundary_dim in boundaries:
253
- row = boundary_dim // cols
254
- col = boundary_dim % cols
255
-
256
- if col == 0:
257
- # Boundary is at the start of a row, draw horizontal line
258
- ax.axhline(y=row, color='red', linewidth=1.2, linestyle='-', alpha=0.9)
259
- else:
260
- # Boundary is in the middle of a row, draw an L-shaped line
261
- # Vertical line from current position to end of row
262
- ax.plot([col, col], [row, row + 1],
263
- color='red', linewidth=1.2, linestyle='-', alpha=0.9)
264
- # Horizontal line at the bottom of current row
265
- ax.plot([0, col], [row + 1, row + 1],
266
- color='red', linewidth=1.2, linestyle='-', alpha=0.9)
267
- # Horizontal line at the top of next row (if boundary continues)
268
- if row < rows - 1:
269
- ax.plot([col, cols], [row + 1, row + 1],
270
- color='red', linewidth=1.2, linestyle='-', alpha=0.9)
271
-
272
- # Add text labels for pose types at region centers (1.5x size)
273
- pose_labels = POSE_TYPE_ORDER
274
- pose_boundaries = [0] + boundaries
275
- for i, pose_name in enumerate(pose_labels):
276
- start_dim = pose_boundaries[i]
277
- end_dim = pose_boundaries[i + 1] - 1 # Last dimension in region
278
-
279
- # Calculate geometric center for regions spanning multiple rows
280
- start_row = start_dim // cols
281
- start_col = start_dim % cols
282
- end_row = end_dim // cols
283
- end_col = end_dim % cols
284
-
285
- region_size = pose_boundaries[i + 1] - start_dim
286
-
287
- # Calculate center row
288
- center_row = (start_row + end_row) / 2.0
289
-
290
- # Calculate center col based on region shape
291
- if start_row == end_row:
292
- # Single row: simple average
293
- center_col = (start_col + end_col) / 2.0
294
- else:
295
- # Multi-row: calculate weighted average col
296
- total_cells = 0
297
- weighted_col = 0
298
-
299
- # First partial row
300
- first_row_cells = cols - start_col
301
- weighted_col += (start_col + cols - 1) / 2.0 * first_row_cells
302
- total_cells += first_row_cells
303
-
304
- # Full middle rows
305
- middle_rows = end_row - start_row - 1
306
- if middle_rows > 0:
307
- weighted_col += (cols / 2.0) * cols * middle_rows
308
- total_cells += cols * middle_rows
309
-
310
- # Last partial row
311
- last_row_cells = end_col + 1
312
- weighted_col += (end_col / 2.0) * last_row_cells
313
- total_cells += last_row_cells
314
-
315
- center_col = weighted_col / total_cells
316
-
317
- # Add label if there's enough space
318
- if region_size >= 50:
319
- ax.text(center_col, center_row, pose_name,
320
- fontsize=14, ha='center', va='center',
321
- color='white', weight='bold',
322
- bbox=dict(boxstyle='round,pad=0.3', facecolor='black', alpha=0.5))
323
-
324
- # Set labels and title with 2x font size
325
- ax.set_xlabel("Chunk index", fontsize=20)
326
- ax.set_ylabel("Row", fontsize=20)
327
- ax.set_title("Pose dimension importance heatmap", fontsize=24)
328
-
329
- # Set tick label size to 2x
330
- ax.tick_params(axis='both', which='major', labelsize=20)
331
-
332
- # Add colorbar with larger font, shrink to reduce width
333
- cbar = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
334
- cbar.ax.tick_params(labelsize=20)
335
- cbar.set_label("Normalized importance", fontsize=20)
336
-
337
- plt.tight_layout()
338
- plt.savefig(output_path, dpi=240, bbox_inches='tight')
339
- # Also save as PDF
340
- pdf_path = output_path.parent / (output_path.stem + ".pdf")
341
- plt.savefig(pdf_path, bbox_inches='tight')
342
- plt.close()
343
-
344
-
345
- def plot_cumulative(scores, output_path):
346
- sorted_scores = np.sort(scores)[::-1]
347
- coverage = np.cumsum(sorted_scores) / sorted_scores.sum()
348
- plt.figure(figsize=(8, 4))
349
- plt.plot(np.arange(1, len(sorted_scores) + 1), coverage, color="#ff7f0e")
350
- plt.xlabel("Top-k dimensions")
351
- plt.ylabel("Cumulative coverage")
352
- plt.grid(alpha=0.3)
353
- plt.tight_layout()
354
- plt.savefig(output_path, dpi=240)
355
- plt.close()
356
- return coverage
357
-
358
-
359
- def save_csv(scores, normalized, output_path):
360
- with open(output_path, "w", encoding="utf-8") as handle:
361
- handle.write("dimension,score,normalized\n")
362
- for idx, (score, norm) in enumerate(zip(scores, normalized)):
363
- handle.write(f"{idx},{score:.8f},{norm:.6f}\n")
364
-
365
-
366
- def write_report(video, checkpoint, scores, normalized, coverage, top_indices, output_path):
367
- with open(output_path, "w", encoding="utf-8") as handle:
368
- handle.write("Pose ViT dimensional analysis\n")
369
- handle.write("=" * 60 + "\n\n")
370
- handle.write(f"Video : {video}\n")
371
- handle.write(f"Checkpoint : {checkpoint}\n")
372
- handle.write(f"Total dims : {scores.shape[0]}\n\n")
373
- handle.write("Top dimensions:\n")
374
- for rank, dim_idx in enumerate(top_indices, 1):
375
- handle.write(
376
- f"{rank:02d}. dim {dim_idx:04d} | score={scores[dim_idx]:.6f} "
377
- f"| normalized={normalized[dim_idx]:.4f}\n"
378
- )
379
-
380
- handle.write("\nCoverage milestones:\n")
381
- for pct in (0.25, 0.5, 0.9):
382
- required = np.argmax(coverage >= pct) + 1
383
- handle.write(f" - Top {required:4d} dims explain {pct:.0%} of energy\n")
384
-
385
- handle.write("\nScores = mean absolute activation over frames/batch.\n")
386
-
387
-
388
- def main():
389
- args = parse_args()
390
- video_abs = os.path.abspath(args.video)
391
- ckpt_abs = os.path.abspath(args.checkpoint)
392
- out_dir = ensure_dir(args.output_dir)
393
-
394
- if not os.path.exists(video_abs):
395
- raise FileNotFoundError(f"Video not found: {video_abs}")
396
- if not os.path.exists(ckpt_abs):
397
- raise FileNotFoundError(f"Checkpoint not found: {ckpt_abs}")
398
-
399
- device = prepare_device(args.device)
400
- print(f"[INFO] Using device: {device}")
401
-
402
- state_dict = load_checkpoint(ckpt_abs, device)
403
- video2pose = Video2Pose(INPUT_DIMS).to(device)
404
- load_video2pose_weights(video2pose, state_dict)
405
- projector = PadMatch(sum(INPUT_DIMS.values()), 2048).to(device)
406
- load_padmatch_weights(projector, state_dict)
407
-
408
- frames = load_and_process_video(video_abs, args.num_frames).unsqueeze(0).to(device) # [1, F, 3, 224, 224]
409
-
410
- with torch.no_grad():
411
- pose_dict = video2pose(frames)
412
- pose_concat = torch.cat([pose_dict[ptype] for ptype in POSE_TYPE_ORDER if ptype in pose_dict], dim=-1)
413
- B, F, D = pose_concat.shape
414
- pose_flat = pose_concat.reshape(B * F, D)
415
- pose_2048 = projector(pose_flat).view(B, F, -1)
416
- np.save(out_dir / "pose_2048.npy", pose_2048.cpu().numpy())
417
-
418
- scores, normalized = compute_importance(pose_2048)
419
- save_csv(scores, normalized, out_dir / "dimension_scores.csv")
420
-
421
- topk = min(args.topk, scores.shape[0])
422
- top_indices = np.argsort(scores)[::-1][:topk]
423
- plot_top_dimensions(scores, top_indices, out_dir / "top_dimensions.png")
424
- plot_heatmap(normalized, out_dir / "dimension_heatmap.png")
425
- coverage = plot_cumulative(scores, out_dir / "cumulative_importance.png")
426
- write_report(video_abs, ckpt_abs, scores, normalized, coverage, top_indices, out_dir / "analysis_report.txt")
427
-
428
- meta = {
429
- "video": video_abs,
430
- "checkpoint": ckpt_abs,
431
- "num_frames": args.num_frames,
432
- "device": str(device),
433
- "top_dimensions": top_indices.tolist(),
434
- }
435
- with open(out_dir / "metadata.json", "w", encoding="utf-8") as handle:
436
- json.dump(meta, handle, indent=2)
437
-
438
- print(f"[INFO] Analysis complete. Artifacts saved to: {out_dir}")
439
-
440
-
441
- if __name__ == "__main__":
442
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/regenerate_visualizations.py DELETED
@@ -1,122 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Regenerate visualization assets (using the latest attention_analysis.py).
4
-
5
- Usage:
6
- python regenerate_visualizations.py <detailed_prediction_dir> <video_path>
7
-
8
- Example:
9
- python regenerate_visualizations.py detailed_prediction_20251226_161117 ./eval/tiny_test_data/videos/632051.mp4
10
- """
11
-
12
- import sys
13
- import os
14
- from pathlib import Path
15
-
16
- # 添加项目根目录到path
17
- SCRIPT_DIR = Path(__file__).parent.parent
18
- sys.path.insert(0, str(SCRIPT_DIR))
19
-
20
- from eval.attention_analysis import AttentionAnalyzer
21
- import numpy as np
22
-
23
-
24
- def regenerate_sample_visualizations(sample_dir, video_path):
25
- """Regenerate every visualization asset for a single sample directory."""
26
- sample_dir = Path(sample_dir)
27
-
28
- if not sample_dir.exists():
29
- print(f"Error: sample directory not found: {sample_dir}")
30
- return False
31
-
32
- # 加载数据
33
- attn_file = sample_dir / "attention_weights.npy"
34
- trans_file = sample_dir / "translation.txt"
35
-
36
- if not attn_file.exists() or not trans_file.exists():
37
- print(f" Skipping {sample_dir.name}: required files are missing")
38
- return False
39
-
40
- # 读取数据
41
- attention_weights = np.load(attn_file)
42
- with open(trans_file, 'r') as f:
43
- lines = f.readlines()
44
- # Prefer the translation following the "Clean:" line
45
- translation = None
46
- for line in lines:
47
- if line.startswith('Clean:'):
48
- translation = line.replace('Clean:', '').strip()
49
- break
50
- if translation is None:
51
- translation = lines[0].strip() # fallback
52
-
53
- # Determine feature count (video_frames)
54
- if len(attention_weights.shape) == 4:
55
- video_frames = attention_weights.shape[3]
56
- elif len(attention_weights.shape) == 3:
57
- video_frames = attention_weights.shape[2]
58
- else:
59
- video_frames = attention_weights.shape[1]
60
-
61
- print(f" Sample: {sample_dir.name}")
62
- print(f" Attention shape: {attention_weights.shape}")
63
- print(f" Translation: {translation}")
64
- print(f" Features: {video_frames}")
65
-
66
- # 创建分析器
67
- analyzer = AttentionAnalyzer(
68
- attentions=attention_weights,
69
- translation=translation,
70
- video_frames=video_frames,
71
- video_path=str(video_path) if video_path else None
72
- )
73
-
74
- # Regenerate frame_alignment.png (with original-frame layer)
75
- print(" Regenerating frame_alignment.png...")
76
- analyzer.plot_frame_alignment(sample_dir / "frame_alignment.png")
77
-
78
- # Regenerate gloss_to_frames.png (feature index overlay)
79
- if video_path and Path(video_path).exists():
80
- print(" Regenerating gloss_to_frames.png...")
81
- try:
82
- analyzer.generate_gloss_to_frames_visualization(sample_dir / "gloss_to_frames.png")
83
- except Exception as e:
84
- print(f" Warning: failed to create gloss_to_frames.png: {e}")
85
-
86
- return True
87
-
88
-
89
- def main():
90
- if len(sys.argv) < 2:
91
- print("Usage: python regenerate_visualizations.py <detailed_prediction_dir> [<video_path>]")
92
- print("\nExample:")
93
- print(" python regenerate_visualizations.py detailed_prediction_20251226_161117 ./eval/tiny_test_data/videos/632051.mp4")
94
- sys.exit(1)
95
-
96
- pred_dir = Path(sys.argv[1])
97
- video_path = Path(sys.argv[2]) if len(sys.argv) > 2 else None
98
-
99
- if not pred_dir.exists():
100
- print(f"Error: detailed prediction directory not found: {pred_dir}")
101
- sys.exit(1)
102
-
103
- if video_path and not video_path.exists():
104
- print(f"Warning: video file not found, disabling video overlays: {video_path}")
105
- video_path = None
106
-
107
- print("Regenerating visualizations:")
108
- print(f" Detailed prediction dir: {pred_dir}")
109
- print(f" Video path: {video_path if video_path else 'N/A'}")
110
- print()
111
-
112
- # 处理所有样本
113
- success_count = 0
114
- for sample_dir in sorted([d for d in pred_dir.iterdir() if d.is_dir()]):
115
- if regenerate_sample_visualizations(sample_dir, video_path):
116
- success_count += 1
117
-
118
- print(f"\n✓ Done! Successfully processed {success_count} sample(s)")
119
-
120
-
121
- if __name__ == "__main__":
122
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/sacrebleu.py DELETED
The diff for this file is too large to render. See raw diff
 
plugins/SignX/eval/simple_benchmark.sh DELETED
@@ -1,188 +0,0 @@
1
- #!/bin/bash
2
- # 简单的效率基准测试 - 测量真实的推理时间和功耗
3
- set -e
4
-
5
- GREEN='\033[0;32m'
6
- BLUE='\033[0;34m'
7
- YELLOW='\033[1;33m'
8
- NC='\033[0m'
9
-
10
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
11
- PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
12
- OUTPUT_DIR="${PROJECT_ROOT}/benchmark_results"
13
- mkdir -p "$OUTPUT_DIR"
14
-
15
- echo ""
16
- echo "======================================================================"
17
- echo " SignX Efficiency Benchmark (Simple Version)"
18
- echo "======================================================================"
19
- echo ""
20
-
21
- # 激活conda
22
- CONDA_BASE=$(conda info --base 2>/dev/null || echo "")
23
- source "${CONDA_BASE}/etc/profile.d/conda.sh"
24
-
25
- # ============================================================
26
- # 1. Latent-only: 只测量 SLTUNET 推理时间
27
- # ============================================================
28
- echo -e "${BLUE}[1/2] Benchmarking Latent-only (SLTUNET only)${NC}"
29
- echo ""
30
-
31
- conda activate slt_tf1
32
- export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
33
-
34
- # 创建配置文件(使用benchmark专用配置,禁用pose assistance和详细输出)
35
- cat > /tmp/latent_only_config.py <<'EOF'
36
- {
37
- 'sign_cfg': 'smkd/asllrp_baseline_benchmark.yaml',
38
- 'gloss_path': 'smkd/asllrp/gloss_dict.npy',
39
- 'smkd_model_path': 'smkd/work_dir第一次训练的基线/asllrp_smkd/best_model.pt',
40
- 'img_test_file': 'smkd/work_dir第一次训练的基线/asllrp_smkd/test.h5',
41
- 'src_test_file': 'preprocessed-asllrp/test.bpe.gloss',
42
- 'tgt_test_file': 'preprocessed-asllrp/test.bpe.gloss',
43
- 'src_vocab_file': 'preprocessed-asllrp/vocab.asllrp',
44
- 'tgt_vocab_file': 'preprocessed-asllrp/vocab.asllrp',
45
- 'src_codes': 'preprocessed-asllrp/asllrp.bpe',
46
- 'tgt_codes': 'preprocessed-asllrp/asllrp.bpe',
47
- 'output_dir': 'checkpoints_asllrp第一次训练的基线',
48
- 'test_output': '/tmp/latent_only_output.txt',
49
- 'eval_batch_size': 10,
50
- 'gpus': [0],
51
- 'remove_bpe': True,
52
- 'collect_attention_weights': False, # 禁用attention收集以加速基准测试
53
- }
54
- EOF
55
-
56
- echo "Running latent-only inference..."
57
-
58
- # 记录GPU功耗(后台进程)
59
- nvidia-smi --query-gpu=power.draw --format=csv,noheader,nounits -l 1 > /tmp/power_latent.log &
60
- POWER_PID=$!
61
-
62
- # 测量推理时间
63
- START=$(date +%s.%N)
64
- cd "$PROJECT_ROOT"
65
- python run.py --mode test --config /tmp/latent_only_config.py 2>&1 | grep -E "(BLEU|Evaluating)" || true
66
- END=$(date +%s.%N)
67
-
68
- # 停止功耗监控
69
- kill $POWER_PID 2>/dev/null || true
70
-
71
- # 计算结果
72
- LATENT_TIME=$(echo "$END - $START" | bc)
73
- LATENT_POWER=$(awk '{ sum += $1; n++ } END { if (n > 0) print sum / n }' /tmp/power_latent.log)
74
-
75
- # 计算FPS(使用test集的样本数)
76
- NUM_SAMPLES=$(wc -l < "$PROJECT_ROOT/preprocessed-asllrp/test.bpe.gloss")
77
- LATENT_FPS=$(echo "scale=2; $NUM_SAMPLES / $LATENT_TIME" | bc)
78
-
79
- echo -e "${GREEN}✓ Latent-only完成${NC}"
80
- echo " 推理时间: ${LATENT_TIME}s"
81
- echo " 平均功耗: ${LATENT_POWER}W"
82
- echo " FPS: $LATENT_FPS"
83
- echo ""
84
-
85
- # ============================================================
86
- # 2. SMKD Feature Extraction: 测量视频特征提取时间
87
- # ============================================================
88
- echo -e "${BLUE}[2/3] Benchmarking SMKD Feature Extraction${NC}"
89
- echo ""
90
-
91
- # 运行 SMKD 基准测试脚本
92
- if [ -f "$SCRIPT_DIR/benchmark_smkd.sh" ]; then
93
- bash "$SCRIPT_DIR/benchmark_smkd.sh" 2>&1 | grep -E "(FPS|Power|Time)" | tail -3 > /tmp/smkd_results.txt
94
-
95
- # 提取结果
96
- SMKD_FPS=$(grep "FPS:" /tmp/smkd_results.txt | awk '{print $2}')
97
- SMKD_POWER=$(grep "Power:" /tmp/smkd_results.txt | awk '{print $2}' | sed 's/W//')
98
-
99
- echo -e "${GREEN}✓ SMKD Feature Extraction完成${NC}"
100
- echo " FPS: $SMKD_FPS"
101
- echo " 功耗: ${SMKD_POWER}W"
102
- echo ""
103
- else
104
- echo "Warning: benchmark_smkd.sh not found, skipping SMKD test"
105
- SMKD_FPS="N/A"
106
- SMKD_POWER="N/A"
107
- fi
108
-
109
- # ============================================================
110
- # 3. Full Pipeline: 测量 inference.sh 的总时间
111
- # ============================================================
112
- echo -e "${BLUE}[3/3] Benchmarking Full Pipeline (SMKD + SLTUNET)${NC}"
113
- echo ""
114
-
115
- TEST_VIDEO="${PROJECT_ROOT}/eval/tiny_test_data/videos/666.mp4"
116
-
117
- if [ ! -f "$TEST_VIDEO" ]; then
118
- echo "Warning: Test video not found, skipping full pipeline test"
119
- else
120
- echo "Running full pipeline inference..."
121
-
122
- # 记录GPU功耗
123
- nvidia-smi --query-gpu=power.draw --format=csv,noheader,nounits -l 1 > /tmp/power_full.log &
124
- POWER_PID=$!
125
-
126
- # 测量推理时间
127
- START=$(date +%s.%N)
128
- cd "$PROJECT_ROOT"
129
- bash inference.sh "$TEST_VIDEO" /tmp/full_pipeline_output.txt 2>&1 | grep -E "(完成|BLEU)" || true
130
- END=$(date +%s.%N)
131
-
132
- # 停止功耗监控
133
- kill $POWER_PID 2>/dev/null || true
134
-
135
- # 计算结果
136
- FULL_TIME=$(echo "$END - $START" | bc)
137
- FULL_POWER=$(awk '{ sum += $1; n++ } END { if (n > 0) print sum / n }' /tmp/power_full.log)
138
- FULL_FPS=$(echo "scale=2; 1 / $FULL_TIME" | bc) # 单个视频
139
-
140
- echo -e "${GREEN}�� Full Pipeline完成${NC}"
141
- echo " 推理时间: ${FULL_TIME}s"
142
- echo " 平均功耗: ${FULL_POWER}W"
143
- echo " FPS: $FULL_FPS"
144
- echo ""
145
- fi
146
-
147
- # ============================================================
148
- # 4. 生成LaTeX表格
149
- # ============================================================
150
- echo -e "${BLUE}[4/4] Generating LaTeX Table${NC}"
151
- echo ""
152
-
153
- cat > "${OUTPUT_DIR}/efficiency_comparison_table.tex" <<EOF
154
- \begin{table}[t]
155
- \centering
156
- \caption{\textbf{Inference Efficiency on ASLLRP:} SignX achieves real-time performance by operating in latent space.}
157
- \label{tab:efficiency}
158
- \begin{tabular}{lcc}
159
- \toprule
160
- Method & FPS \$\\uparrow\$ & Power (W) \$\\downarrow\$ \\\\
161
- \midrule
162
- SignX (Full Pipeline) & ${FULL_FPS:-N/A} & ${FULL_POWER:-N/A} \\\\
163
- SignX (SMKD Feature Extraction) & ${SMKD_FPS:-N/A} & ${SMKD_POWER:-N/A} \\\\
164
- SignX (Latent-only) & $LATENT_FPS & $LATENT_POWER \\\\
165
- \bottomrule
166
- \end{tabular}
167
- \end{table}
168
- EOF
169
-
170
- echo "======================================================================"
171
- echo " Benchmark Results"
172
- echo "======================================================================"
173
- echo ""
174
- echo "Configuration | FPS | Power (W)"
175
- echo "-----------------------------------|----------|----------"
176
- echo "Full Pipeline | ${FULL_FPS:-N/A} | ${FULL_POWER:-N/A}"
177
- echo "SMKD Feature Extraction (视频→特征) | ${SMKD_FPS:-N/A} | ${SMKD_POWER:-N/A}"
178
- echo "Latent-only (特征→gloss) | $LATENT_FPS | $LATENT_POWER"
179
- echo ""
180
- echo -e "${GREEN}✓ LaTeX table saved to: ${OUTPUT_DIR}/efficiency_comparison_table.tex${NC}"
181
- echo ""
182
-
183
- # 清理
184
- rm -f /tmp/latent_only_config.py /tmp/power_*.log /tmp/latent_only_output.txt /tmp/full_pipeline_output.txt /tmp/smkd_results.txt
185
- rm -rf /tmp/detailed_* # 删除任何详细输出目录
186
-
187
- echo -e "${GREEN}✓ Benchmark complete!${NC}"
188
- echo ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/README.md DELETED
@@ -1,86 +0,0 @@
1
- # Tiny Test Dataset
2
-
3
- 这是一个包含10个ASLLRP测试样本的小型数据集,用于快速测试推理脚本。
4
-
5
- ## 内容
6
-
7
- - **videos/**: 10个测试视频(MP4格式)
8
- - **ground_truth.txt**: Ground truth gloss标注
9
- - **video_list.txt**: 视频文件名列表
10
-
11
- ## 统计信息
12
-
13
- - 样本数量: 10
14
- - 数据来源: ASLLRP测试集(前10个样本)
15
-
16
- ## Ground Truth 格式
17
-
18
- ```
19
- <video_id>\t<gloss_sequence>
20
- ```
21
-
22
- ## 使用方法
23
-
24
- ### 测试单个视频
25
-
26
- ```bash
27
- # 使用快速推理
28
- cd ../../../
29
- python inference.py --video eval/tiny_test_data/videos/60484391.mp4
30
-
31
- # 使用完整pipeline
32
- ./inference.sh eval/tiny_test_data/videos/60484391.mp4
33
- ```
34
-
35
- ### 批量测试
36
-
37
- ```bash
38
- # 测试所有10个视频
39
- for video in eval/tiny_test_data/videos/*.mp4; do
40
- echo "Testing: $video"
41
- python inference.py --video "$video" --output "results/$(basename $video .mp4).txt"
42
- done
43
- ```
44
-
45
- ### 计算WER
46
-
47
- ```bash
48
- # 使用eval/metrics.py计算WER
49
- python eval/metrics.py \
50
- --task slr \
51
- --hypothesis predictions.txt \
52
- --reference eval/tiny_test_data/ground_truth.txt
53
- ```
54
-
55
- ## 样本列表
56
-
57
- 1. **60484391.mp4**
58
- - Gloss: `fs-GRUNT ACCEPT IN AREA TALK HEAR/LISTEN CULTURE THROUGH SO-SO NOT EXACT`
59
-
60
- 2. **666.mp4**
61
- - Gloss: `NEW STUDENT UP-TO-NOW NONE/NOTHING MEET NONE/NOTHING`
62
-
63
- 3. **47609690.mp4**
64
- - Gloss: `HAVE CULTURE VOICE-RANGE fs-RANGE CANNOT ENTER DCL:5"emit waste" FUTURE 5"surpri...`
65
-
66
- 4. **11945625.mp4**
67
- - Gloss: `IX-1p BABY BORN IX-1p WANT GIFT ns-IRELAND NAME BUT IX IX-1p FATHER IX WANT GIFT...`
68
-
69
- 5. **26826234.mp4**
70
- - Gloss: `IX ns-fs-JOHN GO-OUT WITH ns-fs-MARY NOT DRIVE 5"wave no" SCL:U-L"person walking...`
71
-
72
- 6. **51694177.mp4**
73
- - Gloss: `GO-OUT DATE/DESSERT PROGRESS POSS HOME ENTER TOILET fs-CODA WOMAN LOOK OUT POSS ...`
74
-
75
- 7. **97998032.mp4**
76
- - Gloss: `BOX/ROOM BIG`
77
-
78
- 8. **632051.mp4**
79
- - Gloss: `#IF FRIEND GROUP/TOGETHER GO-OUT PARTY IX-1p JOIN IX-1p`
80
-
81
- 9. **63826969.mp4**
82
- - Gloss: `SHOW ns-fs-BAUMAN BETWEEN/SHARE POSS EXPERIENCE IN IX fs-LOCKER+BOX/ROOM`
83
-
84
- 10. **46272693.mp4**
85
- - Gloss: `IDEA fs-OF VOICE VOICE-RANGE fs-RANGE PLACE PERMIT BUT STILL MUST VOICE-RANGE fs...`
86
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/171921.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b55f3fae16c90ecd7e799d2515aeea9af00df4efad003d84e6b0aba1a3527822
3
- size 102121
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/173238.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:48c605e2c0dbd04fe25871a7b2e270615d02a198567f3f903c3ae7da68bcf8ca
3
- size 98921
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/173745.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:289b2fa3e751823c99b78a40e38ff799dfb7e28cdc53053b045c5e9dbb15d7fb
3
- size 494802
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/23880856.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:555d737baa311faa5ff33afa7d8a6ca4c3090c41e8c47eaa39569e493dce7282
3
- size 87354
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/23881350.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:910a66cdb56e3099362c109e0d5eca9a802d84384447450361a17fd1eadd2437
3
- size 956456
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/31655975.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:be37c2b598e44b89f31c5f716b8e58953f222b1da7e5d78043a7bdf33df9747a
3
- size 632842
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/31657848.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a7959393ce0fb59a832113b12966203777bef8859c4f21b9b4401b5621f5bb80
3
- size 79933
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/3378265.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0e91b2fbe52346403e109933052e53dcf3e172b6a638ccc87eb72507d2ab0ba3
3
- size 739857
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/3381121.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:571fea555cf82d20e3ccb155759389414f2e214b9a5aa82b08a022a47395adca
3
- size 923026
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/4235359.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:3255cd64085e24f93527adc5159b457583c2da9dfcc21472e370254c6f3b0812
3
- size 62516
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/4236171.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:608e2c41f8c445ecbf08bc22321c7e50c69999108755d9a4d2c4d784dbc20dc8
3
- size 529850
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/50802118.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0c3db765ef374d1247d8d4a90ec00a01833fda7d71c171ec774e675b092674a9
3
- size 90142
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/5597316.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a40b162f904048599a7b3ce04d439038afcc8f8c8a70bcd15c6faae00ad495c0
3
- size 88439
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/6185086.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:ea4e7811e3452b5c4a36ef84aa1bad600af68b5b5d2a29f130a42907a27f29c3
3
- size 724598
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/6185381.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:c35bdbf4087677ffb0b9d348feda0d5f45f53549f7cc6c3e8680303a6562b3b5
3
- size 632143
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/619048.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:011b44c741b104d2aa07efb0df33df970e1ece034a7915590c68a9716d843f52
3
- size 135468
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/629983.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:8bb7fd93838b5c931ac89f00adf62c08be3e45f0b90803126035c924bb7e2bde
3
- size 90085
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/634818.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6a7d034c6da97babb440de4eb8dc598e243141a9a8ed3b9ca3b6b222841eea6d
3
- size 523852
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/63579.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:21c8fa94f8c3bc8f9a771ed47b646ecc2e02c0345bedf37ea3b803e9d9d8293c
3
- size 52159
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7454155.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:bb47173044695c44654232f7fed41810e08f999280d066a84c88c83cdc3b9221
3
- size 66481
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7566726.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:79376e879cd691efe05a10db610d97c3a06d33f3d44dafedeaddabb1a00cdfef
3
- size 54623
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7569669.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:e756f0fcb4bfa4a64f433dc11309a4752fa202884310c72f5deb64923e10d5a4
3
- size 80089
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7701925.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:2508adc6e401bcf01be6b1d3599bb047db0c5c90b26199bb9bfa32f49d17f52a
3
- size 88745
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7710510.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6307afb97fa84097c574ded2cbae7083e6bf45493e5c9683fc5fe78aba29cf54
3
- size 109316
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7981884.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:35b84894607a914e677d35b22b977a06a20018398381b9af514c1e551b608057
3
- size 690566
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7982378.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:112e37f2307ba072084e9b56519b68555a4affbf3543ca6fe71ae2151e54d5ac
3
- size 755230
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/7983362.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:64341d796bd95627ef2d141fbc36bf025778461dc8670cf39b3c358ddf5be036
3
- size 109429
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/83940254.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:e821e90296446a5ef9b2013f636cdf95d1782e01f3420653c40b024e53513614
3
- size 86808
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/83940846.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:f5d5a2d3e345ed478ac34f60e1dd25e2affdc8eaf021a00d98df5a1559fa068e
3
- size 64648
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/83941734.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:e74082b54128ed094006d64034886f14ec9be2247525ad59d44f27f9bbd58897
3
- size 786211
 
 
 
 
plugins/SignX/eval/tiny_test_data_for_ASLLRP/good_videos/8394388.mp4 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0338d7524771d4709d0e34efa92e653afb80b8c9480fbdd16b525067bb265f06
3
- size 646955