FangSen9000 commited on
Commit
9f9e779
·
1 Parent(s): 5fb3ca1

The reasoning has been converted into English.

Browse files
Files changed (39) hide show
  1. SignX/eval/attention_analysis.py +120 -138
  2. SignX/eval/extract_attention_keyframes.py +39 -54
  3. SignX/eval/generate_feature_mapping.py +23 -23
  4. SignX/eval/generate_interactive_alignment.py +25 -25
  5. SignX/eval/regenerate_visualizations.py +23 -23
  6. SignX/inference.sh +112 -121
  7. SignX/inference_output/detailed_prediction_20260102_180915/23881350/attention_keyframes/keyframes_index.txt +0 -27
  8. SignX/inference_output/detailed_prediction_20260102_180915/23881350/frame_alignment.json +0 -59
  9. SignX/inference_output/detailed_prediction_20260102_180915/23881350/translation.txt +0 -3
  10. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/analysis_report.txt +17 -14
  11. SignX/inference_output/detailed_prediction_20260102_182015/632051/attention_heatmap.pdf +0 -0
  12. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/attention_heatmap.png +2 -2
  13. SignX/inference_output/detailed_prediction_20260102_182015/632051/attention_keyframes/keyframes_index.txt +35 -0
  14. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/attention_weights.npy +2 -2
  15. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/debug_video_path.txt +1 -1
  16. SignX/inference_output/detailed_prediction_20260102_182015/632051/feature_frame_mapping.json +176 -0
  17. SignX/inference_output/detailed_prediction_20260102_182015/632051/frame_alignment.json +86 -0
  18. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/frame_alignment.pdf +0 -0
  19. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/frame_alignment.png +2 -2
  20. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/frame_alignment_short.pdf +0 -0
  21. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/frame_alignment_short.png +2 -2
  22. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/gloss_to_frames.png +2 -2
  23. SignX/inference_output/detailed_prediction_20260102_182015/632051/interactive_alignment.html +579 -0
  24. SignX/inference_output/detailed_prediction_20260102_182015/632051/translation.txt +3 -0
  25. SignX/inference_output/detailed_prediction_20260102_183038/97998032/analysis_report.txt +42 -0
  26. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_183038/97998032}/attention_heatmap.pdf +0 -0
  27. SignX/inference_output/detailed_prediction_20260102_183038/97998032/attention_heatmap.png +3 -0
  28. SignX/inference_output/detailed_prediction_20260102_183038/97998032/attention_keyframes/keyframes_index.txt +39 -0
  29. SignX/inference_output/detailed_prediction_20260102_183038/97998032/attention_weights.npy +3 -0
  30. SignX/inference_output/detailed_prediction_20260102_183038/97998032/debug_video_path.txt +4 -0
  31. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_183038/97998032}/feature_frame_mapping.json +19 -37
  32. SignX/inference_output/detailed_prediction_20260102_183038/97998032/frame_alignment.json +77 -0
  33. SignX/inference_output/detailed_prediction_20260102_183038/97998032/frame_alignment.pdf +0 -0
  34. SignX/inference_output/detailed_prediction_20260102_183038/97998032/frame_alignment.png +3 -0
  35. SignX/inference_output/detailed_prediction_20260102_183038/97998032/frame_alignment_short.pdf +0 -0
  36. SignX/inference_output/detailed_prediction_20260102_183038/97998032/frame_alignment_short.png +3 -0
  37. SignX/inference_output/detailed_prediction_20260102_183038/97998032/gloss_to_frames.png +3 -0
  38. SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_183038/97998032}/interactive_alignment.html +9 -9
  39. SignX/inference_output/detailed_prediction_20260102_183038/97998032/translation.txt +3 -0
SignX/eval/attention_analysis.py CHANGED
@@ -1,14 +1,14 @@
1
  #!/usr/bin/env python3
2
  """
3
- Attention权重分析和可视化模块
4
 
5
- 功能:
6
- 1. 解析attention权重数据
7
- 2. 计算每个词对应的视频帧范围
8
- 3. 生成可视化图表(热图、对齐图、时间线)
9
- 4. 保存详细分析报告
10
 
11
- 使用示例:
12
  from eval.attention_analysis import AttentionAnalyzer
13
 
14
  analyzer = AttentionAnalyzer(
@@ -17,7 +17,6 @@ Attention权重分析和可视化模块
17
  video_frames=100
18
  )
19
 
20
- # 生成所有可视化
21
  analyzer.generate_all_visualizations(output_dir="results/")
22
  """
23
 
@@ -32,37 +31,37 @@ from datetime import datetime
32
 
33
 
34
  class AttentionAnalyzer:
35
- """Attention权重分析器"""
36
 
37
  def __init__(self, attentions, translation, video_frames, beam_sequences=None, beam_scores=None,
38
  video_path=None, original_video_fps=30, original_video_total_frames=None):
39
  """
40
  Args:
41
  attentions: numpy array, shape [time_steps, batch, beam, src_len]
42
- [time_steps, src_len] (已提取最佳beam)
43
- translation: str, 翻译结果(BPE已移除)
44
- video_frames: int, SMKD特征序列帧数
45
- beam_sequences: list, 所有beam的序列 (可选)
46
- beam_scores: list, 所有beam的分数 (可选)
47
- video_path: str, 原始视频文件路径 (可选,用于提取视频帧)
48
- original_video_fps: int, 原始视频FPS (默认30)
49
- original_video_total_frames: int, 原始视频总帧数 (可选,如果不提供则从视频中读取)
50
  """
51
  self.attentions = attentions
52
  self.translation = translation
53
  self.words = translation.split()
54
- self.video_frames = video_frames # SMKD特征帧数
55
  self.beam_sequences = beam_sequences
56
  self.beam_scores = beam_scores
57
 
58
- # 原始视频相关
59
  self.video_path = video_path
60
  self.original_video_fps = original_video_fps
61
  self.original_video_total_frames = original_video_total_frames
62
  self._cv2_module = None
63
  self._cv2_checked = False
64
 
65
- # 如果提供了视频路径但没有提供总帧数,尝试读取
66
  if video_path and original_video_total_frames is None:
67
  metadata = self._read_video_metadata()
68
  if metadata:
@@ -70,9 +69,9 @@ class AttentionAnalyzer:
70
  if metadata.get('fps'):
71
  self.original_video_fps = metadata['fps']
72
  elif video_path:
73
- print(f"Warning: 无法解析视频信息, Gloss-to-Frames 可视化将无法对齐实际帧 ({video_path})")
74
 
75
- # 提取最佳路径的attention (batch=0, beam=0)
76
  if len(attentions.shape) == 4:
77
  self.attn_best = attentions[:, 0, 0, :] # [time, src_len]
78
  elif len(attentions.shape) == 3:
@@ -80,32 +79,22 @@ class AttentionAnalyzer:
80
  else:
81
  self.attn_best = attentions # [time, src_len]
82
 
83
- # 计算词-帧对应关系
84
  self.word_frame_ranges = self._compute_word_frame_ranges()
85
  self.frame_attention_strength = self._compute_frame_attention_strength()
86
 
87
  def _compute_word_frame_ranges(self):
88
  """
89
- 计算每个词对应的主要视频帧范围
90
 
91
  Returns:
92
- list of dict: [
93
- {
94
- 'word': str,
95
- 'start_frame': int,
96
- 'end_frame': int,
97
- 'peak_frame': int,
98
- 'avg_attention': float,
99
- 'confidence': str
100
- },
101
- ...
102
- ]
103
  """
104
  word_ranges = []
105
 
106
  for word_idx, word in enumerate(self.words):
107
  if word_idx >= self.attn_best.shape[0]:
108
- # 超出attention范围
109
  word_ranges.append({
110
  'word': word,
111
  'start_frame': 0,
@@ -118,11 +107,11 @@ class AttentionAnalyzer:
118
 
119
  attn_weights = self.attn_best[word_idx, :]
120
 
121
- # 找到权重最高的帧
122
  peak_frame = int(np.argmax(attn_weights))
123
  peak_weight = attn_weights[peak_frame]
124
 
125
- # 计算显著帧范围(权重 >= 最大值的90%
126
  threshold = peak_weight * 0.9
127
  significant_frames = np.where(attn_weights >= threshold)[0]
128
 
@@ -135,7 +124,7 @@ class AttentionAnalyzer:
135
  end_frame = peak_frame
136
  avg_weight = float(peak_weight)
137
 
138
- # 判断置信度
139
  if avg_weight > 0.5:
140
  confidence = 'high'
141
  elif avg_weight > 0.2:
@@ -204,32 +193,29 @@ class AttentionAnalyzer:
204
 
205
  def generate_all_visualizations(self, output_dir):
206
  """
207
- 生成所有可视化图表
208
-
209
- Args:
210
- output_dir: 输出目录路径
211
  """
212
  output_dir = Path(output_dir)
213
  output_dir.mkdir(parents=True, exist_ok=True)
214
 
215
- print(f"\n生成可视化图表到: {output_dir}")
216
 
217
- # 1. Attention热图
218
  self.plot_attention_heatmap(output_dir / "attention_heatmap.png")
219
 
220
- # 2. 帧对齐图
221
  self.plot_frame_alignment(output_dir / "frame_alignment.png")
222
 
223
- # 3. 保存数值数据
224
  self.save_alignment_data(output_dir / "frame_alignment.json")
225
 
226
- # 4. 保存详细报告
227
  self.save_text_report(output_dir / "analysis_report.txt")
228
 
229
- # 5. 保存numpy数据(供进一步分析)
230
  np.save(output_dir / "attention_weights.npy", self.attentions)
231
 
232
- # 6. Gloss-to-Frames可视化 (如果提供了视频路径)
233
  # Write debug info to file
234
  debug_file = output_dir / "debug_video_path.txt"
235
  with open(debug_file, 'w') as f:
@@ -251,36 +237,36 @@ class AttentionAnalyzer:
251
  else:
252
  print("[DEBUG] Skipping gloss-to-frames visualization (no video path provided)")
253
 
254
- print(f"✓ 已生成 {len(list(output_dir.glob('*')))} 个文件")
255
 
256
  def plot_attention_heatmap(self, output_path):
257
- """生成Attention热图"""
258
  try:
259
  import matplotlib
260
  matplotlib.use('Agg')
261
  import matplotlib.pyplot as plt
262
  except ImportError:
263
- print(" 跳过热图: matplotlib未安装")
264
  return
265
 
266
  fig, ax = plt.subplots(figsize=(14, 8))
267
 
268
- # 绘制热图
269
  im = ax.imshow(self.attn_best.T, cmap='hot', aspect='auto',
270
  interpolation='nearest', origin='lower')
271
 
272
- # 设置标签
273
  ax.set_xlabel('Generated Word Index', fontsize=13)
274
  ax.set_ylabel('Video Frame Index', fontsize=13)
275
  ax.set_title('Cross-Attention Weights\n(Decoder → Video Frames)',
276
  fontsize=15, pad=20, fontweight='bold')
277
 
278
- # 词标签
279
  if len(self.words) <= self.attn_best.shape[0]:
280
  ax.set_xticks(range(len(self.words)))
281
  ax.set_xticklabels(self.words, rotation=45, ha='right', fontsize=10)
282
 
283
- # 添加颜色条
284
  cbar = plt.colorbar(im, ax=ax, label='Attention Weight', fraction=0.046, pad=0.04)
285
  cbar.ax.tick_params(labelsize=10)
286
 
@@ -294,7 +280,7 @@ class AttentionAnalyzer:
294
  print(f" ✓ {output_path.name} (PDF copy saved)")
295
 
296
  def plot_frame_alignment(self, output_path):
297
- """生成帧对齐可视化"""
298
  try:
299
  import matplotlib
300
  matplotlib.use('Agg')
@@ -302,7 +288,7 @@ class AttentionAnalyzer:
302
  import matplotlib.patches as patches
303
  from matplotlib.gridspec import GridSpec
304
  except ImportError:
305
- print(" 跳过对齐图: matplotlib未安装")
306
  return
307
 
308
  output_path = Path(output_path)
@@ -347,7 +333,7 @@ class AttentionAnalyzer:
347
  fig = plt.figure(figsize=(18, 7.5))
348
  gs = GridSpec(2, 1, height_ratios=[4, 1], hspace=0.32)
349
 
350
- # === 上图: -帧对齐 ===
351
  ax1 = fig.add_subplot(gs[0])
352
  colors = plt.cm.tab20(np.linspace(0, 1, max(len(self.words), 20)))
353
 
@@ -384,7 +370,7 @@ class AttentionAnalyzer:
384
  ax1.set_yticks(range(len(self.words)))
385
  ax1.set_yticklabels([w['word'] for w in self.word_frame_ranges], fontsize=10)
386
 
387
- # === 中图1: Latent timeline ===
388
  ax2 = fig.add_subplot(gs[1])
389
  ax2.barh(0, self.video_frames, height=0.6, color='lightgray',
390
  edgecolor='black', linewidth=2)
@@ -481,7 +467,7 @@ class AttentionAnalyzer:
481
  render_alignment(short_path, latent_short_limit, orig_short_limit if orig_short_limit else orig_full_limit)
482
 
483
  def save_alignment_data(self, output_path):
484
- """保存帧对齐数据为JSON"""
485
  data = {
486
  'translation': self.translation,
487
  'words': self.words,
@@ -501,35 +487,35 @@ class AttentionAnalyzer:
501
  print(f" ✓ {output_path.name}")
502
 
503
  def save_text_report(self, output_path):
504
- """保存文本格式的详细报告"""
505
  with open(output_path, 'w', encoding='utf-8') as f:
506
  f.write("=" * 80 + "\n")
507
- f.write(" Sign Language Recognition - Attention分析报告\n")
508
  f.write("=" * 80 + "\n\n")
509
 
510
- f.write(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
511
 
512
- f.write("翻译结果:\n")
513
  f.write("-" * 80 + "\n")
514
  f.write(f"{self.translation}\n\n")
515
 
516
- f.write("视频信息:\n")
517
  f.write("-" * 80 + "\n")
518
- f.write(f"总帧数: {self.video_frames}\n")
519
- f.write(f"词数量: {len(self.words)}\n\n")
520
 
521
- f.write("Attention权重信息:\n")
522
  f.write("-" * 80 + "\n")
523
- f.write(f"形状: {self.attentions.shape}\n")
524
- f.write(f" - 解码步数: {self.attentions.shape[0]}\n")
525
  if len(self.attentions.shape) >= 3:
526
- f.write(f" - Batch大小: {self.attentions.shape[1]}\n")
527
  if len(self.attentions.shape) >= 4:
528
- f.write(f" - Beam大小: {self.attentions.shape[2]}\n")
529
- f.write(f" - 源序列长度: {self.attentions.shape[3]}\n")
530
  f.write("\n")
531
 
532
- f.write("-帧对应详情:\n")
533
  f.write("=" * 80 + "\n")
534
  f.write(f"{'No.':<5} {'Word':<20} {'Frames':<15} {'Peak':<8} {'Attn':<8} {'Conf':<10}\n")
535
  f.write("-" * 80 + "\n")
@@ -541,7 +527,7 @@ class AttentionAnalyzer:
541
 
542
  f.write("\n" + "=" * 80 + "\n")
543
 
544
- # 统计信息
545
  stats = {
546
  'avg_confidence': np.mean([w['avg_attention'] for w in self.word_frame_ranges]),
547
  'high': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'high'),
@@ -549,12 +535,12 @@ class AttentionAnalyzer:
549
  'low': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'low'),
550
  }
551
 
552
- f.write("\n统计摘要:\n")
553
  f.write("-" * 80 + "\n")
554
- f.write(f"平均attention权重: {stats['avg_confidence']:.3f}\n")
555
- f.write(f"高置信度词: {stats['high']} ({stats['high']/len(self.words)*100:.1f}%)\n")
556
- f.write(f"中置信度词: {stats['medium']} ({stats['medium']/len(self.words)*100:.1f}%)\n")
557
- f.write(f"低置信度词: {stats['low']} ({stats['low']/len(self.words)*100:.1f}%)\n")
558
  f.write("\n" + "=" * 80 + "\n")
559
 
560
  print(f" ✓ {output_path.name}")
@@ -562,34 +548,34 @@ class AttentionAnalyzer:
562
 
563
  def _map_feature_frame_to_original(self, feature_frame_idx):
564
  """
565
- SMKD特征帧索引映射到原始视频帧索引
566
 
567
  Args:
568
- feature_frame_idx: SMKD特征帧索引 (0-based)
569
 
570
  Returns:
571
- int: 原始视频帧索引,如果无法映射则返回None
572
  """
573
  if self.original_video_total_frames is None:
574
  return None
575
 
576
- # 计算降采样率
577
  downsample_ratio = self.original_video_total_frames / self.video_frames
578
 
579
- # 映射到原始视频帧
580
  original_frame_idx = int(feature_frame_idx * downsample_ratio)
581
 
582
  return min(original_frame_idx, self.original_video_total_frames - 1)
583
 
584
  def _extract_video_frames(self, frame_indices):
585
  """
586
- 从视频中提取指定索引的帧
587
 
588
  Args:
589
- frame_indices: list of int, 要提取的帧索引列表
590
 
591
  Returns:
592
- dict: {frame_idx: numpy_array}, 帧索引到图像数据的映射
593
  """
594
  if not self.video_path:
595
  return {}
@@ -601,7 +587,7 @@ class AttentionAnalyzer:
601
  return self._extract_frames_with_ffmpeg(frame_indices)
602
 
603
  def _get_cv2_module(self):
604
- """惰性加载cv2, 缓存导入结果"""
605
  if self._cv2_checked:
606
  return self._cv2_module
607
 
@@ -614,11 +600,11 @@ class AttentionAnalyzer:
614
  self._cv2_checked = True
615
 
616
  if self._cv2_module is None:
617
- print("Warning: opencv-python 未安装, 将尝试使用 ffmpeg 提取视频帧")
618
  return self._cv2_module
619
 
620
  def _extract_frames_with_cv2(self, cv2, frame_indices):
621
- """使用opencv提取视频帧"""
622
  frames = {}
623
  cap = cv2.VideoCapture(self.video_path)
624
 
@@ -637,15 +623,15 @@ class AttentionAnalyzer:
637
  return frames
638
 
639
  def _extract_frames_with_ffmpeg(self, frame_indices):
640
- """使用ffmpeg + Pillow提取视频帧(在opencv缺失时调用)"""
641
  if shutil.which("ffmpeg") is None:
642
- print("Warning: 未找到 ffmpeg, 无法提取视频帧")
643
  return {}
644
 
645
  try:
646
  from PIL import Image
647
  except ImportError:
648
- print("Warning: Pillow 未安装, 无法解码ffmpeg输出的图像")
649
  return {}
650
 
651
  frames = {}
@@ -669,26 +655,22 @@ class AttentionAnalyzer:
669
  image = Image.open(io.BytesIO(result.stdout)).convert("RGB")
670
  frames[frame_idx] = np.array(image)
671
  except subprocess.CalledProcessError as e:
672
- print(f"Warning: ffmpeg 提取帧 {frame_idx} 失败: {e}")
673
  except Exception as ex:
674
- print(f"Warning: 解码帧 {frame_idx} 失败: {ex}")
675
 
676
  if frames:
677
- print(f" ✓ 使用 ffmpeg 提取了 {len(frames)} ")
678
  else:
679
- print(" ⓘ ffmpeg 未能提取任何帧")
680
  return frames
681
 
682
  def generate_gloss_to_frames_visualization(self, output_path):
683
  """
684
- 生成 Gloss-to-Frames 可视化图像
685
- 布局: 每行对应一个gloss
686
- 列1: Gloss文本
687
- 列2: 相对时间和帧索引信息
688
- 列3: 该时间段内的视频帧缩略图
689
-
690
- Args:
691
- output_path: 输出图像路径
692
  """
693
  if not self.video_path:
694
  print(" ⓘ Skipping gloss-to-frames visualization (no video path provided)")
@@ -701,7 +683,7 @@ class AttentionAnalyzer:
701
  print("Warning: matplotlib not installed")
702
  return
703
 
704
- # 加载feature-to-frame mapping
705
  feature_mapping = None
706
  output_dir = Path(output_path).parent
707
  mapping_file = output_dir / "feature_frame_mapping.json"
@@ -713,53 +695,53 @@ class AttentionAnalyzer:
713
  except Exception as e:
714
  print(f" Warning: Failed to load feature mapping: {e}")
715
 
716
- # 收集所有需要提取的原始视频帧
717
  all_original_frames = set()
718
  for word_info in self.word_frame_ranges:
719
- # 特征帧范围
720
  start_feat = word_info['start_frame']
721
  end_feat = word_info['end_frame']
722
 
723
- # 映射整个feature范围到原始视频帧
724
  if feature_mapping:
725
- # 使用实际的feature mapping
726
  for feat_idx in range(start_feat, end_feat + 1):
727
  if feat_idx < len(feature_mapping):
728
- # 从feature_mapping中获取该feature对应的所有原始帧
729
  feat_info = feature_mapping[feat_idx]
730
  for orig_idx in range(feat_info['frame_start'], feat_info['frame_end']):
731
  all_original_frames.add(orig_idx)
732
  else:
733
- # 后备方案:使用uniform mapping
734
  for feat_idx in range(start_feat, end_feat + 1):
735
  orig_idx = self._map_feature_frame_to_original(feat_idx)
736
  if orig_idx is not None:
737
  all_original_frames.add(orig_idx)
738
 
739
- # 提取视频帧
740
- print(f" 提取 {len(all_original_frames)} 个视频帧...")
741
  video_frames_dict = self._extract_video_frames(list(all_original_frames))
742
 
743
  if not video_frames_dict:
744
  print(" ⓘ No video frames extracted, skipping visualization")
745
  return
746
 
747
- # 创建figure (4列布局: Gloss | Feature Index | Peak Frame | All Frames)
748
  n_words = len(self.words)
749
  fig = plt.figure(figsize=(28, 3 * n_words))
750
  gs = gridspec.GridSpec(n_words, 4, width_ratios=[1.5, 1.5, 2.5, 8], hspace=0.3, wspace=0.2)
751
 
752
  for row_idx, (word, word_info) in enumerate(zip(self.words, self.word_frame_ranges)):
753
- # 1: Gloss文本
754
  ax_gloss = fig.add_subplot(gs[row_idx, 0])
755
  ax_gloss.text(0.5, 0.5, word, fontsize=24, weight='bold',
756
  ha='center', va='center', wrap=True)
757
  ax_gloss.axis('off')
758
 
759
- # 2: 特征索引信息 (Feature Index Layer)
760
  ax_feature = fig.add_subplot(gs[row_idx, 1])
761
 
762
- # 特征帧信息
763
  feat_start = word_info['start_frame']
764
  feat_end = word_info['end_frame']
765
  feat_peak = word_info['peak_frame']
@@ -776,28 +758,28 @@ class AttentionAnalyzer:
776
  edgecolor='darkblue', linewidth=2, alpha=0.7))
777
  ax_feature.axis('off')
778
 
779
- # 3: 峰值feature对应的原始帧
780
  ax_peak_frames = fig.add_subplot(gs[row_idx, 2])
781
 
782
  peak_frames_to_show = []
783
  orig_peak_start, orig_peak_end = None, None
784
  if feature_mapping and feat_peak is not None and feat_peak < len(feature_mapping):
785
- # 使用实际的feature mapping
786
  peak_info = feature_mapping[feat_peak]
787
  orig_peak_start = peak_info['frame_start']
788
  orig_peak_end = peak_info['frame_end']
789
 
790
- # 显示峰值feature对应的所有原始帧
791
  for orig_idx in range(orig_peak_start, orig_peak_end):
792
  if orig_idx in video_frames_dict:
793
  peak_frames_to_show.append(video_frames_dict[orig_idx])
794
 
795
  if peak_frames_to_show:
796
- # 水平拼接帧
797
  combined_peak = np.hstack(peak_frames_to_show)
798
  ax_peak_frames.imshow(combined_peak)
799
 
800
- # 添加标题
801
  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)",
802
  ha='center', va='top', transform=ax_peak_frames.transAxes,
803
  fontsize=10, weight='bold', color='red',
@@ -808,28 +790,28 @@ class AttentionAnalyzer:
808
 
809
  ax_peak_frames.axis('off')
810
 
811
- # 4: 整个gloss覆盖的所有原始帧
812
  ax_all_frames = fig.add_subplot(gs[row_idx, 3])
813
 
814
  all_frames_to_show = []
815
  orig_start, orig_end = None, None
816
  if feature_mapping:
817
- # 使用实际的feature mapping获取范围
818
  if feat_start < len(feature_mapping) and feat_end < len(feature_mapping):
819
  orig_start = feature_mapping[feat_start]['frame_start']
820
  orig_end = feature_mapping[feat_end]['frame_end']
821
 
822
- # 收集所有原始帧
823
  for orig_idx in range(orig_start, orig_end):
824
  if orig_idx in video_frames_dict:
825
  all_frames_to_show.append(video_frames_dict[orig_idx])
826
 
827
  if all_frames_to_show:
828
- # 水平拼接所有帧
829
  combined_all = np.hstack(all_frames_to_show)
830
  ax_all_frames.imshow(combined_all)
831
 
832
- # 添加标题显示帧数
833
  frame_count = len(all_frames_to_show)
834
  ax_all_frames.text(0.5, -0.05, f"All Frames ({frame_count} frames)\nRange: {orig_start}-{orig_end-1}",
835
  ha='center', va='top', transform=ax_all_frames.transAxes,
@@ -850,7 +832,7 @@ class AttentionAnalyzer:
850
  print(f" ✓ {Path(output_path).name}")
851
 
852
  def _read_video_metadata(self):
853
- """尝试读取原始视频的帧数和fps"""
854
  metadata = self._read_metadata_with_cv2()
855
  if metadata:
856
  return metadata
@@ -927,7 +909,7 @@ class AttentionAnalyzer:
927
 
928
  @staticmethod
929
  def _parse_ffprobe_fps(rate_str):
930
- """解析ffprobe输出的帧率字符串,例如'30000/1001'"""
931
  if not rate_str or rate_str in ("0/0", "0"):
932
  return None
933
 
@@ -950,13 +932,13 @@ class AttentionAnalyzer:
950
 
951
  def analyze_from_numpy_file(attention_file, translation, video_frames, output_dir):
952
  """
953
- 从numpy文件加载attention并分析
954
 
955
  Args:
956
- attention_file: .npy文件路径
957
- translation: 翻译结果字符串
958
- video_frames: 视频总帧数
959
- output_dir: 输出目录
960
  """
961
  attentions = np.load(attention_file)
962
  analyzer = AttentionAnalyzer(attentions, translation, video_frames)
 
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(
 
17
  video_frames=100
18
  )
19
 
 
20
  analyzer.generate_all_visualizations(output_dir="results/")
21
  """
22
 
 
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:
 
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:
 
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,
 
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
 
 
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:
 
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:
 
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
 
 
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')
 
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)
 
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
 
 
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)
 
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,
 
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")
 
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'),
 
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}")
 
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 {}
 
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
 
 
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
 
 
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 = {}
 
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)")
 
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"
 
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']
 
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',
 
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,
 
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
 
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
 
 
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)
SignX/eval/extract_attention_keyframes.py CHANGED
@@ -1,6 +1,6 @@
1
  #!/usr/bin/env python3
2
  """
3
- 提取peak feature对应的关键帧,并将注意力可视化叠加到帧上
4
  """
5
 
6
  import os
@@ -14,42 +14,36 @@ from matplotlib import cm
14
 
15
  def apply_attention_heatmap(frame, attention_weight, alpha=0.5):
16
  """
17
- 将注意力热力图叠加到视频帧上
18
 
19
  Args:
20
- frame: 原始帧 (H, W, 3)
21
- attention_weight: 注意力权重 (0-1之间的标量值)
22
- alpha: 热力图透明度
23
 
24
  Returns:
25
- 带有注意力热力图的帧
26
  """
27
  h, w = frame.shape[:2]
28
 
29
- # 创建一个简单的中心高斯热力图(假设注意力集中在中心区域)
30
- # 更好的方法是使用真实的空间注意力权重,但这需要模型输出空间维度的注意力
31
-
32
- # 创建热力图 - 使用注意力权重调整强度
33
  y, x = np.ogrid[:h, :w]
34
  center_y, center_x = h // 2, w // 2
35
 
36
- # 高斯分布,注意力权重越高,热力图越集中
37
- sigma = min(h, w) / 3 * (1.5 - attention_weight) # 权重高时sigma更小,更集中
38
  gaussian = np.exp(-((x - center_x)**2 + (y - center_y)**2) / (2 * sigma**2))
39
 
40
- # 归一化到 [0, 1]
41
  gaussian = (gaussian - gaussian.min()) / (gaussian.max() - gaussian.min() + 1e-8)
42
 
43
- # 应用注意力权重
44
  heatmap = gaussian * attention_weight
45
 
46
- # 使用colormap: 蓝色(低) -> 绿色 -> 黄色 -> 橙色 -> 红色()
47
- # 使用 'jet' 'hot' colormap
48
- colormap = cm.get_cmap('jet') # 或使用 'hot'
49
- heatmap_colored = colormap(heatmap)[:, :, :3] * 255 # 转为RGB
50
  heatmap_colored = heatmap_colored.astype(np.uint8)
51
 
52
- # 叠加到原始帧
53
  result = cv2.addWeighted(frame, 1-alpha, heatmap_colored, alpha, 0)
54
 
55
  return result
@@ -57,30 +51,30 @@ def apply_attention_heatmap(frame, attention_weight, alpha=0.5):
57
 
58
  def extract_keyframes_with_attention(sample_dir, video_path):
59
  """
60
- 提取peak feature对应的关键帧,并叠加注意力可视化
61
 
62
  Args:
63
- sample_dir: sample目录路径 (e.g., detailed_xxx/sample_0)
64
- video_path: 原始视频路径
65
  """
66
  sample_dir = Path(sample_dir)
67
 
68
- print(f"\n处理样本: {sample_dir.name}")
69
 
70
  # 检查必要文件
71
  mapping_file = sample_dir / "feature_frame_mapping.json"
72
  weights_file = sample_dir / "attention_weights.npy"
73
 
74
  if not mapping_file.exists():
75
- print(f" ⚠ 未找到映射文件: {mapping_file}")
76
  return
77
 
78
  if not weights_file.exists():
79
- print(f" ⚠ 未找到注意力权重: {weights_file}")
80
  return
81
 
82
  if not os.path.exists(video_path):
83
- print(f" ⚠ 视频文件不存在: {video_path}")
84
  return
85
 
86
  # 加载映射和注意力权重
@@ -89,22 +83,22 @@ def extract_keyframes_with_attention(sample_dir, video_path):
89
 
90
  attention_weights = np.load(weights_file)
91
 
92
- # 创建关键帧输出目录
93
  keyframes_dir = sample_dir / "attention_keyframes"
94
  keyframes_dir.mkdir(exist_ok=True)
95
 
96
- print(f" 特征数量: {mapping_data['feature_count']}")
97
- print(f" 原始帧数: {mapping_data['original_frame_count']}")
98
- print(f" 注意力权重形状: {attention_weights.shape}")
99
 
100
  # 打开视频
101
  cap = cv2.VideoCapture(video_path)
102
  if not cap.isOpened():
103
- print(f" ✗ 无法打开视频: {video_path}")
104
  return
105
 
106
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
107
- print(f" 视频总帧数: {total_frames}")
108
 
109
  # 构建特征索引到帧的映射(使用中间帧)
110
  feature_to_frame = {}
@@ -112,57 +106,48 @@ def extract_keyframes_with_attention(sample_dir, video_path):
112
  feature_idx = item['feature_index']
113
  frame_start = item['frame_start']
114
  frame_end = item['frame_end']
115
- # 使用中间帧
116
  mid_frame = (frame_start + frame_end) // 2
117
  feature_to_frame[feature_idx] = mid_frame
118
 
119
  num_glosses = attention_weights.shape[0] if len(attention_weights.shape) > 1 else 0
120
 
121
  if num_glosses == 0:
122
- print(f" ⚠ 注意力权重维度不正确")
123
  cap.release()
124
  return
125
 
126
  saved_count = 0
127
 
128
  for gloss_idx in range(num_glosses):
129
- # 获取该gloss的注意力权重 (对所有特征的注意力)
130
  gloss_attention = attention_weights[gloss_idx] # shape: (num_features,)
131
 
132
- # 找到peak特征 (注意力最高的特征)
133
  peak_feature_idx = np.argmax(gloss_attention)
134
  peak_attention = gloss_attention[peak_feature_idx]
135
 
136
- # 获取对应的帧索引
137
  if peak_feature_idx not in feature_to_frame:
138
- print(f" ⚠ Gloss {gloss_idx}: 特征 {peak_feature_idx} 没有对应的帧")
139
  continue
140
 
141
  frame_idx = feature_to_frame[peak_feature_idx]
142
 
143
- # 读取该帧
144
  cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
145
  ret, frame = cap.read()
146
 
147
  if not ret:
148
- print(f" ⚠ Gloss {gloss_idx}: 无法读取帧 {frame_idx}")
149
  continue
150
 
151
- # 应用注意力热力图
152
  frame_with_attention = apply_attention_heatmap(frame, peak_attention, alpha=0.4)
153
 
154
- # 添加文本信息
155
  text = f"Gloss {gloss_idx} | Feature {peak_feature_idx} | Frame {frame_idx}"
156
  attention_text = f"Attention: {peak_attention:.3f}"
157
 
158
- # 在图像顶部添加黑色背景条
159
  cv2.rectangle(frame_with_attention, (0, 0), (frame.shape[1], 60), (0, 0, 0), -1)
160
  cv2.putText(frame_with_attention, text, (10, 25),
161
  cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
162
  cv2.putText(frame_with_attention, attention_text, (10, 50),
163
  cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
164
 
165
- # 保存关键帧
166
  output_filename = f"keyframe_{gloss_idx:03d}_feat{peak_feature_idx}_frame{frame_idx}_att{peak_attention:.3f}.jpg"
167
  output_path = keyframes_dir / output_filename
168
 
@@ -171,17 +156,17 @@ def extract_keyframes_with_attention(sample_dir, video_path):
171
 
172
  cap.release()
173
 
174
- print(f" ✓ 已保存 {saved_count} 个关键帧到: {keyframes_dir}")
175
 
176
- # 创建索引文件
177
  index_file = keyframes_dir / "keyframes_index.txt"
178
  with open(index_file, 'w') as f:
179
- f.write(f"关键帧索引\n")
180
  f.write(f"=" * 60 + "\n\n")
181
- f.write(f"样本目录: {sample_dir}\n")
182
- f.write(f"视频路径: {video_path}\n")
183
- f.write(f"总关键帧数: {saved_count}\n\n")
184
- f.write(f"关键帧列表:\n")
185
  f.write(f"-" * 60 + "\n")
186
 
187
  for gloss_idx in range(num_glosses):
@@ -194,13 +179,13 @@ def extract_keyframes_with_attention(sample_dir, video_path):
194
  filename = f"keyframe_{gloss_idx:03d}_feat{peak_feature_idx}_frame{frame_idx}_att{peak_attention:.3f}.jpg"
195
  f.write(f"Gloss {gloss_idx:3d}: {filename}\n")
196
 
197
- print(f" ✓ 索引文件已创建: {index_file}")
198
 
199
 
200
  def main():
201
  if len(sys.argv) < 3:
202
- print("用法: python extract_attention_keyframes.py <sample_dir> <video_path>")
203
- print("示例: python extract_attention_keyframes.py detailed_xxx/sample_0 video.mp4")
204
  sys.exit(1)
205
 
206
  sample_dir = sys.argv[1]
 
1
  #!/usr/bin/env python3
2
  """
3
+ Extract peak-feature keyframes and overlay attention heatmaps on the video frames.
4
  """
5
 
6
  import os
 
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
 
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
  # 加载映射和注意力权重
 
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 = {}
 
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
 
 
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):
 
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]
SignX/eval/generate_feature_mapping.py CHANGED
@@ -1,6 +1,6 @@
1
  #!/usr/bin/env python
2
  """
3
- 生成特征-帧映射文件
4
 
5
  Usage:
6
  python generate_feature_mapping.py <sample_dir> <video_path>
@@ -17,13 +17,13 @@ import numpy as np
17
  from pathlib import Path
18
 
19
  def generate_feature_mapping(sample_dir, video_path):
20
- """为指定样本生成特征-帧映射文件"""
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"错误: 找不到attention_weights.npy: {attn_file}")
27
  return False
28
 
29
  # Load attention weights to get feature count
@@ -34,29 +34,29 @@ def generate_feature_mapping(sample_dir, video_path):
34
  elif attn_weights.ndim == 3:
35
  feature_count = attn_weights.shape[2] # Shape: (time, beam, features) - beam search
36
  else:
37
- print(f"错误: attention_weights 维度异常: {attn_weights.shape}")
38
  return False
39
 
40
- print(f"特征数量: {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"错误: 无法打开视频文件: {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_frame_count}, FPS: {fps}")
55
 
56
  except ImportError:
57
- print("警告: OpenCV不可用,使用估算值")
58
- # 假设30fps,根据特征数估算
59
- original_frame_count = feature_count * 3 # 默认3倍下采样
60
  fps = 30.0
61
 
62
  # Calculate uniform mapping: feature i -> frames [start, end]
@@ -84,29 +84,29 @@ def generate_feature_mapping(sample_dir, video_path):
84
  with open(output_file, 'w') as f:
85
  json.dump(mapping_data, f, indent=2)
86
 
87
- print(f"\n✓ 已生成映射文件: {output_file}")
88
- print(f" 原始帧数: {original_frame_count}")
89
- print(f" 特征数量: {feature_count}")
90
- print(f" 下采样比例: {mapping_data['downsampling_ratio']:.2f}x")
91
 
92
  # Print sample mappings
93
- print("\n映射示例:")
94
  for i in range(min(3, len(frame_mapping))):
95
  mapping = frame_mapping[i]
96
- print(f" 特征 {mapping['feature_index']}: {mapping['frame_start']}-{mapping['frame_end']} "
97
- f"({mapping['frame_count']} )")
98
  if len(frame_mapping) > 3:
99
  print(" ...")
100
  mapping = frame_mapping[-1]
101
- print(f" 特征 {mapping['feature_index']}: {mapping['frame_start']}-{mapping['frame_end']} "
102
- f"({mapping['frame_count']} )")
103
 
104
  return True
105
 
106
  if __name__ == "__main__":
107
  if len(sys.argv) != 3:
108
- print("用法: python generate_feature_mapping.py <sample_dir> <video_path>")
109
- print("\n示例:")
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)
@@ -115,11 +115,11 @@ if __name__ == "__main__":
115
  video_path = sys.argv[2]
116
 
117
  if not os.path.exists(sample_dir):
118
- print(f"错误: 样本目录不存在: {sample_dir}")
119
  sys.exit(1)
120
 
121
  if not os.path.exists(video_path):
122
- print(f"错误: 视频文件不存在: {video_path}")
123
  sys.exit(1)
124
 
125
  success = generate_feature_mapping(sample_dir, video_path)
 
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>
 
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
 
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]
 
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)
 
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)
SignX/eval/generate_interactive_alignment.py CHANGED
@@ -1,11 +1,12 @@
1
  #!/usr/bin/env python3
2
  """
3
- 生成交互式HTML可视化 - 可调整置信度阈值的gloss-to-feature对齐
4
- 参考frame_alignment.png的布局风格
5
- 使用方法:
 
6
  python generate_interactive_alignment.py <sample_dir>
7
 
8
- 例如:
9
  python generate_interactive_alignment.py detailed_prediction_20251226_022246/sample_000
10
  """
11
 
@@ -15,11 +16,11 @@ import numpy as np
15
  from pathlib import Path
16
 
17
  def generate_interactive_html(sample_dir, output_path):
18
- """生成交互式HTML可视化 - 参考frame_alignment.png的风格"""
19
 
20
  sample_dir = Path(sample_dir)
21
 
22
- # 1. 读取注意力权重
23
  attention_weights = np.load(sample_dir / "attention_weights.npy")
24
  # Handle both 2D (inference mode) and 3D (beam search) shapes
25
  if attention_weights.ndim == 2:
@@ -29,7 +30,7 @@ def generate_interactive_html(sample_dir, output_path):
29
  else:
30
  raise ValueError(f"Unexpected attention weights shape: {attention_weights.shape}")
31
 
32
- # 2. 读取翻译结果
33
  with open(sample_dir / "translation.txt", 'r') as f:
34
  lines = f.readlines()
35
  gloss_sequence = None
@@ -39,19 +40,18 @@ def generate_interactive_html(sample_dir, output_path):
39
  break
40
 
41
  if not gloss_sequence:
42
- print("无法找到翻译结果")
43
  return
44
 
45
  glosses = gloss_sequence.split()
46
  num_glosses = len(glosses)
47
  num_features = attn_weights.shape[1]
48
 
49
- print(f"Gloss序列: {glosses}")
50
- print(f"特征数量: {num_features}")
51
  print(f"Attention shape: {attn_weights.shape}")
52
 
53
- # 3. attention权重转换为JSON可序列化格式
54
- # 只取前num_glosses行(实际的gloss,不包括padding)
55
  attn_data = []
56
  for word_idx in range(min(num_glosses, attn_weights.shape[0])):
57
  weights = attn_weights[word_idx, :].tolist()
@@ -61,9 +61,9 @@ def generate_interactive_html(sample_dir, output_path):
61
  'weights': weights
62
  })
63
 
64
- # 4. 生成HTML内容
65
  html_content = f"""<!DOCTYPE html>
66
- <html lang="zh-CN">
67
  <head>
68
  <meta charset="UTF-8">
69
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -213,7 +213,7 @@ def generate_interactive_html(sample_dir, output_path):
213
  <span class="value-display" id="peak-threshold-value">90%</span>
214
  <br>
215
  <small style="margin-left: 255px; color: #666;">
216
- 帧的注意力权重 ≥ (峰值权重 × 阈值%) 时被认为是"显著帧"
217
  </small>
218
  </div>
219
 
@@ -237,7 +237,7 @@ def generate_interactive_html(sample_dir, output_path):
237
  <div>
238
  <h3>Word-to-Frame Alignment</h3>
239
  <p style="color: #666; font-size: 13px;">
240
- 每个词显示为彩色矩形,宽度表示该词对应的特征帧范围。★ = 峰值帧。矩形内部显示注意力权重波形。
241
  </p>
242
  <canvas id="alignment-canvas" width="1600" height="600"></canvas>
243
 
@@ -643,28 +643,28 @@ def generate_interactive_html(sample_dir, output_path):
643
  </html>
644
  """
645
 
646
- # 5. 保存HTML文件
647
  with open(output_path, 'w', encoding='utf-8') as f:
648
  f.write(html_content)
649
 
650
- print(f"✓ 已生成交互式HTML: {output_path}")
651
- print(f" 在浏览器中打开此文件,使用滑块调整阈值")
652
 
653
  if __name__ == "__main__":
654
  if len(sys.argv) != 2:
655
- print("使用方法: python generate_interactive_alignment.py <sample_dir>")
656
- print("例如: 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"错误: 目录不存在: {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(f"\n使用方法:")
669
- print(f" 在浏览器中打开: {output_path.absolute()}")
670
- print(f" 调整滑块实时查看不同阈值下的对齐效果")
 
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
 
 
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:
 
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
 
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()
 
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">
 
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
 
 
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
 
 
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.")
SignX/eval/regenerate_visualizations.py CHANGED
@@ -1,11 +1,11 @@
1
  #!/usr/bin/env python3
2
  """
3
- 重新生成所有可视化(使用最新的attention_analysis.py代码)
4
 
5
- 使用方法:
6
  python regenerate_visualizations.py <detailed_prediction_dir> <video_path>
7
 
8
- 例如:
9
  python regenerate_visualizations.py detailed_prediction_20251226_161117 ./eval/tiny_test_data/videos/632051.mp4
10
  """
11
 
@@ -22,11 +22,11 @@ import numpy as np
22
 
23
 
24
  def regenerate_sample_visualizations(sample_dir, video_path):
25
- """为单个样本重新生成所有可视化"""
26
  sample_dir = Path(sample_dir)
27
 
28
  if not sample_dir.exists():
29
- print(f"错误: 样本目录不存在: {sample_dir}")
30
  return False
31
 
32
  # 加载数据
@@ -34,23 +34,23 @@ def regenerate_sample_visualizations(sample_dir, video_path):
34
  trans_file = sample_dir / "translation.txt"
35
 
36
  if not attn_file.exists() or not trans_file.exists():
37
- print(f" 跳过 {sample_dir.name}: 缺少必要文件")
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
- # 找到 "Clean:" 后的翻译
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() # 后备方案
52
 
53
- # 获取特征数量(video_frames
54
  if len(attention_weights.shape) == 4:
55
  video_frames = attention_weights.shape[3]
56
  elif len(attention_weights.shape) == 3:
@@ -58,7 +58,7 @@ def regenerate_sample_visualizations(sample_dir, video_path):
58
  else:
59
  video_frames = attention_weights.shape[1]
60
 
61
- print(f" 样本: {sample_dir.name}")
62
  print(f" Attention shape: {attention_weights.shape}")
63
  print(f" Translation: {translation}")
64
  print(f" Features: {video_frames}")
@@ -71,25 +71,25 @@ def regenerate_sample_visualizations(sample_dir, video_path):
71
  video_path=str(video_path) if video_path else None
72
  )
73
 
74
- # 重新生成frame_alignment.png (带原始帧层)
75
- print(f" 重新生成 frame_alignment.png...")
76
  analyzer.plot_frame_alignment(sample_dir / "frame_alignment.png")
77
 
78
- # 重新生成gloss_to_frames.png (带特征索引层)
79
  if video_path and Path(video_path).exists():
80
- print(f" 重新生成 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" 警告: gloss_to_frames生成失败: {e}")
85
 
86
  return True
87
 
88
 
89
  def main():
90
  if len(sys.argv) < 2:
91
- print("用法: python regenerate_visualizations.py <detailed_prediction_dir> [<video_path>]")
92
- print("\n示例:")
93
  print(" python regenerate_visualizations.py detailed_prediction_20251226_161117 ./eval/tiny_test_data/videos/632051.mp4")
94
  sys.exit(1)
95
 
@@ -97,16 +97,16 @@ def main():
97
  video_path = Path(sys.argv[2]) if len(sys.argv) > 2 else None
98
 
99
  if not pred_dir.exists():
100
- print(f"错误: 预测目录不存在: {pred_dir}")
101
  sys.exit(1)
102
 
103
  if video_path and not video_path.exists():
104
- print(f"警告: 视频文件不存在: {video_path}")
105
  video_path = None
106
 
107
- print(f"重新生成可视化:")
108
- print(f" 预测目录: {pred_dir}")
109
- print(f" 视频路径: {video_path if video_path else 'N/A'}")
110
  print()
111
 
112
  # 处理所有样本
@@ -115,7 +115,7 @@ def main():
115
  if regenerate_sample_visualizations(sample_dir, video_path):
116
  success_count += 1
117
 
118
- print(f"\n✓ 完成!成功处理 {success_count} 个样本")
119
 
120
 
121
  if __name__ == "__main__":
 
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
 
 
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
  # 加载数据
 
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:
 
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}")
 
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
 
 
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
  # 处理所有样本
 
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__":
SignX/inference.sh CHANGED
@@ -1,33 +1,33 @@
1
  #!/bin/bash
2
- # 手语识别推理脚本 - 从视频输出 gloss 序列
3
  #
4
- # 使用完整的两阶段 pipeline:
5
- # 视频 → [SMKD冻结] → 特征 → [SLTUNET] → gloss序列
6
  #
7
- # 使用方法:
8
  # ./inference.sh <video_path> [output_path]
9
  # ./inference.sh --benchmark-efficiency [options...]
10
  #
11
- # 示例:
12
  # ./inference.sh test.mp4
13
  # ./inference.sh test.mp4 output.txt
14
  #
15
- # 基准测试模式 (用于 ACL 论文):
16
  # ./inference.sh --benchmark-efficiency --video test.mp4 --num-samples 100
17
  # ./inference.sh --benchmark-efficiency --config full_pipeline
18
  # ./inference.sh --benchmark-efficiency --generate-table-only
19
 
20
  set -e
21
 
22
- # 获取脚本目录(提前定义)
23
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
24
  INFERENCE_ROOT="${SCRIPT_DIR}/inference_output"
25
  mkdir -p "$INFERENCE_ROOT"
26
 
27
- # 检查是否是基准测试模式(检查所有参数)
28
  for arg in "$@"; do
29
  if [ "$arg" == "--benchmark-efficiency" ]; then
30
- # 基准测试模式,提示使用simple_benchmark.sh
31
  echo ""
32
  echo "====================================================================="
33
  echo " Efficiency Benchmarking"
@@ -40,14 +40,14 @@ for arg in "$@"; do
40
  fi
41
  done
42
 
43
- # 颜色定义
44
  RED='\033[0;31m'
45
  GREEN='\033[0;32m'
46
  YELLOW='\033[1;33m'
47
  BLUE='\033[0;34m'
48
  NC='\033[0m' # No Color
49
 
50
- # 默认参数 (使用第7次训练的pose协助模型)
51
  SMKD_CONFIG="${SCRIPT_DIR}/smkd/asllrp_baseline.yaml"
52
  SMKD_MODEL="/research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/SignX/smkd/work_dir第七次训练全pose协助2000/asllrp_smkd/best_model.pt"
53
  GLOSS_DICT="/research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/SignX/smkd/asllrp第七次训练全pose协助2000/gloss_dict.npy"
@@ -57,24 +57,24 @@ BPE_CODES="${SCRIPT_DIR}/preprocessed-asllrp/asllrp.bpe"
57
 
58
  echo ""
59
  echo "======================================================================"
60
- echo " Sign Language Recognition - 完整推理 Pipeline"
61
  echo "======================================================================"
62
  echo ""
63
- echo " 架构: 视频 → [SMKD冻结] → 特征 → [SLTUNET] → Gloss"
64
- echo " 方法: 使用 inference 模式 (一键完成两阶段)"
65
  echo ""
66
  echo "======================================================================"
67
  echo ""
68
 
69
- # 检查参数
70
  if [ "$#" -lt 1 ]; then
71
- echo -e "${RED}错误: 缺少视频路径${NC}"
72
  echo ""
73
- echo "使用方法:"
74
  echo " $0 <video_path> [output_path]"
75
  echo " $0 --benchmark-efficiency [options...]"
76
  echo ""
77
- echo "示例:"
78
  echo " $0 test.mp4"
79
  echo " $0 test.mp4 output.txt"
80
  echo " $0 --benchmark-efficiency --video test.mp4"
@@ -89,72 +89,67 @@ else
89
  OUTPUT_PATH="${2}"
90
  fi
91
 
92
- # 检查视频文件是否存在
93
  if [ ! -f "$VIDEO_PATH" ]; then
94
- echo -e "${RED}错误: 视频文件不存在: $VIDEO_PATH${NC}"
95
  exit 1
96
  fi
97
 
98
- # 转换为绝对路径
99
  VIDEO_PATH=$(realpath "$VIDEO_PATH")
100
 
101
- # 如果OUTPUT_PATH是绝对路径或已存在的文件,直接使用
102
- # 否则,在脚本目录下创建输出文件
103
  if [[ "$OUTPUT_PATH" = /* ]]; then
104
- # 已经是绝对路径
105
  OUTPUT_PATH="$OUTPUT_PATH"
106
  elif [ -f "$OUTPUT_PATH" ]; then
107
- # 文件已存在,转换为绝对路径
108
  OUTPUT_PATH=$(realpath "$OUTPUT_PATH")
109
  else
110
- # 相对路径或默认值,在 inference_output 目录下输出
111
  OUTPUT_PATH="${INFERENCE_ROOT}/${OUTPUT_PATH}"
112
  fi
113
  OUTPUT_CLEAN_PATH="${OUTPUT_PATH}.clean"
114
 
115
- echo -e "${BLUE}[配置信息]${NC}"
116
- echo " 输入视频: $VIDEO_PATH"
117
- echo " 输出文件: $OUTPUT_PATH"
118
- echo " SMKD模型: $SMKD_MODEL"
119
  echo " SLTUNET: $SLTUNET_CHECKPOINT"
120
  echo ""
121
 
122
- # 获取conda base
123
  CONDA_BASE=$(conda info --base 2>/dev/null || echo "")
124
 
125
  if [ -z "$CONDA_BASE" ]; then
126
- echo -e "${RED}错误: 未找到conda${NC}"
127
- echo "请确保已安装conda"
128
  exit 1
129
  fi
130
 
131
- # 激活conda
132
  source "${CONDA_BASE}/etc/profile.d/conda.sh"
133
 
134
- # 临时目录
135
  TEMP_DIR=$(mktemp -d)
136
- # 不要在EXIT时删除,因为我们需要保存详细的attention分析结果
137
- # 我们将在脚本结束前手动清理不需要的部分
138
 
139
- echo -e "${BLUE}[1/2] 使用 SMKD 提取视频特征...${NC}"
140
- echo " 环境: signx-slt (PyTorch)"
141
  echo ""
142
 
143
- # 切换到 PyTorch 环境
144
  conda activate signx-slt
145
 
146
  if [ $? -ne 0 ]; then
147
- echo -e "${RED}错误: 无法激活 signx-slt 环境${NC}"
148
  exit 1
149
  fi
150
 
151
- # 创建临时视频列表文件(InferFeeder需要)
152
  VIDEO_LIST_FILE="$TEMP_DIR/video_list.txt"
153
  echo "$VIDEO_PATH" > "$VIDEO_LIST_FILE"
154
 
155
- echo " ✓ 临时视频列表已创建: $VIDEO_LIST_FILE"
156
 
157
- # 使用 SignEmbedding 提取特征
158
  cd "$SCRIPT_DIR"
159
 
160
  FEATURE_OUTPUT="$TEMP_DIR/features.h5"
@@ -168,7 +163,7 @@ from smkd.sign_embedder import SignEmbedding
168
  import h5py
169
  import numpy as np
170
 
171
- print(' 加载 SMKD 模型...')
172
  embedder = SignEmbedding(
173
  cfg='$SMKD_CONFIG',
174
  gloss_path='$GLOSS_DICT',
@@ -178,59 +173,59 @@ embedder = SignEmbedding(
178
  batch_size=1
179
  )
180
 
181
- print(' 提取特征...')
182
  features = embedder.embed()
183
 
184
- print(' 保存特征到 h5 文件...')
185
  with h5py.File('$FEATURE_OUTPUT', 'w') as hf:
186
  for key, feature in features.items():
187
  hf.create_dataset(key, data=feature)
188
 
189
- print(' ✓ 特征提取完成: $FEATURE_OUTPUT')
190
- print(' 特征数量:', len(features))
191
 
192
- # 创建源文件和目标文件(SLTUNET Dataset需要)
193
- # 格式: <image_index> <text>
194
- # 推理时使用占位符text(因为真实gloss是我们要预测的)
195
  with open('$TEMP_DIR/src.txt', 'w') as f:
196
  for key in sorted(features.keys(), key=lambda x: int(x)):
197
- f.write(key + ' <unk>\\n') # 使用 <unk> 作为占位符
198
 
199
  with open('$TEMP_DIR/tgt.txt', 'w') as f:
200
  for key in sorted(features.keys(), key=lambda x: int(x)):
201
- f.write('<unk>\\n') # 使用 <unk> 作为占位符
202
 
203
- print(' ✓ 源文件和目标文件已创建')
204
  "
205
 
206
  if [ $? -ne 0 ]; then
207
- echo -e "${RED}错误: 特征提取失败${NC}"
208
  exit 1
209
  fi
210
 
211
  echo ""
212
- echo -e "${GREEN}✓ Stage 1 完成: 视频特征已提取${NC}"
213
  echo ""
214
 
215
- # 切换到 TensorFlow 环境
216
- echo -e "${BLUE}[2/2] 使用 SLTUNET 生成 Gloss 序列...${NC}"
217
- echo " 环境: slt_tf1 (TensorFlow)"
218
  echo ""
219
 
220
  conda activate slt_tf1
221
 
222
  if [ $? -ne 0 ]; then
223
- echo -e "${RED}错误: 无法激活 slt_tf1 环境${NC}"
224
  exit 1
225
  fi
226
 
227
  export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
228
 
229
- # 获取输出目录(用于保存详细分析)
230
  OUTPUT_DIR=$(dirname "$OUTPUT_PATH")
231
  PREDICTION_TXT="$TEMP_DIR/prediction.txt"
232
 
233
- # 创建临时配置文件用于推理
234
  cat > "$TEMP_DIR/infer_config.py" <<EOF
235
  {
236
  'sign_cfg': '$SMKD_CONFIG',
@@ -253,13 +248,13 @@ cat > "$TEMP_DIR/infer_config.py" <<EOF
253
  }
254
  EOF
255
 
256
- echo " 加载 SLTUNET 模型..."
257
- echo " 开始翻译..."
258
  echo ""
259
 
260
  cd "$SCRIPT_DIR"
261
 
262
- # 运行推理,保存完整输出以便后续检查详细分析
263
  python run.py \
264
  --mode test \
265
  --config "$TEMP_DIR/infer_config.py" \
@@ -267,75 +262,73 @@ python run.py \
267
 
268
  if [ -f "$TEMP_DIR/prediction.txt" ]; then
269
  echo ""
270
- echo -e "${GREEN}✓ 推理完成: Gloss 序列已生成${NC}"
271
  echo ""
272
 
273
- # 复制结果
274
  cp "$TEMP_DIR/prediction.txt" "$OUTPUT_PATH"
275
 
276
- # 移除BPE标记 (@@) 并保存清理后的版本
277
  sed 's/@@ //g' "$OUTPUT_PATH" > "$OUTPUT_CLEAN_PATH"
278
 
279
- # 检查并移动详细的attention分析结果
280
  DETAILED_DIRS=$(find "$TEMP_DIR" -maxdepth 1 -type d -name "detailed_*" 2>/dev/null)
281
  ATTENTION_ANALYSIS_DIR=""
282
 
283
  if [ ! -z "$DETAILED_DIRS" ]; then
284
- echo -e "${BLUE}发现详细的attention分析结果,正在保存...${NC}"
285
  for detailed_dir in $DETAILED_DIRS; do
286
  dir_name=$(basename "$detailed_dir")
287
  dest_path="$INFERENCE_ROOT/$dir_name"
288
  mv "$detailed_dir" "$dest_path"
289
  ATTENTION_ANALYSIS_DIR="$dest_path"
290
 
291
- # 统计样本数量
292
  mapfile -t SAMPLE_DIRS < <(find "$dest_path" -mindepth 1 -maxdepth 1 -type d -print | sort)
293
  sample_count=${#SAMPLE_DIRS[@]}
294
- echo " ✓ 已保存 $sample_count 个样本的详细分析到: $dest_path"
295
 
296
- # 步骤1:生成特征-帧映射 (Feature-to-Frame Mapping)
297
  echo ""
298
- echo -e "${BLUE}生成特征-帧映射...${NC}"
299
  if [ -f "$SCRIPT_DIR/eval/generate_feature_mapping.py" ]; then
300
- # 切换到 signx-slt 环境 ( cv2)
301
  conda activate signx-slt
302
  if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
303
- echo " ⚠ 未找到样本目录,跳过特征映射生成"
304
  else
305
  for sample_dir in "${SAMPLE_DIRS[@]}"; do
306
  if [ -d "$sample_dir" ]; then
307
- python "$SCRIPT_DIR/eval/generate_feature_mapping.py" "$sample_dir" "$VIDEO_PATH" 2>&1 | grep -E "(特征数量|原始帧数|已生成映射|错误)"
308
  fi
309
  done
310
  fi
311
  else
312
- echo " ⓘ generate_feature_mapping.py 未找到,跳过特征映射生成"
313
  fi
314
 
315
- # 步骤2:重新生成所有可视化(使用最新代码)
316
  echo ""
317
- echo -e "${BLUE}重新生成可视化(使用最新代码)...${NC}"
318
  if [ -f "$SCRIPT_DIR/eval/regenerate_visualizations.py" ]; then
319
- # 已在 signx-slt 环境
320
  if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
321
- echo " ⚠ 未找到样本目录,跳过可视化生成"
322
  else
323
  python "$SCRIPT_DIR/eval/regenerate_visualizations.py" "$dest_path" "$VIDEO_PATH"
324
  fi
325
  else
326
- echo " ⓘ regenerate_visualizations.py 未找到,使用旧版本"
327
  if [ -f "$SCRIPT_DIR/eval/generate_gloss_frames.py" ]; then
328
  python "$SCRIPT_DIR/eval/generate_gloss_frames.py" "$dest_path" "$VIDEO_PATH"
329
  fi
330
  fi
331
 
332
- # 步骤3:生成交互式HTML可视化
333
  echo ""
334
- echo -e "${BLUE}生成交互式HTML可视化...${NC}"
335
  if [ -f "$SCRIPT_DIR/eval/generate_interactive_alignment.py" ]; then
336
- # 处理所有样本
337
  if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
338
- echo " ⚠ 未找到样本目录,跳过交互式HTML生成"
339
  else
340
  for sample_dir in "${SAMPLE_DIRS[@]}"; do
341
  if [ -d "$sample_dir" ]; then
@@ -344,40 +337,39 @@ if [ -f "$TEMP_DIR/prediction.txt" ]; then
344
  done
345
  fi
346
  else
347
- echo " ⓘ generate_interactive_alignment.py 未找到,跳过交互式HTML生成"
348
  fi
349
 
350
- # 步骤4:提取关键帧���叠加注意力可视化
351
  echo ""
352
- echo -e "${BLUE}提取关键帧并叠加注意力可视化...${NC}"
353
  if [ -f "$SCRIPT_DIR/eval/extract_attention_keyframes.py" ]; then
354
- # 处理所有样本
355
  if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
356
- echo " ⚠ 未找到样本目录,跳过关键帧提取"
357
  else
358
  for sample_dir in "${SAMPLE_DIRS[@]}"; do
359
  if [ -d "$sample_dir" ]; then
360
- echo " 处理样本: $(basename "$sample_dir")"
361
  python "$SCRIPT_DIR/eval/extract_attention_keyframes.py" "$sample_dir" "$VIDEO_PATH"
362
  fi
363
  done
364
  fi
365
  else
366
- echo " ⓘ extract_attention_keyframes.py 未找到,跳过关键帧提取"
367
  fi
368
 
369
- # 切换回 slt_tf1 环境
370
  conda activate slt_tf1
371
  done
372
  fi
373
 
374
- # 将输出文件移动到样本目录中,保持所有结果集中存储
375
  if [ ! -z "$ATTENTION_ANALYSIS_DIR" ] && [ -d "$ATTENTION_ANALYSIS_DIR" ]; then
376
  PRIMARY_SAMPLE_DIR=$(find "$ATTENTION_ANALYSIS_DIR" -mindepth 1 -maxdepth 1 -type d | sort | head -n 1)
377
  if [ ! -z "$PRIMARY_SAMPLE_DIR" ] && [ -d "$PRIMARY_SAMPLE_DIR" ]; then
378
  TRANSLATION_FILE="${PRIMARY_SAMPLE_DIR}/translation.txt"
379
 
380
- # 将推理输出移动到样本目录(便于调试)
381
  MOVED_BPE_FILE=""
382
  MOVED_CLEAN_FILE=""
383
  if [ -f "$OUTPUT_PATH" ]; then
@@ -393,7 +385,7 @@ if [ -f "$TEMP_DIR/prediction.txt" ]; then
393
  MOVED_CLEAN_FILE="$NEW_CLEAN_PATH"
394
  fi
395
 
396
- # 若不存在 translation.txt,则根据当前推理结果生成一个
397
  if [ ! -f "$TRANSLATION_FILE" ]; then
398
  TRANS_BPE=$(head -n 1 "$TEMP_DIR/prediction.txt")
399
  TRANS_CLEAN=$(sed 's/@@ //g' "$TEMP_DIR/prediction.txt" | head -n 1)
@@ -404,7 +396,7 @@ if [ -f "$TEMP_DIR/prediction.txt" ]; then
404
  } > "$TRANSLATION_FILE"
405
  fi
406
 
407
- # 移除不再需要的原始输出文件
408
  if [ -n "$MOVED_BPE_FILE" ] && [ -f "$MOVED_BPE_FILE" ] && [ "$MOVED_BPE_FILE" != "$TRANSLATION_FILE" ]; then
409
  rm -f "$MOVED_BPE_FILE"
410
  fi
@@ -419,44 +411,43 @@ if [ -f "$TEMP_DIR/prediction.txt" ]; then
419
 
420
  echo ""
421
  echo "======================================================================"
422
- echo " 推理成功!"
423
  echo "======================================================================"
424
  echo ""
425
- echo "输出文件:"
426
- echo " 原始输出 (BPE): $OUTPUT_PATH"
427
- echo " 清理后输出: $OUTPUT_CLEAN_PATH"
428
 
429
  if [ ! -z "$ATTENTION_ANALYSIS_DIR" ]; then
430
- echo " 详细分析目录: $ATTENTION_ANALYSIS_DIR"
431
  echo ""
432
- echo "Attention分析包含:"
433
- echo " - 注意力权重热图 (attention_heatmap.png)"
434
- echo " - 词-帧对齐图 (word_frame_alignment.png)"
435
- echo " - Gloss-视频帧对应图 (gloss_to_frames.png)"
436
- echo " - 分析报告 (analysis_report.txt)"
437
- echo " - 原始数据 (attention_weights.npy)"
438
- echo " - 关键帧可视化 (attention_keyframes/ 文件夹)"
439
- echo " * 包含每个gloss的peak feature"
440
- echo " * 注意力热力图叠加(橙红=高注意力,蓝色=低注意力)"
441
  fi
442
 
443
  echo ""
444
- echo "识别结果 (移除BPE):"
445
  echo "----------------------------------------------------------------------"
446
  head -5 "$OUTPUT_CLEAN_PATH" | sed 's/^/ /'
447
  echo "----------------------------------------------------------------------"
448
  echo ""
449
- echo -e "${GREEN}✓ 完整 Pipeline 执行成功 (SMKD → SLTUNET)${NC}"
450
  echo ""
451
 
452
- # 清理临时目录
453
- echo -e "${BLUE}清理临时文件...${NC}"
454
  rm -rf "$TEMP_DIR"
455
- echo " ✓ 临时文件已清理"
456
  echo ""
457
  else
458
- echo -e "${RED}错误: 推理失败,未生成输出文件${NC}"
459
- # 清理临时目录
460
  rm -rf "$TEMP_DIR"
461
  exit 1
462
  fi
 
1
  #!/bin/bash
2
+ # Sign language recognition inference script – video to gloss sequence
3
  #
4
+ # Full two-stage pipeline:
5
+ # Video → [SMKD frozen] → Features → [SLTUNET] → Gloss sequence
6
  #
7
+ # Usage:
8
  # ./inference.sh <video_path> [output_path]
9
  # ./inference.sh --benchmark-efficiency [options...]
10
  #
11
+ # Examples:
12
  # ./inference.sh test.mp4
13
  # ./inference.sh test.mp4 output.txt
14
  #
15
+ # Benchmark mode (used for ACL paper experiments):
16
  # ./inference.sh --benchmark-efficiency --video test.mp4 --num-samples 100
17
  # ./inference.sh --benchmark-efficiency --config full_pipeline
18
  # ./inference.sh --benchmark-efficiency --generate-table-only
19
 
20
  set -e
21
 
22
+ # Resolve script directory
23
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
24
  INFERENCE_ROOT="${SCRIPT_DIR}/inference_output"
25
  mkdir -p "$INFERENCE_ROOT"
26
 
27
+ # Detect benchmark mode (scan all args)
28
  for arg in "$@"; do
29
  if [ "$arg" == "--benchmark-efficiency" ]; then
30
+ # For benchmarking, redirect to simple_benchmark.sh
31
  echo ""
32
  echo "====================================================================="
33
  echo " Efficiency Benchmarking"
 
40
  fi
41
  done
42
 
43
+ # ANSI colors
44
  RED='\033[0;31m'
45
  GREEN='\033[0;32m'
46
  YELLOW='\033[1;33m'
47
  BLUE='\033[0;34m'
48
  NC='\033[0m' # No Color
49
 
50
+ # Default configuration (7th training run with pose assistance)
51
  SMKD_CONFIG="${SCRIPT_DIR}/smkd/asllrp_baseline.yaml"
52
  SMKD_MODEL="/research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/SignX/smkd/work_dir第七次训练全pose协助2000/asllrp_smkd/best_model.pt"
53
  GLOSS_DICT="/research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/SignX/smkd/asllrp第七次训练全pose协助2000/gloss_dict.npy"
 
57
 
58
  echo ""
59
  echo "======================================================================"
60
+ echo " Sign Language Recognition - Full Inference Pipeline"
61
  echo "======================================================================"
62
  echo ""
63
+ echo " Pipeline: Video → [SMKD frozen] → Features → [SLTUNET] → Gloss"
64
+ echo " Mode: inference (one-click two-stage execution)"
65
  echo ""
66
  echo "======================================================================"
67
  echo ""
68
 
69
+ # Validate arguments
70
  if [ "$#" -lt 1 ]; then
71
+ echo -e "${RED}Error: missing video path${NC}"
72
  echo ""
73
+ echo "Usage:"
74
  echo " $0 <video_path> [output_path]"
75
  echo " $0 --benchmark-efficiency [options...]"
76
  echo ""
77
+ echo "Examples:"
78
  echo " $0 test.mp4"
79
  echo " $0 test.mp4 output.txt"
80
  echo " $0 --benchmark-efficiency --video test.mp4"
 
89
  OUTPUT_PATH="${2}"
90
  fi
91
 
92
+ # Verify video file exists
93
  if [ ! -f "$VIDEO_PATH" ]; then
94
+ echo -e "${RED}Error: video file not found: $VIDEO_PATH${NC}"
95
  exit 1
96
  fi
97
 
98
+ # Convert to absolute path
99
  VIDEO_PATH=$(realpath "$VIDEO_PATH")
100
 
101
+ # If OUTPUT_PATH is already absolute, keep it; otherwise store under inference_output
 
102
  if [[ "$OUTPUT_PATH" = /* ]]; then
 
103
  OUTPUT_PATH="$OUTPUT_PATH"
104
  elif [ -f "$OUTPUT_PATH" ]; then
 
105
  OUTPUT_PATH=$(realpath "$OUTPUT_PATH")
106
  else
 
107
  OUTPUT_PATH="${INFERENCE_ROOT}/${OUTPUT_PATH}"
108
  fi
109
  OUTPUT_CLEAN_PATH="${OUTPUT_PATH}.clean"
110
 
111
+ echo -e "${BLUE}[Configuration]${NC}"
112
+ echo " Input video: $VIDEO_PATH"
113
+ echo " Output file: $OUTPUT_PATH"
114
+ echo " SMKD model: $SMKD_MODEL"
115
  echo " SLTUNET: $SLTUNET_CHECKPOINT"
116
  echo ""
117
 
118
+ # Locate conda base
119
  CONDA_BASE=$(conda info --base 2>/dev/null || echo "")
120
 
121
  if [ -z "$CONDA_BASE" ]; then
122
+ echo -e "${RED}Error: could not find conda${NC}"
123
+ echo "Please make sure conda is installed."
124
  exit 1
125
  fi
126
 
127
+ # Enable conda activation
128
  source "${CONDA_BASE}/etc/profile.d/conda.sh"
129
 
130
+ # Temporary directory
131
  TEMP_DIR=$(mktemp -d)
132
+ # Do not auto-delete on exit—we need the detailed attention results later
 
133
 
134
+ echo -e "${BLUE}[1/2] Extracting video features with SMKD...${NC}"
135
+ echo " Environment: signx-slt (PyTorch)"
136
  echo ""
137
 
138
+ # Activate PyTorch environment
139
  conda activate signx-slt
140
 
141
  if [ $? -ne 0 ]; then
142
+ echo -e "${RED}Error: failed to activate signx-slt environment${NC}"
143
  exit 1
144
  fi
145
 
146
+ # Create temporary video list file (required by InferFeeder)
147
  VIDEO_LIST_FILE="$TEMP_DIR/video_list.txt"
148
  echo "$VIDEO_PATH" > "$VIDEO_LIST_FILE"
149
 
150
+ echo " ✓ Temporary video list created: $VIDEO_LIST_FILE"
151
 
152
+ # Run SignEmbedding to extract features
153
  cd "$SCRIPT_DIR"
154
 
155
  FEATURE_OUTPUT="$TEMP_DIR/features.h5"
 
163
  import h5py
164
  import numpy as np
165
 
166
+ print(' Loading SMKD model...')
167
  embedder = SignEmbedding(
168
  cfg='$SMKD_CONFIG',
169
  gloss_path='$GLOSS_DICT',
 
173
  batch_size=1
174
  )
175
 
176
+ print(' Extracting features...')
177
  features = embedder.embed()
178
 
179
+ print(' Saving features to h5 file...')
180
  with h5py.File('$FEATURE_OUTPUT', 'w') as hf:
181
  for key, feature in features.items():
182
  hf.create_dataset(key, data=feature)
183
 
184
+ print(' ✓ Feature extraction complete:', '$FEATURE_OUTPUT')
185
+ print(' Number of feature sequences:', len(features))
186
 
187
+ # Create source/target placeholder files for SLTUNET dataset
188
+ # Format: <image_index> <text>
189
+ # Use placeholder tokens because the gloss is what we want to predict
190
  with open('$TEMP_DIR/src.txt', 'w') as f:
191
  for key in sorted(features.keys(), key=lambda x: int(x)):
192
+ f.write(key + ' <unk>\\n') # placeholder text
193
 
194
  with open('$TEMP_DIR/tgt.txt', 'w') as f:
195
  for key in sorted(features.keys(), key=lambda x: int(x)):
196
+ f.write('<unk>\\n')
197
 
198
+ print(' ✓ Source/target placeholder files ready')
199
  "
200
 
201
  if [ $? -ne 0 ]; then
202
+ echo -e "${RED}Error: SMKD feature extraction failed${NC}"
203
  exit 1
204
  fi
205
 
206
  echo ""
207
+ echo -e "${GREEN}✓ Stage 1 complete: features extracted${NC}"
208
  echo ""
209
 
210
+ # Switch to TensorFlow environment
211
+ echo -e "${BLUE}[2/2] Generating gloss sequence with SLTUNET...${NC}"
212
+ echo " Environment: slt_tf1 (TensorFlow)"
213
  echo ""
214
 
215
  conda activate slt_tf1
216
 
217
  if [ $? -ne 0 ]; then
218
+ echo -e "${RED}Error: failed to activate slt_tf1 environment${NC}"
219
  exit 1
220
  fi
221
 
222
  export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
223
 
224
+ # Determine output directory (for attention artifacts)
225
  OUTPUT_DIR=$(dirname "$OUTPUT_PATH")
226
  PREDICTION_TXT="$TEMP_DIR/prediction.txt"
227
 
228
+ # Build temporary inference config
229
  cat > "$TEMP_DIR/infer_config.py" <<EOF
230
  {
231
  'sign_cfg': '$SMKD_CONFIG',
 
248
  }
249
  EOF
250
 
251
+ echo " Loading SLTUNET model..."
252
+ echo " Running translation..."
253
  echo ""
254
 
255
  cd "$SCRIPT_DIR"
256
 
257
+ # Run inference and capture logs for later inspection
258
  python run.py \
259
  --mode test \
260
  --config "$TEMP_DIR/infer_config.py" \
 
262
 
263
  if [ -f "$TEMP_DIR/prediction.txt" ]; then
264
  echo ""
265
+ echo -e "${GREEN}✓ Inference complete: gloss sequence generated${NC}"
266
  echo ""
267
 
268
+ # Copy raw result
269
  cp "$TEMP_DIR/prediction.txt" "$OUTPUT_PATH"
270
 
271
+ # Remove BPE markers (@@) for a clean text version
272
  sed 's/@@ //g' "$OUTPUT_PATH" > "$OUTPUT_CLEAN_PATH"
273
 
274
+ # Move detailed attention analysis output if present
275
  DETAILED_DIRS=$(find "$TEMP_DIR" -maxdepth 1 -type d -name "detailed_*" 2>/dev/null)
276
  ATTENTION_ANALYSIS_DIR=""
277
 
278
  if [ ! -z "$DETAILED_DIRS" ]; then
279
+ echo -e "${BLUE}Detected detailed attention analysis, saving...${NC}"
280
  for detailed_dir in $DETAILED_DIRS; do
281
  dir_name=$(basename "$detailed_dir")
282
  dest_path="$INFERENCE_ROOT/$dir_name"
283
  mv "$detailed_dir" "$dest_path"
284
  ATTENTION_ANALYSIS_DIR="$dest_path"
285
 
286
+ # Count sample directories
287
  mapfile -t SAMPLE_DIRS < <(find "$dest_path" -mindepth 1 -maxdepth 1 -type d -print | sort)
288
  sample_count=${#SAMPLE_DIRS[@]}
289
+ echo " ✓ Saved $sample_count sample analyses to: $dest_path"
290
 
291
+ # Step 1: feature-to-frame mapping
292
  echo ""
293
+ echo -e "${BLUE}Generating feature-to-frame mapping...${NC}"
294
  if [ -f "$SCRIPT_DIR/eval/generate_feature_mapping.py" ]; then
295
+ # Switch to signx-slt environment (CV2 available)
296
  conda activate signx-slt
297
  if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
298
+ echo " ⚠ No sample directories found, skipping mapping"
299
  else
300
  for sample_dir in "${SAMPLE_DIRS[@]}"; do
301
  if [ -d "$sample_dir" ]; then
302
+ python "$SCRIPT_DIR/eval/generate_feature_mapping.py" "$sample_dir" "$VIDEO_PATH" 2>&1 | grep -E "(feature|frame|mapping|error)"
303
  fi
304
  done
305
  fi
306
  else
307
+ echo " ⓘ generate_feature_mapping.py not found, skipping mapping"
308
  fi
309
 
310
+ # Step 2: regenerate visualizations
311
  echo ""
312
+ echo -e "${BLUE}Regenerating visualizations (latest code)...${NC}"
313
  if [ -f "$SCRIPT_DIR/eval/regenerate_visualizations.py" ]; then
 
314
  if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
315
+ echo " ⚠ No sample directories found, skipping visualization"
316
  else
317
  python "$SCRIPT_DIR/eval/regenerate_visualizations.py" "$dest_path" "$VIDEO_PATH"
318
  fi
319
  else
320
+ echo " ⓘ regenerate_visualizations.py not found, falling back to legacy scripts"
321
  if [ -f "$SCRIPT_DIR/eval/generate_gloss_frames.py" ]; then
322
  python "$SCRIPT_DIR/eval/generate_gloss_frames.py" "$dest_path" "$VIDEO_PATH"
323
  fi
324
  fi
325
 
326
+ # Step 3: interactive HTML visualization
327
  echo ""
328
+ echo -e "${BLUE}Creating interactive HTML visualization...${NC}"
329
  if [ -f "$SCRIPT_DIR/eval/generate_interactive_alignment.py" ]; then
 
330
  if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
331
+ echo " ⚠ No sample directories found, skipping HTML generation"
332
  else
333
  for sample_dir in "${SAMPLE_DIRS[@]}"; do
334
  if [ -d "$sample_dir" ]; then
 
337
  done
338
  fi
339
  else
340
+ echo " ⓘ generate_interactive_alignment.py not found, skipping HTML generation"
341
  fi
342
 
343
+ # Step 4: extract attention keyframes
344
  echo ""
345
+ echo -e "${BLUE}Extracting attention keyframes...${NC}"
346
  if [ -f "$SCRIPT_DIR/eval/extract_attention_keyframes.py" ]; then
 
347
  if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
348
+ echo " ⚠ No sample directories found, skipping keyframes"
349
  else
350
  for sample_dir in "${SAMPLE_DIRS[@]}"; do
351
  if [ -d "$sample_dir" ]; then
352
+ echo " Processing sample: $(basename "$sample_dir")"
353
  python "$SCRIPT_DIR/eval/extract_attention_keyframes.py" "$sample_dir" "$VIDEO_PATH"
354
  fi
355
  done
356
  fi
357
  else
358
+ echo " ⓘ extract_attention_keyframes.py not found, skipping keyframes"
359
  fi
360
 
361
+ # Switch back to slt_tf1 environment
362
  conda activate slt_tf1
363
  done
364
  fi
365
 
366
+ # Move final output into the primary sample directory for convenience
367
  if [ ! -z "$ATTENTION_ANALYSIS_DIR" ] && [ -d "$ATTENTION_ANALYSIS_DIR" ]; then
368
  PRIMARY_SAMPLE_DIR=$(find "$ATTENTION_ANALYSIS_DIR" -mindepth 1 -maxdepth 1 -type d | sort | head -n 1)
369
  if [ ! -z "$PRIMARY_SAMPLE_DIR" ] && [ -d "$PRIMARY_SAMPLE_DIR" ]; then
370
  TRANSLATION_FILE="${PRIMARY_SAMPLE_DIR}/translation.txt"
371
 
372
+ # Keep a copy for debugging inside the sample directory
373
  MOVED_BPE_FILE=""
374
  MOVED_CLEAN_FILE=""
375
  if [ -f "$OUTPUT_PATH" ]; then
 
385
  MOVED_CLEAN_FILE="$NEW_CLEAN_PATH"
386
  fi
387
 
388
+ # Generate translation.txt if it was not created
389
  if [ ! -f "$TRANSLATION_FILE" ]; then
390
  TRANS_BPE=$(head -n 1 "$TEMP_DIR/prediction.txt")
391
  TRANS_CLEAN=$(sed 's/@@ //g' "$TEMP_DIR/prediction.txt" | head -n 1)
 
396
  } > "$TRANSLATION_FILE"
397
  fi
398
 
399
+ # Remove redundant files now that translation.txt exists
400
  if [ -n "$MOVED_BPE_FILE" ] && [ -f "$MOVED_BPE_FILE" ] && [ "$MOVED_BPE_FILE" != "$TRANSLATION_FILE" ]; then
401
  rm -f "$MOVED_BPE_FILE"
402
  fi
 
411
 
412
  echo ""
413
  echo "======================================================================"
414
+ echo " Inference succeeded!"
415
  echo "======================================================================"
416
  echo ""
417
+ echo "Output files:"
418
+ echo " Raw (with BPE): $OUTPUT_PATH"
419
+ echo " Cleaned result: $OUTPUT_CLEAN_PATH"
420
 
421
  if [ ! -z "$ATTENTION_ANALYSIS_DIR" ]; then
422
+ echo " Detailed analysis dir: $ATTENTION_ANALYSIS_DIR"
423
  echo ""
424
+ echo "Attention assets include:"
425
+ echo " - attention_heatmap.png"
426
+ echo " - word_frame_alignment.png"
427
+ echo " - gloss_to_frames.png"
428
+ echo " - analysis_report.txt"
429
+ echo " - attention_weights.npy"
430
+ echo " - attention_keyframes/ (per-gloss keyframe previews)"
431
+ echo " * peak feature frames per gloss"
432
+ echo " * heatmaps overlayed on the video frames"
433
  fi
434
 
435
  echo ""
436
+ echo "Recognition result (BPE removed):"
437
  echo "----------------------------------------------------------------------"
438
  head -5 "$OUTPUT_CLEAN_PATH" | sed 's/^/ /'
439
  echo "----------------------------------------------------------------------"
440
  echo ""
441
+ echo -e "${GREEN}✓ Full pipeline completed (SMKD → SLTUNET)${NC}"
442
  echo ""
443
 
444
+ # Clean temp directory
445
+ echo -e "${BLUE}Cleaning temporary files...${NC}"
446
  rm -rf "$TEMP_DIR"
447
+ echo " ✓ Temporary files removed"
448
  echo ""
449
  else
450
+ echo -e "${RED}Error: inference failed, no output generated${NC}"
 
451
  rm -rf "$TEMP_DIR"
452
  exit 1
453
  fi
SignX/inference_output/detailed_prediction_20260102_180915/23881350/attention_keyframes/keyframes_index.txt DELETED
@@ -1,27 +0,0 @@
1
- 关键帧索引
2
- ============================================================
3
-
4
- 样本目录: /research/cbim/vast/sf895/code/ControlWorld/plugins/SignX/inference_output/detailed_prediction_20260102_180915/23881350
5
- 视频路径: /common/users/sf895/output/huggingface_asllrp_repo/SignX/eval/tiny_test_data/good_videos/23881350.mp4
6
- 总关键帧数: 18
7
-
8
- 关键帧列表:
9
- ------------------------------------------------------------
10
- Gloss 0: keyframe_000_feat2_frame9_att0.338.jpg
11
- Gloss 1: keyframe_001_feat0_frame1_att0.358.jpg
12
- Gloss 2: keyframe_002_feat0_frame1_att0.353.jpg
13
- Gloss 3: keyframe_003_feat0_frame1_att0.403.jpg
14
- Gloss 4: keyframe_004_feat7_frame28_att0.240.jpg
15
- Gloss 5: keyframe_005_feat0_frame1_att0.195.jpg
16
- Gloss 6: keyframe_006_feat0_frame1_att0.346.jpg
17
- Gloss 7: keyframe_007_feat11_frame43_att0.358.jpg
18
- Gloss 8: keyframe_008_feat13_frame51_att0.303.jpg
19
- Gloss 9: keyframe_009_feat17_frame66_att0.248.jpg
20
- Gloss 10: keyframe_010_feat13_frame51_att0.297.jpg
21
- Gloss 11: keyframe_011_feat21_frame82_att0.287.jpg
22
- Gloss 12: keyframe_012_feat0_frame1_att0.413.jpg
23
- Gloss 13: keyframe_013_feat21_frame82_att0.284.jpg
24
- Gloss 14: keyframe_014_feat20_frame78_att0.171.jpg
25
- Gloss 15: keyframe_015_feat0_frame1_att0.314.jpg
26
- Gloss 16: keyframe_016_feat21_frame82_att0.262.jpg
27
- Gloss 17: keyframe_017_feat21_frame82_att0.289.jpg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
SignX/inference_output/detailed_prediction_20260102_180915/23881350/frame_alignment.json DELETED
@@ -1,59 +0,0 @@
1
- {
2
- "translation": "HAPPEN RAIN IX-1p STAY HOME",
3
- "words": [
4
- "HAPPEN",
5
- "RAIN",
6
- "IX-1p",
7
- "STAY",
8
- "HOME"
9
- ],
10
- "total_video_frames": 22,
11
- "frame_ranges": [
12
- {
13
- "word": "HAPPEN",
14
- "start_frame": 2,
15
- "end_frame": 2,
16
- "peak_frame": 2,
17
- "avg_attention": 0.33764514327049255,
18
- "confidence": "medium"
19
- },
20
- {
21
- "word": "RAIN",
22
- "start_frame": 0,
23
- "end_frame": 0,
24
- "peak_frame": 0,
25
- "avg_attention": 0.3576834201812744,
26
- "confidence": "medium"
27
- },
28
- {
29
- "word": "IX-1p",
30
- "start_frame": 0,
31
- "end_frame": 0,
32
- "peak_frame": 0,
33
- "avg_attention": 0.3532525599002838,
34
- "confidence": "medium"
35
- },
36
- {
37
- "word": "STAY",
38
- "start_frame": 0,
39
- "end_frame": 0,
40
- "peak_frame": 0,
41
- "avg_attention": 0.40251624584198,
42
- "confidence": "medium"
43
- },
44
- {
45
- "word": "HOME",
46
- "start_frame": 7,
47
- "end_frame": 7,
48
- "peak_frame": 7,
49
- "avg_attention": 0.24049112200737,
50
- "confidence": "medium"
51
- }
52
- ],
53
- "statistics": {
54
- "avg_confidence": 0.33831769824028013,
55
- "high_confidence_words": 0,
56
- "medium_confidence_words": 5,
57
- "low_confidence_words": 0
58
- }
59
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
SignX/inference_output/detailed_prediction_20260102_180915/23881350/translation.txt DELETED
@@ -1,3 +0,0 @@
1
- With BPE: HA@@ P@@ PE@@ N RA@@ I@@ N IX-1p STAY HOME
2
- Clean: HAPPEN RAIN IX-1p STAY HOME
3
- Ground Truth: HAPPEN RAIN IX-1p STAY HOME
 
 
 
 
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/analysis_report.txt RENAMED
@@ -2,39 +2,42 @@
2
  Sign Language Recognition - Attention分析报告
3
  ================================================================================
4
 
5
- 生成时间: 2026-01-02 18:09:21
6
 
7
  翻译结果:
8
  --------------------------------------------------------------------------------
9
- HAPPEN RAIN IX-1p STAY HOME
10
 
11
  视频信息:
12
  --------------------------------------------------------------------------------
13
- 总帧数: 22
14
- 词数量: 5
15
 
16
  Attention权重信息:
17
  --------------------------------------------------------------------------------
18
- 形状: (18, 22)
19
- - 解码步数: 18
20
 
21
  词-帧对应详情:
22
  ================================================================================
23
  No. Word Frames Peak Attn Conf
24
  --------------------------------------------------------------------------------
25
- 1 HAPPEN 2-2 2 0.338 medium
26
- 2 RAIN 0-0 0 0.358 medium
27
- 3 IX-1p 0-0 0 0.353 medium
28
- 4 STAY 0-0 0 0.403 medium
29
- 5 HOME 7-7 7 0.240 medium
 
 
 
30
 
31
  ================================================================================
32
 
33
  统计摘要:
34
  --------------------------------------------------------------------------------
35
- 平均attention权重: 0.338
36
- 高置信度词: 0 (0.0%)
37
- 中置信度词: 5 (100.0%)
38
  低置信度词: 0 (0.0%)
39
 
40
  ================================================================================
 
2
  Sign Language Recognition - Attention分析报告
3
  ================================================================================
4
 
5
+ 生成时间: 2026-01-02 18:20:20
6
 
7
  翻译结果:
8
  --------------------------------------------------------------------------------
9
+ #IF FRIEND GROUP/TOGETHER DEPART PARTY IX-1p JOIN IX-1p
10
 
11
  视频信息:
12
  --------------------------------------------------------------------------------
13
+ 总帧数: 28
14
+ 词数量: 8
15
 
16
  Attention权重信息:
17
  --------------------------------------------------------------------------------
18
+ 形状: (26, 28)
19
+ - 解码步数: 26
20
 
21
  词-帧对应详情:
22
  ================================================================================
23
  No. Word Frames Peak Attn Conf
24
  --------------------------------------------------------------------------------
25
+ 1 #IF 2-2 2 0.472 medium
26
+ 2 FRIEND 5-5 5 0.425 medium
27
+ 3 GROUP/TOGETHER 8-8 8 0.375 medium
28
+ 4 DEPART 27-27 27 0.348 medium
29
+ 5 PARTY 27-27 27 0.383 medium
30
+ 6 IX-1p 27-27 27 0.333 medium
31
+ 7 JOIN 11-11 11 0.520 high
32
+ 8 IX-1p 14-14 14 0.368 medium
33
 
34
  ================================================================================
35
 
36
  统计摘要:
37
  --------------------------------------------------------------------------------
38
+ 平均attention权重: 0.403
39
+ 高置信度词: 1 (12.5%)
40
+ 中置信度词: 7 (87.5%)
41
  低置信度词: 0 (0.0%)
42
 
43
  ================================================================================
SignX/inference_output/detailed_prediction_20260102_182015/632051/attention_heatmap.pdf ADDED
Binary file (34.2 kB). View file
 
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/attention_heatmap.png RENAMED
File without changes
SignX/inference_output/detailed_prediction_20260102_182015/632051/attention_keyframes/keyframes_index.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 关键帧索引
2
+ ============================================================
3
+
4
+ 样本目录: /research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/SignX/inference_output/detailed_prediction_20260102_182015/632051
5
+ 视频路径: /common/users/sf895/output/huggingface_asllrp_repo/SignX/eval/tiny_test_data/videos/632051.mp4
6
+ 总关键帧数: 26
7
+
8
+ 关键帧列表:
9
+ ------------------------------------------------------------
10
+ Gloss 0: keyframe_000_feat2_frame9_att0.472.jpg
11
+ Gloss 1: keyframe_001_feat5_frame20_att0.425.jpg
12
+ Gloss 2: keyframe_002_feat8_frame32_att0.375.jpg
13
+ Gloss 3: keyframe_003_feat27_frame104_att0.348.jpg
14
+ Gloss 4: keyframe_004_feat27_frame104_att0.383.jpg
15
+ Gloss 5: keyframe_005_feat27_frame104_att0.333.jpg
16
+ Gloss 6: keyframe_006_feat11_frame43_att0.520.jpg
17
+ Gloss 7: keyframe_007_feat14_frame54_att0.368.jpg
18
+ Gloss 8: keyframe_008_feat17_frame66_att0.252.jpg
19
+ Gloss 9: keyframe_009_feat19_frame73_att0.884.jpg
20
+ Gloss 10: keyframe_010_feat0_frame1_att0.118.jpg
21
+ Gloss 11: keyframe_011_feat27_frame104_att0.164.jpg
22
+ Gloss 12: keyframe_012_feat25_frame96_att0.265.jpg
23
+ Gloss 13: keyframe_013_feat25_frame96_att0.282.jpg
24
+ Gloss 14: keyframe_014_feat25_frame96_att0.278.jpg
25
+ Gloss 15: keyframe_015_feat25_frame96_att0.277.jpg
26
+ Gloss 16: keyframe_016_feat27_frame104_att0.219.jpg
27
+ Gloss 17: keyframe_017_feat27_frame104_att0.190.jpg
28
+ Gloss 18: keyframe_018_feat27_frame104_att0.225.jpg
29
+ Gloss 19: keyframe_019_feat23_frame88_att0.150.jpg
30
+ Gloss 20: keyframe_020_feat27_frame104_att0.151.jpg
31
+ Gloss 21: keyframe_021_feat25_frame96_att0.360.jpg
32
+ Gloss 22: keyframe_022_feat25_frame96_att0.153.jpg
33
+ Gloss 23: keyframe_023_feat27_frame104_att0.144.jpg
34
+ Gloss 24: keyframe_024_feat25_frame96_att0.144.jpg
35
+ Gloss 25: keyframe_025_feat27_frame104_att0.186.jpg
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/attention_weights.npy RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:db90d41d7bb154b5162dd389749f9b12b177c09c69d3961bd8b58585bae1baaa
3
- size 1712
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d89932ced21ae95e0d7e034d8b3917146effa747bf7236c5eed30dd8cb9a258a
3
+ size 3040
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/debug_video_path.txt RENAMED
@@ -1,4 +1,4 @@
1
- video_path = '/common/users/sf895/output/huggingface_asllrp_repo/SignX/eval/tiny_test_data/good_videos/23881350.mp4'
2
  video_path type = <class 'str'>
3
  video_path is None: False
4
  bool(video_path): True
 
1
+ video_path = '/common/users/sf895/output/huggingface_asllrp_repo/SignX/eval/tiny_test_data/videos/632051.mp4'
2
  video_path type = <class 'str'>
3
  video_path is None: False
4
  bool(video_path): True
SignX/inference_output/detailed_prediction_20260102_182015/632051/feature_frame_mapping.json ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "original_frame_count": 106,
3
+ "feature_count": 28,
4
+ "downsampling_ratio": 3.7857142857142856,
5
+ "fps": 24.0,
6
+ "mapping": [
7
+ {
8
+ "feature_index": 0,
9
+ "frame_start": 0,
10
+ "frame_end": 3,
11
+ "frame_count": 3
12
+ },
13
+ {
14
+ "feature_index": 1,
15
+ "frame_start": 3,
16
+ "frame_end": 7,
17
+ "frame_count": 4
18
+ },
19
+ {
20
+ "feature_index": 2,
21
+ "frame_start": 7,
22
+ "frame_end": 11,
23
+ "frame_count": 4
24
+ },
25
+ {
26
+ "feature_index": 3,
27
+ "frame_start": 11,
28
+ "frame_end": 15,
29
+ "frame_count": 4
30
+ },
31
+ {
32
+ "feature_index": 4,
33
+ "frame_start": 15,
34
+ "frame_end": 18,
35
+ "frame_count": 3
36
+ },
37
+ {
38
+ "feature_index": 5,
39
+ "frame_start": 18,
40
+ "frame_end": 22,
41
+ "frame_count": 4
42
+ },
43
+ {
44
+ "feature_index": 6,
45
+ "frame_start": 22,
46
+ "frame_end": 26,
47
+ "frame_count": 4
48
+ },
49
+ {
50
+ "feature_index": 7,
51
+ "frame_start": 26,
52
+ "frame_end": 30,
53
+ "frame_count": 4
54
+ },
55
+ {
56
+ "feature_index": 8,
57
+ "frame_start": 30,
58
+ "frame_end": 34,
59
+ "frame_count": 4
60
+ },
61
+ {
62
+ "feature_index": 9,
63
+ "frame_start": 34,
64
+ "frame_end": 37,
65
+ "frame_count": 3
66
+ },
67
+ {
68
+ "feature_index": 10,
69
+ "frame_start": 37,
70
+ "frame_end": 41,
71
+ "frame_count": 4
72
+ },
73
+ {
74
+ "feature_index": 11,
75
+ "frame_start": 41,
76
+ "frame_end": 45,
77
+ "frame_count": 4
78
+ },
79
+ {
80
+ "feature_index": 12,
81
+ "frame_start": 45,
82
+ "frame_end": 49,
83
+ "frame_count": 4
84
+ },
85
+ {
86
+ "feature_index": 13,
87
+ "frame_start": 49,
88
+ "frame_end": 53,
89
+ "frame_count": 4
90
+ },
91
+ {
92
+ "feature_index": 14,
93
+ "frame_start": 53,
94
+ "frame_end": 56,
95
+ "frame_count": 3
96
+ },
97
+ {
98
+ "feature_index": 15,
99
+ "frame_start": 56,
100
+ "frame_end": 60,
101
+ "frame_count": 4
102
+ },
103
+ {
104
+ "feature_index": 16,
105
+ "frame_start": 60,
106
+ "frame_end": 64,
107
+ "frame_count": 4
108
+ },
109
+ {
110
+ "feature_index": 17,
111
+ "frame_start": 64,
112
+ "frame_end": 68,
113
+ "frame_count": 4
114
+ },
115
+ {
116
+ "feature_index": 18,
117
+ "frame_start": 68,
118
+ "frame_end": 71,
119
+ "frame_count": 3
120
+ },
121
+ {
122
+ "feature_index": 19,
123
+ "frame_start": 71,
124
+ "frame_end": 75,
125
+ "frame_count": 4
126
+ },
127
+ {
128
+ "feature_index": 20,
129
+ "frame_start": 75,
130
+ "frame_end": 79,
131
+ "frame_count": 4
132
+ },
133
+ {
134
+ "feature_index": 21,
135
+ "frame_start": 79,
136
+ "frame_end": 83,
137
+ "frame_count": 4
138
+ },
139
+ {
140
+ "feature_index": 22,
141
+ "frame_start": 83,
142
+ "frame_end": 87,
143
+ "frame_count": 4
144
+ },
145
+ {
146
+ "feature_index": 23,
147
+ "frame_start": 87,
148
+ "frame_end": 90,
149
+ "frame_count": 3
150
+ },
151
+ {
152
+ "feature_index": 24,
153
+ "frame_start": 90,
154
+ "frame_end": 94,
155
+ "frame_count": 4
156
+ },
157
+ {
158
+ "feature_index": 25,
159
+ "frame_start": 94,
160
+ "frame_end": 98,
161
+ "frame_count": 4
162
+ },
163
+ {
164
+ "feature_index": 26,
165
+ "frame_start": 98,
166
+ "frame_end": 102,
167
+ "frame_count": 4
168
+ },
169
+ {
170
+ "feature_index": 27,
171
+ "frame_start": 102,
172
+ "frame_end": 106,
173
+ "frame_count": 4
174
+ }
175
+ ]
176
+ }
SignX/inference_output/detailed_prediction_20260102_182015/632051/frame_alignment.json ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "translation": "#IF FRIEND GROUP/TOGETHER DEPART PARTY IX-1p JOIN IX-1p",
3
+ "words": [
4
+ "#IF",
5
+ "FRIEND",
6
+ "GROUP/TOGETHER",
7
+ "DEPART",
8
+ "PARTY",
9
+ "IX-1p",
10
+ "JOIN",
11
+ "IX-1p"
12
+ ],
13
+ "total_video_frames": 28,
14
+ "frame_ranges": [
15
+ {
16
+ "word": "#IF",
17
+ "start_frame": 2,
18
+ "end_frame": 2,
19
+ "peak_frame": 2,
20
+ "avg_attention": 0.47214657068252563,
21
+ "confidence": "medium"
22
+ },
23
+ {
24
+ "word": "FRIEND",
25
+ "start_frame": 5,
26
+ "end_frame": 5,
27
+ "peak_frame": 5,
28
+ "avg_attention": 0.4252290427684784,
29
+ "confidence": "medium"
30
+ },
31
+ {
32
+ "word": "GROUP/TOGETHER",
33
+ "start_frame": 8,
34
+ "end_frame": 8,
35
+ "peak_frame": 8,
36
+ "avg_attention": 0.37518179416656494,
37
+ "confidence": "medium"
38
+ },
39
+ {
40
+ "word": "DEPART",
41
+ "start_frame": 27,
42
+ "end_frame": 27,
43
+ "peak_frame": 27,
44
+ "avg_attention": 0.3480324149131775,
45
+ "confidence": "medium"
46
+ },
47
+ {
48
+ "word": "PARTY",
49
+ "start_frame": 27,
50
+ "end_frame": 27,
51
+ "peak_frame": 27,
52
+ "avg_attention": 0.38299673795700073,
53
+ "confidence": "medium"
54
+ },
55
+ {
56
+ "word": "IX-1p",
57
+ "start_frame": 27,
58
+ "end_frame": 27,
59
+ "peak_frame": 27,
60
+ "avg_attention": 0.33272165060043335,
61
+ "confidence": "medium"
62
+ },
63
+ {
64
+ "word": "JOIN",
65
+ "start_frame": 11,
66
+ "end_frame": 11,
67
+ "peak_frame": 11,
68
+ "avg_attention": 0.5199229121208191,
69
+ "confidence": "high"
70
+ },
71
+ {
72
+ "word": "IX-1p",
73
+ "start_frame": 14,
74
+ "end_frame": 14,
75
+ "peak_frame": 14,
76
+ "avg_attention": 0.3677118122577667,
77
+ "confidence": "medium"
78
+ }
79
+ ],
80
+ "statistics": {
81
+ "avg_confidence": 0.4029928669333458,
82
+ "high_confidence_words": 1,
83
+ "medium_confidence_words": 7,
84
+ "low_confidence_words": 0
85
+ }
86
+ }
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/frame_alignment.pdf RENAMED
Binary files a/SignX/inference_output/detailed_prediction_20260102_180915/23881350/frame_alignment.pdf and b/SignX/inference_output/detailed_prediction_20260102_182015/632051/frame_alignment.pdf differ
 
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/frame_alignment.png RENAMED
File without changes
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/frame_alignment_short.pdf RENAMED
Binary files a/SignX/inference_output/detailed_prediction_20260102_180915/23881350/frame_alignment_short.pdf and b/SignX/inference_output/detailed_prediction_20260102_182015/632051/frame_alignment_short.pdf differ
 
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/frame_alignment_short.png RENAMED
File without changes
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_182015/632051}/gloss_to_frames.png RENAMED
File without changes
SignX/inference_output/detailed_prediction_20260102_182015/632051/interactive_alignment.html ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Interactive Word-Frame Alignment</title>
7
+ <style>
8
+ body {
9
+ font-family: 'Arial', sans-serif;
10
+ margin: 20px;
11
+ background-color: #f5f5f5;
12
+ }
13
+ .container {
14
+ max-width: 1800px;
15
+ margin: 0 auto;
16
+ background-color: white;
17
+ padding: 30px;
18
+ border-radius: 8px;
19
+ box-shadow: 0 2px 10px rgba(0,0,0,0.1);
20
+ }
21
+ h1 {
22
+ color: #333;
23
+ border-bottom: 3px solid #4CAF50;
24
+ padding-bottom: 10px;
25
+ margin-bottom: 20px;
26
+ }
27
+ .stats {
28
+ background-color: #E3F2FD;
29
+ padding: 15px;
30
+ border-radius: 5px;
31
+ margin-bottom: 20px;
32
+ border-left: 4px solid #2196F3;
33
+ font-size: 14px;
34
+ }
35
+ .controls {
36
+ background-color: #f9f9f9;
37
+ padding: 20px;
38
+ border-radius: 5px;
39
+ margin-bottom: 30px;
40
+ border: 1px solid #ddd;
41
+ }
42
+ .control-group {
43
+ margin-bottom: 15px;
44
+ }
45
+ label {
46
+ font-weight: bold;
47
+ display: inline-block;
48
+ width: 250px;
49
+ color: #555;
50
+ }
51
+ input[type="range"] {
52
+ width: 400px;
53
+ vertical-align: middle;
54
+ }
55
+ .value-display {
56
+ display: inline-block;
57
+ width: 80px;
58
+ font-family: monospace;
59
+ font-size: 14px;
60
+ color: #2196F3;
61
+ font-weight: bold;
62
+ }
63
+ .reset-btn {
64
+ margin-top: 15px;
65
+ padding: 10px 25px;
66
+ background-color: #2196F3;
67
+ color: white;
68
+ border: none;
69
+ border-radius: 5px;
70
+ cursor: pointer;
71
+ font-size: 14px;
72
+ font-weight: bold;
73
+ }
74
+ .reset-btn:hover {
75
+ background-color: #1976D2;
76
+ }
77
+ canvas {
78
+ border: 1px solid #999;
79
+ display: block;
80
+ margin: 20px auto;
81
+ background: white;
82
+ }
83
+ .legend {
84
+ margin-top: 20px;
85
+ padding: 15px;
86
+ background-color: #fff;
87
+ border: 1px solid #ddd;
88
+ border-radius: 5px;
89
+ }
90
+ .legend-item {
91
+ display: inline-block;
92
+ margin-right: 25px;
93
+ font-size: 13px;
94
+ margin-bottom: 10px;
95
+ }
96
+ .color-box {
97
+ display: inline-block;
98
+ width: 30px;
99
+ height: 15px;
100
+ margin-right: 8px;
101
+ vertical-align: middle;
102
+ border: 1px solid #666;
103
+ }
104
+ .info-panel {
105
+ margin-top: 20px;
106
+ padding: 15px;
107
+ background-color: #f9f9f9;
108
+ border-radius: 5px;
109
+ border: 1px solid #ddd;
110
+ }
111
+ .confidence {
112
+ display: inline-block;
113
+ padding: 3px 10px;
114
+ border-radius: 10px;
115
+ font-weight: bold;
116
+ font-size: 11px;
117
+ text-transform: uppercase;
118
+ }
119
+ .confidence.high {
120
+ background-color: #4CAF50;
121
+ color: white;
122
+ }
123
+ .confidence.medium {
124
+ background-color: #FF9800;
125
+ color: white;
126
+ }
127
+ .confidence.low {
128
+ background-color: #f44336;
129
+ color: white;
130
+ }
131
+ </style>
132
+ </head>
133
+ <body>
134
+ <div class="container">
135
+ <h1>🎯 Interactive Word-to-Frame Alignment Visualizer</h1>
136
+
137
+ <div class="stats">
138
+ <strong>Translation:</strong> #IF FRIEND GROUP/TOGETHER DEPART PARTY IX-1p JOIN IX-1p<br>
139
+ <strong>Total Words:</strong> 8 |
140
+ <strong>Total Features:</strong> 28
141
+ </div>
142
+
143
+ <div class="controls">
144
+ <h3>⚙️ Threshold Controls</h3>
145
+
146
+ <div class="control-group">
147
+ <label for="peak-threshold">Peak Threshold (% of max):</label>
148
+ <input type="range" id="peak-threshold" min="1" max="100" value="90" step="1">
149
+ <span class="value-display" id="peak-threshold-value">90%</span>
150
+ <br>
151
+ <small style="margin-left: 255px; color: #666;">
152
+ 帧的注意力权重 ≥ (峰值权重 × 阈值%) 时被认为是"显著帧"
153
+ </small>
154
+ </div>
155
+
156
+ <div class="control-group">
157
+ <label for="confidence-high">High Confidence (avg attn >):</label>
158
+ <input type="range" id="confidence-high" min="0" max="100" value="50" step="1">
159
+ <span class="value-display" id="confidence-high-value">0.50</span>
160
+ </div>
161
+
162
+ <div class="control-group">
163
+ <label for="confidence-medium">Medium Confidence (avg attn >):</label>
164
+ <input type="range" id="confidence-medium" min="0" max="100" value="20" step="1">
165
+ <span class="value-display" id="confidence-medium-value">0.20</span>
166
+ </div>
167
+
168
+ <button class="reset-btn" onclick="resetDefaults()">
169
+ Reset to Defaults
170
+ </button>
171
+ </div>
172
+
173
+ <div>
174
+ <h3>Word-to-Frame Alignment</h3>
175
+ <p style="color: #666; font-size: 13px;">
176
+ 每个词显示为彩色矩形,宽度表示该词对应的特征帧范围。★ = 峰值帧。矩形内部显示注意力权重波形。
177
+ </p>
178
+ <canvas id="alignment-canvas" width="1600" height="600"></canvas>
179
+
180
+ <h3 style="margin-top: 30px;">Timeline Progress Bar</h3>
181
+ <canvas id="timeline-canvas" width="1600" height="100"></canvas>
182
+
183
+ <div class="legend">
184
+ <strong>Legend:</strong><br><br>
185
+ <div class="legend-item">
186
+ <span class="confidence high">High</span>
187
+ <span class="confidence medium">Medium</span>
188
+ <span class="confidence low">Low</span>
189
+ Confidence Levels (opacity reflects confidence)
190
+ </div>
191
+ <div class="legend-item">
192
+ <span style="color: red; font-size: 20px;">★</span>
193
+ Peak Frame (highest attention)
194
+ </div>
195
+ <div class="legend-item">
196
+ <span style="color: blue;">━</span>
197
+ Attention Waveform (within word region)
198
+ </div>
199
+ </div>
200
+ </div>
201
+
202
+ <div class="info-panel">
203
+ <h3>Alignment Details</h3>
204
+ <div id="alignment-details"></div>
205
+ </div>
206
+ </div>
207
+
208
+ <script>
209
+ // Attention data from Python
210
+ const attentionData = [{"word": "#IF", "word_idx": 0, "weights": [0.013499895110726357, 0.02982642501592636, 0.47214657068252563, 0.4107391834259033, 0.04950176924467087, 0.011385880410671234, 0.007043282967060804, 0.0014652750687673688, 0.0005238102748990059, 0.00040972864371724427, 0.0001160625834017992, 6.416538963094354e-05, 5.9505786339286715e-05, 5.076597517472692e-05, 6.82844765833579e-05, 0.00012157609307905659, 6.597878382308409e-05, 0.00010269331687595695, 0.00013462362403515726, 6.423696322599426e-05, 8.642762986710295e-05, 9.25226995605044e-05, 0.00011670421372400597, 0.0001578366500325501, 0.00020240909361746162, 0.0003825947642326355, 0.0007172566256485879, 0.0008544913143850863]}, {"word": "FRIEND", "word_idx": 1, "weights": [0.009660173207521439, 0.010518566705286503, 0.011222519911825657, 0.014483344741165638, 0.1795402616262436, 0.4252290427684784, 0.25737643241882324, 0.05393827706575394, 0.01512613520026207, 0.013365501537919044, 0.002376752672716975, 0.00014935070066712797, 8.692959818290547e-05, 0.0004998841905035079, 0.0008451194153167307, 0.0011626698542386293, 0.00042453958303667605, 0.00017692227265797555, 0.00016767902707215399, 4.8644251364748925e-05, 8.348096889676526e-05, 0.0001094180770451203, 0.00030694258748553693, 0.0002885134017560631, 0.00031121523352339864, 0.0006241592927835882, 0.0008697768207639456, 0.0010077793849632144]}, {"word": "GROUP/TOGETHER", "word_idx": 2, "weights": [0.010994982905685902, 0.004551935940980911, 0.002873026067391038, 0.003936904948204756, 0.008626177906990051, 0.014811795204877853, 0.02318989858031273, 0.12032425403594971, 0.37518179416656494, 0.2971201539039612, 0.08549409359693527, 0.014250868931412697, 0.008063109591603279, 0.00339426938444376, 0.0037573552690446377, 0.004879903048276901, 0.0018731161253526807, 0.0011690640822052956, 0.0013268929906189442, 0.0007135092164389789, 0.000632062554359436, 0.000777124660089612, 0.0009553946438245475, 0.0009487943025305867, 0.0007010120898485184, 0.001496487995609641, 0.0037835948169231415, 0.004172381013631821]}, {"word": "DEPART", "word_idx": 3, "weights": [0.22514434158802032, 0.12377114593982697, 0.00781786348670721, 0.0074639273807406425, 0.01298774778842926, 0.00438598683103919, 0.004350316245108843, 0.006786263547837734, 0.006216868292540312, 0.0061629218980669975, 0.004193580709397793, 0.0015793128404766321, 0.0011525226291269064, 0.0014239393640309572, 0.0007423617644235492, 0.0008507575839757919, 0.0008870838792063296, 0.00024679809575900435, 0.00034805957693606615, 0.005230794660747051, 0.0011639633448794484, 0.001367528340779245, 0.010013289749622345, 0.018452608957886696, 0.0018141826149076223, 0.001117207808420062, 0.19629621505737305, 0.3480324149131775]}, {"word": "PARTY", "word_idx": 4, "weights": [0.1664648950099945, 0.06123431771993637, 0.0020844682585448027, 0.0020428383722901344, 0.0058554718270897865, 0.004360921215265989, 0.004692059941589832, 0.009323552250862122, 0.015183845534920692, 0.016528787091374397, 0.015347503125667572, 0.007253072690218687, 0.005231750197708607, 0.009598116390407085, 0.00704572768881917, 0.007053114008158445, 0.006423295009881258, 0.0010452027199789882, 0.0009786873124539852, 0.004494669381529093, 0.005323153454810381, 0.006433582864701748, 0.022334398701786995, 0.03912580758333206, 0.004556183237582445, 0.0021732028108090162, 0.18481463193893433, 0.38299673795700073]}, {"word": "IX-1p", "word_idx": 5, "weights": [0.2268882542848587, 0.10439852625131607, 0.005018203519284725, 0.005008632782846689, 0.005379822570830584, 0.00215631234459579, 0.0024426421150565147, 0.007580526173114777, 0.011461855843663216, 0.010575865395367146, 0.010204891674220562, 0.004322281572967768, 0.0023845669347792864, 0.0016265056328848004, 0.0011272492120042443, 0.0014091862831264734, 0.0019118450582027435, 0.0019068039255216718, 0.002558623207733035, 0.005466249771416187, 0.002576562575995922, 0.0033958060666918755, 0.014094071462750435, 0.03357496112585068, 0.005502632353454828, 0.003941097296774387, 0.19036439061164856, 0.33272165060043335]}, {"word": "JOIN", "word_idx": 6, "weights": [0.006536237895488739, 0.002151536289602518, 0.0006580766057595611, 0.0008207014761865139, 0.0003112705599050969, 0.0003111894184257835, 0.0008894064230844378, 0.004121360369026661, 0.01069970428943634, 0.008291625417768955, 0.01931559480726719, 0.5199229121208191, 0.40212148427963257, 0.004480497911572456, 0.0010337198618799448, 0.0007998707587830722, 0.00024323497200384736, 7.284984894795343e-05, 0.00011325528612360358, 0.00540410028770566, 0.0011726750526577234, 0.0009422790608368814, 0.0003188242844771594, 0.00024731658049859107, 3.1396619306178764e-05, 4.355102646513842e-05, 0.0036189379170536995, 0.005326398182660341]}, {"word": "IX-1p", "word_idx": 7, "weights": [0.0013159031514078379, 0.0007256589597091079, 0.00017777174070943147, 0.0001744187029544264, 0.00025140171055682003, 0.00039260604535229504, 0.0003829205525107682, 0.000333531730575487, 0.0007308170897886157, 0.0010108469286933541, 0.0015992401167750359, 0.003526317421346903, 0.012568545527756214, 0.2852487564086914, 0.3677118122577667, 0.19535787403583527, 0.07697467505931854, 0.012815488502383232, 0.007124335505068302, 0.0009805350564420223, 0.007633780129253864, 0.007437399588525295, 0.005485337693244219, 0.003693929873406887, 0.0026681837625801563, 0.0011110405903309584, 0.0008843602845445275, 0.0016825739294290543]}];
211
+ const numGlosses = 8;
212
+ const numFeatures = 28;
213
+
214
+ // Colors for different words (matching matplotlib tab20)
215
+ const colors = [
216
+ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
217
+ '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf',
218
+ '#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#c5b0d5',
219
+ '#c49c94', '#f7b6d2', '#c7c7c7', '#dbdb8d', '#9edae5'
220
+ ];
221
+
222
+ // Get controls
223
+ const peakThresholdSlider = document.getElementById('peak-threshold');
224
+ const peakThresholdValue = document.getElementById('peak-threshold-value');
225
+ const confidenceHighSlider = document.getElementById('confidence-high');
226
+ const confidenceHighValue = document.getElementById('confidence-high-value');
227
+ const confidenceMediumSlider = document.getElementById('confidence-medium');
228
+ const confidenceMediumValue = document.getElementById('confidence-medium-value');
229
+ const alignmentCanvas = document.getElementById('alignment-canvas');
230
+ const timelineCanvas = document.getElementById('timeline-canvas');
231
+ const alignmentCtx = alignmentCanvas.getContext('2d');
232
+ const timelineCtx = timelineCanvas.getContext('2d');
233
+
234
+ // Update displays when sliders change
235
+ peakThresholdSlider.oninput = function() {
236
+ peakThresholdValue.textContent = this.value + '%';
237
+ updateVisualization();
238
+ };
239
+
240
+ confidenceHighSlider.oninput = function() {
241
+ confidenceHighValue.textContent = (this.value / 100).toFixed(2);
242
+ updateVisualization();
243
+ };
244
+
245
+ confidenceMediumSlider.oninput = function() {
246
+ confidenceMediumValue.textContent = (this.value / 100).toFixed(2);
247
+ updateVisualization();
248
+ };
249
+
250
+ function resetDefaults() {
251
+ peakThresholdSlider.value = 90;
252
+ confidenceHighSlider.value = 50;
253
+ confidenceMediumSlider.value = 20;
254
+ peakThresholdValue.textContent = '90%';
255
+ confidenceHighValue.textContent = '0.50';
256
+ confidenceMediumValue.textContent = '0.20';
257
+ updateVisualization();
258
+ }
259
+
260
+ function calculateAlignment(weights, peakThreshold) {
261
+ // Find peak
262
+ let peakIdx = 0;
263
+ let peakWeight = weights[0];
264
+ for (let i = 1; i < weights.length; i++) {
265
+ if (weights[i] > peakWeight) {
266
+ peakWeight = weights[i];
267
+ peakIdx = i;
268
+ }
269
+ }
270
+
271
+ // Find significant frames
272
+ const threshold = peakWeight * (peakThreshold / 100);
273
+ let startIdx = peakIdx;
274
+ let endIdx = peakIdx;
275
+ let sumWeight = 0;
276
+ let count = 0;
277
+
278
+ for (let i = 0; i < weights.length; i++) {
279
+ if (weights[i] >= threshold) {
280
+ if (i < startIdx) startIdx = i;
281
+ if (i > endIdx) endIdx = i;
282
+ sumWeight += weights[i];
283
+ count++;
284
+ }
285
+ }
286
+
287
+ const avgWeight = count > 0 ? sumWeight / count : peakWeight;
288
+
289
+ return {
290
+ startIdx: startIdx,
291
+ endIdx: endIdx,
292
+ peakIdx: peakIdx,
293
+ peakWeight: peakWeight,
294
+ avgWeight: avgWeight,
295
+ threshold: threshold
296
+ };
297
+ }
298
+
299
+ function getConfidenceLevel(avgWeight, highThreshold, mediumThreshold) {
300
+ if (avgWeight > highThreshold) return 'high';
301
+ if (avgWeight > mediumThreshold) return 'medium';
302
+ return 'low';
303
+ }
304
+
305
+ function drawAlignmentChart() {
306
+ const peakThreshold = parseInt(peakThresholdSlider.value);
307
+ const highThreshold = parseInt(confidenceHighSlider.value) / 100;
308
+ const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;
309
+
310
+ // Canvas dimensions
311
+ const width = alignmentCanvas.width;
312
+ const height = alignmentCanvas.height;
313
+ const leftMargin = 180;
314
+ const rightMargin = 50;
315
+ const topMargin = 60;
316
+ const bottomMargin = 80;
317
+
318
+ const plotWidth = width - leftMargin - rightMargin;
319
+ const plotHeight = height - topMargin - bottomMargin;
320
+
321
+ const rowHeight = plotHeight / numGlosses;
322
+ const featureWidth = plotWidth / numFeatures;
323
+
324
+ // Clear canvas
325
+ alignmentCtx.clearRect(0, 0, width, height);
326
+
327
+ // Draw title
328
+ alignmentCtx.fillStyle = '#333';
329
+ alignmentCtx.font = 'bold 18px Arial';
330
+ alignmentCtx.textAlign = 'center';
331
+ alignmentCtx.fillText('Word-to-Frame Alignment', width / 2, 30);
332
+ alignmentCtx.font = '13px Arial';
333
+ alignmentCtx.fillText('(based on attention peaks, ★ = peak frame)', width / 2, 48);
334
+
335
+ // Calculate alignments
336
+ const alignments = [];
337
+ for (let wordIdx = 0; wordIdx < numGlosses; wordIdx++) {
338
+ const data = attentionData[wordIdx];
339
+ const alignment = calculateAlignment(data.weights, peakThreshold);
340
+ alignment.word = data.word;
341
+ alignment.wordIdx = wordIdx;
342
+ alignment.weights = data.weights;
343
+ alignments.push(alignment);
344
+ }
345
+
346
+ // Draw grid
347
+ alignmentCtx.strokeStyle = '#e0e0e0';
348
+ alignmentCtx.lineWidth = 0.5;
349
+ for (let i = 0; i <= numFeatures; i++) {
350
+ const x = leftMargin + i * featureWidth;
351
+ alignmentCtx.beginPath();
352
+ alignmentCtx.moveTo(x, topMargin);
353
+ alignmentCtx.lineTo(x, topMargin + plotHeight);
354
+ alignmentCtx.stroke();
355
+ }
356
+
357
+ // Draw word regions
358
+ for (let wordIdx = 0; wordIdx < numGlosses; wordIdx++) {
359
+ const alignment = alignments[wordIdx];
360
+ const confidence = getConfidenceLevel(alignment.avgWeight, highThreshold, mediumThreshold);
361
+ const y = topMargin + wordIdx * rowHeight;
362
+
363
+ // Alpha based on confidence
364
+ const alpha = confidence === 'high' ? 0.9 : confidence === 'medium' ? 0.7 : 0.5;
365
+
366
+ // Draw rectangle for word region
367
+ const startX = leftMargin + alignment.startIdx * featureWidth;
368
+ const rectWidth = (alignment.endIdx - alignment.startIdx + 1) * featureWidth;
369
+
370
+ alignmentCtx.fillStyle = colors[wordIdx % 20];
371
+ alignmentCtx.globalAlpha = alpha;
372
+ alignmentCtx.fillRect(startX, y, rectWidth, rowHeight * 0.8);
373
+ alignmentCtx.globalAlpha = 1.0;
374
+
375
+ // Draw border
376
+ alignmentCtx.strokeStyle = '#000';
377
+ alignmentCtx.lineWidth = 2;
378
+ alignmentCtx.strokeRect(startX, y, rectWidth, rowHeight * 0.8);
379
+
380
+ // Draw attention waveform inside rectangle
381
+ alignmentCtx.strokeStyle = 'rgba(0, 0, 255, 0.8)';
382
+ alignmentCtx.lineWidth = 1.5;
383
+ alignmentCtx.beginPath();
384
+ for (let i = alignment.startIdx; i <= alignment.endIdx; i++) {
385
+ const x = leftMargin + i * featureWidth + featureWidth / 2;
386
+ const weight = alignment.weights[i];
387
+ const maxWeight = alignment.peakWeight;
388
+ const normalizedWeight = weight / (maxWeight * 1.2); // Scale for visibility
389
+ const waveY = y + rowHeight * 0.8 - (normalizedWeight * rowHeight * 0.6);
390
+
391
+ if (i === alignment.startIdx) {
392
+ alignmentCtx.moveTo(x, waveY);
393
+ } else {
394
+ alignmentCtx.lineTo(x, waveY);
395
+ }
396
+ }
397
+ alignmentCtx.stroke();
398
+
399
+ // Draw word label
400
+ const labelX = startX + rectWidth / 2;
401
+ const labelY = y + rowHeight * 0.4;
402
+
403
+ alignmentCtx.fillStyle = 'rgba(0, 0, 0, 0.7)';
404
+ alignmentCtx.fillRect(labelX - 60, labelY - 12, 120, 24);
405
+ alignmentCtx.fillStyle = '#fff';
406
+ alignmentCtx.font = 'bold 13px Arial';
407
+ alignmentCtx.textAlign = 'center';
408
+ alignmentCtx.textBaseline = 'middle';
409
+ alignmentCtx.fillText(alignment.word, labelX, labelY);
410
+
411
+ // Mark peak frame with star
412
+ const peakX = leftMargin + alignment.peakIdx * featureWidth + featureWidth / 2;
413
+ const peakY = y + rowHeight * 0.4;
414
+
415
+ // Draw star
416
+ alignmentCtx.fillStyle = '#ff0000';
417
+ alignmentCtx.strokeStyle = '#ffff00';
418
+ alignmentCtx.lineWidth = 1.5;
419
+ alignmentCtx.font = '20px Arial';
420
+ alignmentCtx.textAlign = 'center';
421
+ alignmentCtx.strokeText('★', peakX, peakY);
422
+ alignmentCtx.fillText('★', peakX, peakY);
423
+
424
+ // Y-axis label (word names)
425
+ alignmentCtx.fillStyle = '#333';
426
+ alignmentCtx.font = '12px Arial';
427
+ alignmentCtx.textAlign = 'right';
428
+ alignmentCtx.textBaseline = 'middle';
429
+ alignmentCtx.fillText(alignment.word, leftMargin - 10, y + rowHeight * 0.4);
430
+ }
431
+
432
+ // Draw horizontal grid lines
433
+ alignmentCtx.strokeStyle = '#ccc';
434
+ alignmentCtx.lineWidth = 0.5;
435
+ for (let i = 0; i <= numGlosses; i++) {
436
+ const y = topMargin + i * rowHeight;
437
+ alignmentCtx.beginPath();
438
+ alignmentCtx.moveTo(leftMargin, y);
439
+ alignmentCtx.lineTo(leftMargin + plotWidth, y);
440
+ alignmentCtx.stroke();
441
+ }
442
+
443
+ // Draw axes
444
+ alignmentCtx.strokeStyle = '#000';
445
+ alignmentCtx.lineWidth = 2;
446
+ alignmentCtx.strokeRect(leftMargin, topMargin, plotWidth, plotHeight);
447
+
448
+ // X-axis labels (frame indices)
449
+ alignmentCtx.fillStyle = '#000';
450
+ alignmentCtx.font = '11px Arial';
451
+ alignmentCtx.textAlign = 'center';
452
+ alignmentCtx.textBaseline = 'top';
453
+ for (let i = 0; i < numFeatures; i++) {
454
+ const x = leftMargin + i * featureWidth + featureWidth / 2;
455
+ alignmentCtx.fillText(i.toString(), x, topMargin + plotHeight + 10);
456
+ }
457
+
458
+ // Axis titles
459
+ alignmentCtx.fillStyle = '#333';
460
+ alignmentCtx.font = 'bold 14px Arial';
461
+ alignmentCtx.textAlign = 'center';
462
+ alignmentCtx.fillText('Feature Frame Index', leftMargin + plotWidth / 2, height - 20);
463
+
464
+ alignmentCtx.save();
465
+ alignmentCtx.translate(30, topMargin + plotHeight / 2);
466
+ alignmentCtx.rotate(-Math.PI / 2);
467
+ alignmentCtx.fillText('Generated Word', 0, 0);
468
+ alignmentCtx.restore();
469
+
470
+ return alignments;
471
+ }
472
+
473
+ function drawTimeline(alignments) {
474
+ const highThreshold = parseInt(confidenceHighSlider.value) / 100;
475
+ const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;
476
+
477
+ const width = timelineCanvas.width;
478
+ const height = timelineCanvas.height;
479
+ const leftMargin = 180;
480
+ const rightMargin = 50;
481
+ const plotWidth = width - leftMargin - rightMargin;
482
+ const featureWidth = plotWidth / numFeatures;
483
+
484
+ // Clear canvas
485
+ timelineCtx.clearRect(0, 0, width, height);
486
+
487
+ // Background bar
488
+ timelineCtx.fillStyle = '#ddd';
489
+ timelineCtx.fillRect(leftMargin, 30, plotWidth, 40);
490
+ timelineCtx.strokeStyle = '#000';
491
+ timelineCtx.lineWidth = 2;
492
+ timelineCtx.strokeRect(leftMargin, 30, plotWidth, 40);
493
+
494
+ // Draw word regions on timeline
495
+ for (let wordIdx = 0; wordIdx < alignments.length; wordIdx++) {
496
+ const alignment = alignments[wordIdx];
497
+ const confidence = getConfidenceLevel(alignment.avgWeight, highThreshold, mediumThreshold);
498
+ const alpha = confidence === 'high' ? 0.9 : confidence === 'medium' ? 0.7 : 0.5;
499
+
500
+ const startX = leftMargin + alignment.startIdx * featureWidth;
501
+ const rectWidth = (alignment.endIdx - alignment.startIdx + 1) * featureWidth;
502
+
503
+ timelineCtx.fillStyle = colors[wordIdx % 20];
504
+ timelineCtx.globalAlpha = alpha;
505
+ timelineCtx.fillRect(startX, 30, rectWidth, 40);
506
+ timelineCtx.globalAlpha = 1.0;
507
+ timelineCtx.strokeStyle = '#000';
508
+ timelineCtx.lineWidth = 0.5;
509
+ timelineCtx.strokeRect(startX, 30, rectWidth, 40);
510
+ }
511
+
512
+ // Title
513
+ timelineCtx.fillStyle = '#333';
514
+ timelineCtx.font = 'bold 13px Arial';
515
+ timelineCtx.textAlign = 'left';
516
+ timelineCtx.fillText('Timeline Progress Bar', leftMargin, 20);
517
+ }
518
+
519
+ function updateDetailsPanel(alignments, highThreshold, mediumThreshold) {
520
+ const panel = document.getElementById('alignment-details');
521
+ let html = '<table style="width: 100%; border-collapse: collapse;">';
522
+ html += '<tr style="background: #f0f0f0; font-weight: bold;">';
523
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Word</th>';
524
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Feature Range</th>';
525
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Peak</th>';
526
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Span</th>';
527
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Avg Attention</th>';
528
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Confidence</th>';
529
+ html += '</tr>';
530
+
531
+ for (const align of alignments) {
532
+ const confidence = getConfidenceLevel(align.avgWeight, highThreshold, mediumThreshold);
533
+ const span = align.endIdx - align.startIdx + 1;
534
+
535
+ html += '<tr>';
536
+ html += `<td style="padding: 8px; border: 1px solid #ddd;"><strong>${align.word}</strong></td>`;
537
+ html += `<td style="padding: 8px; border: 1px solid #ddd;">${align.startIdx} → ${align.endIdx}</td>`;
538
+ html += `<td style="padding: 8px; border: 1px solid #ddd;">${align.peakIdx}</td>`;
539
+ html += `<td style="padding: 8px; border: 1px solid #ddd;">${span}</td>`;
540
+ html += `<td style="padding: 8px; border: 1px solid #ddd;">${align.avgWeight.toFixed(4)}</td>`;
541
+ html += `<td style="padding: 8px; border: 1px solid #ddd;"><span class="confidence ${confidence}">${confidence}</span></td>`;
542
+ html += '</tr>';
543
+ }
544
+
545
+ html += '</table>';
546
+ panel.innerHTML = html;
547
+ }
548
+
549
+ function updateVisualization() {
550
+ const alignments = drawAlignmentChart();
551
+ drawTimeline(alignments);
552
+ const highThreshold = parseInt(confidenceHighSlider.value) / 100;
553
+ const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;
554
+ updateDetailsPanel(alignments, highThreshold, mediumThreshold);
555
+ }
556
+
557
+ // Event listeners for sliders
558
+ peakSlider.addEventListener('input', function() {
559
+ peakValue.textContent = peakSlider.value + '%';
560
+ updateVisualization();
561
+ });
562
+
563
+ confidenceHighSlider.addEventListener('input', function() {
564
+ const val = parseInt(confidenceHighSlider.value) / 100;
565
+ confidenceHighValue.textContent = val.toFixed(2);
566
+ updateVisualization();
567
+ });
568
+
569
+ confidenceMediumSlider.addEventListener('input', function() {
570
+ const val = parseInt(confidenceMediumSlider.value) / 100;
571
+ confidenceMediumValue.textContent = val.toFixed(2);
572
+ updateVisualization();
573
+ });
574
+
575
+ // Initial visualization
576
+ updateVisualization();
577
+ </script>
578
+ </body>
579
+ </html>
SignX/inference_output/detailed_prediction_20260102_182015/632051/translation.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ With BPE: #IF FRIEND GROUP/TOGE@@ TH@@ E@@ R DEPART PARTY IX-1p JO@@ I@@ N IX-1p
2
+ Clean: #IF FRIEND GROUP/TOGETHER DEPART PARTY IX-1p JOIN IX-1p
3
+ Ground Truth: #IF FRIEND GROUP/TOGETHER GO-OUT PARTY IX-1p JOIN IX-1p
SignX/inference_output/detailed_prediction_20260102_183038/97998032/analysis_report.txt ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ================================================================================
2
+ Sign Language Recognition - Attention Analysis Report
3
+ ================================================================================
4
+
5
+ Generated at: 2026-01-02 18:30:43
6
+
7
+ Translation:
8
+ --------------------------------------------------------------------------------
9
+ BOX/ROOM REALLY BIG #DOG "I don't know"
10
+
11
+ Video info:
12
+ --------------------------------------------------------------------------------
13
+ Total feature frames: 19
14
+ Word count: 7
15
+
16
+ Attention tensor:
17
+ --------------------------------------------------------------------------------
18
+ Shape: (30, 19)
19
+ - Decoder steps: 30
20
+
21
+ Word-to-frame details:
22
+ ================================================================================
23
+ No. Word Frames Peak Attn Conf
24
+ --------------------------------------------------------------------------------
25
+ 1 BOX/ROOM 3-3 3 0.557 high
26
+ 2 REALLY 7-7 7 0.479 medium
27
+ 3 BIG 9-9 9 0.435 medium
28
+ 4 #DOG 12-14 14 0.160 low
29
+ 5 "I 7-7 7 0.448 medium
30
+ 6 don't 9-9 9 0.445 medium
31
+ 7 know" 14-15 15 0.172 low
32
+
33
+ ================================================================================
34
+
35
+ Summary:
36
+ --------------------------------------------------------------------------------
37
+ Average attention weight: 0.385
38
+ High-confidence words: 1 (14.3%)
39
+ Medium-confidence words: 4 (57.1%)
40
+ Low-confidence words: 2 (28.6%)
41
+
42
+ ================================================================================
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_183038/97998032}/attention_heatmap.pdf RENAMED
Binary files a/SignX/inference_output/detailed_prediction_20260102_180915/23881350/attention_heatmap.pdf and b/SignX/inference_output/detailed_prediction_20260102_183038/97998032/attention_heatmap.pdf differ
 
SignX/inference_output/detailed_prediction_20260102_183038/97998032/attention_heatmap.png ADDED

Git LFS Details

  • SHA256: f64100d76a27bdaddcda1b7c6b4c6363f61208dcbb7f3907050ce41816ebb19f
  • Pointer size: 130 Bytes
  • Size of remote file: 82.9 kB
SignX/inference_output/detailed_prediction_20260102_183038/97998032/attention_keyframes/keyframes_index.txt ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attention Keyframe Index
2
+ ============================================================
3
+
4
+ Sample directory: /research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/SignX/inference_output/detailed_prediction_20260102_183038/97998032
5
+ Video path: /common/users/sf895/output/huggingface_asllrp_repo/SignX/eval/tiny_test_data/videos/97998032.mp4
6
+ Total keyframes: 30
7
+
8
+ Keyframe list:
9
+ ------------------------------------------------------------
10
+ Gloss 0: keyframe_000_feat3_frame13_att0.557.jpg
11
+ Gloss 1: keyframe_001_feat7_frame28_att0.479.jpg
12
+ Gloss 2: keyframe_002_feat9_frame35_att0.435.jpg
13
+ Gloss 3: keyframe_003_feat14_frame54_att0.166.jpg
14
+ Gloss 4: keyframe_004_feat7_frame28_att0.448.jpg
15
+ Gloss 5: keyframe_005_feat9_frame35_att0.445.jpg
16
+ Gloss 6: keyframe_006_feat15_frame58_att0.181.jpg
17
+ Gloss 7: keyframe_007_feat0_frame1_att0.212.jpg
18
+ Gloss 8: keyframe_008_feat17_frame66_att0.165.jpg
19
+ Gloss 9: keyframe_009_feat17_frame66_att0.158.jpg
20
+ Gloss 10: keyframe_010_feat18_frame70_att0.164.jpg
21
+ Gloss 11: keyframe_011_feat17_frame66_att0.163.jpg
22
+ Gloss 12: keyframe_012_feat17_frame66_att0.156.jpg
23
+ Gloss 13: keyframe_013_feat0_frame1_att0.227.jpg
24
+ Gloss 14: keyframe_014_feat0_frame1_att0.224.jpg
25
+ Gloss 15: keyframe_015_feat0_frame1_att0.202.jpg
26
+ Gloss 16: keyframe_016_feat0_frame1_att0.240.jpg
27
+ Gloss 17: keyframe_017_feat17_frame66_att0.149.jpg
28
+ Gloss 18: keyframe_018_feat0_frame1_att0.252.jpg
29
+ Gloss 19: keyframe_019_feat0_frame1_att0.240.jpg
30
+ Gloss 20: keyframe_020_feat0_frame1_att0.241.jpg
31
+ Gloss 21: keyframe_021_feat0_frame1_att0.289.jpg
32
+ Gloss 22: keyframe_022_feat0_frame1_att0.289.jpg
33
+ Gloss 23: keyframe_023_feat0_frame1_att0.244.jpg
34
+ Gloss 24: keyframe_024_feat15_frame58_att0.187.jpg
35
+ Gloss 25: keyframe_025_feat0_frame1_att0.239.jpg
36
+ Gloss 26: keyframe_026_feat0_frame1_att0.266.jpg
37
+ Gloss 27: keyframe_027_feat0_frame1_att0.193.jpg
38
+ Gloss 28: keyframe_028_feat18_frame70_att0.173.jpg
39
+ Gloss 29: keyframe_029_feat0_frame1_att0.242.jpg
SignX/inference_output/detailed_prediction_20260102_183038/97998032/attention_weights.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9e5cdf1f92b3111bd9aadfeb12979448f8511a5aac4809abbcffd3ae863a320
3
+ size 2408
SignX/inference_output/detailed_prediction_20260102_183038/97998032/debug_video_path.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ video_path = '/common/users/sf895/output/huggingface_asllrp_repo/SignX/eval/tiny_test_data/videos/97998032.mp4'
2
+ video_path type = <class 'str'>
3
+ video_path is None: False
4
+ bool(video_path): True
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_183038/97998032}/feature_frame_mapping.json RENAMED
@@ -1,7 +1,7 @@
1
  {
2
- "original_frame_count": 84,
3
- "feature_count": 22,
4
- "downsampling_ratio": 3.8181818181818183,
5
  "fps": 30.0,
6
  "mapping": [
7
  {
@@ -31,14 +31,14 @@
31
  {
32
  "feature_index": 4,
33
  "frame_start": 15,
34
- "frame_end": 19,
35
- "frame_count": 4
36
  },
37
  {
38
  "feature_index": 5,
39
- "frame_start": 19,
40
  "frame_end": 22,
41
- "frame_count": 3
42
  },
43
  {
44
  "feature_index": 6,
@@ -61,20 +61,20 @@
61
  {
62
  "feature_index": 9,
63
  "frame_start": 34,
64
- "frame_end": 38,
65
- "frame_count": 4
66
  },
67
  {
68
  "feature_index": 10,
69
- "frame_start": 38,
70
- "frame_end": 42,
71
  "frame_count": 4
72
  },
73
  {
74
  "feature_index": 11,
75
- "frame_start": 42,
76
  "frame_end": 45,
77
- "frame_count": 3
78
  },
79
  {
80
  "feature_index": 12,
@@ -91,20 +91,20 @@
91
  {
92
  "feature_index": 14,
93
  "frame_start": 53,
94
- "frame_end": 57,
95
- "frame_count": 4
96
  },
97
  {
98
  "feature_index": 15,
99
- "frame_start": 57,
100
- "frame_end": 61,
101
  "frame_count": 4
102
  },
103
  {
104
  "feature_index": 16,
105
- "frame_start": 61,
106
  "frame_end": 64,
107
- "frame_count": 3
108
  },
109
  {
110
  "feature_index": 17,
@@ -117,24 +117,6 @@
117
  "frame_start": 68,
118
  "frame_end": 72,
119
  "frame_count": 4
120
- },
121
- {
122
- "feature_index": 19,
123
- "frame_start": 72,
124
- "frame_end": 76,
125
- "frame_count": 4
126
- },
127
- {
128
- "feature_index": 20,
129
- "frame_start": 76,
130
- "frame_end": 80,
131
- "frame_count": 4
132
- },
133
- {
134
- "feature_index": 21,
135
- "frame_start": 80,
136
- "frame_end": 84,
137
- "frame_count": 4
138
  }
139
  ]
140
  }
 
1
  {
2
+ "original_frame_count": 72,
3
+ "feature_count": 19,
4
+ "downsampling_ratio": 3.789473684210526,
5
  "fps": 30.0,
6
  "mapping": [
7
  {
 
31
  {
32
  "feature_index": 4,
33
  "frame_start": 15,
34
+ "frame_end": 18,
35
+ "frame_count": 3
36
  },
37
  {
38
  "feature_index": 5,
39
+ "frame_start": 18,
40
  "frame_end": 22,
41
+ "frame_count": 4
42
  },
43
  {
44
  "feature_index": 6,
 
61
  {
62
  "feature_index": 9,
63
  "frame_start": 34,
64
+ "frame_end": 37,
65
+ "frame_count": 3
66
  },
67
  {
68
  "feature_index": 10,
69
+ "frame_start": 37,
70
+ "frame_end": 41,
71
  "frame_count": 4
72
  },
73
  {
74
  "feature_index": 11,
75
+ "frame_start": 41,
76
  "frame_end": 45,
77
+ "frame_count": 4
78
  },
79
  {
80
  "feature_index": 12,
 
91
  {
92
  "feature_index": 14,
93
  "frame_start": 53,
94
+ "frame_end": 56,
95
+ "frame_count": 3
96
  },
97
  {
98
  "feature_index": 15,
99
+ "frame_start": 56,
100
+ "frame_end": 60,
101
  "frame_count": 4
102
  },
103
  {
104
  "feature_index": 16,
105
+ "frame_start": 60,
106
  "frame_end": 64,
107
+ "frame_count": 4
108
  },
109
  {
110
  "feature_index": 17,
 
117
  "frame_start": 68,
118
  "frame_end": 72,
119
  "frame_count": 4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  }
121
  ]
122
  }
SignX/inference_output/detailed_prediction_20260102_183038/97998032/frame_alignment.json ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "translation": "BOX/ROOM REALLY BIG #DOG \"I don't know\"",
3
+ "words": [
4
+ "BOX/ROOM",
5
+ "REALLY",
6
+ "BIG",
7
+ "#DOG",
8
+ "\"I",
9
+ "don't",
10
+ "know\""
11
+ ],
12
+ "total_video_frames": 19,
13
+ "frame_ranges": [
14
+ {
15
+ "word": "BOX/ROOM",
16
+ "start_frame": 3,
17
+ "end_frame": 3,
18
+ "peak_frame": 3,
19
+ "avg_attention": 0.557424008846283,
20
+ "confidence": "high"
21
+ },
22
+ {
23
+ "word": "REALLY",
24
+ "start_frame": 7,
25
+ "end_frame": 7,
26
+ "peak_frame": 7,
27
+ "avg_attention": 0.4792027473449707,
28
+ "confidence": "medium"
29
+ },
30
+ {
31
+ "word": "BIG",
32
+ "start_frame": 9,
33
+ "end_frame": 9,
34
+ "peak_frame": 9,
35
+ "avg_attention": 0.43524169921875,
36
+ "confidence": "medium"
37
+ },
38
+ {
39
+ "word": "#DOG",
40
+ "start_frame": 12,
41
+ "end_frame": 14,
42
+ "peak_frame": 14,
43
+ "avg_attention": 0.1597622036933899,
44
+ "confidence": "low"
45
+ },
46
+ {
47
+ "word": "\"I",
48
+ "start_frame": 7,
49
+ "end_frame": 7,
50
+ "peak_frame": 7,
51
+ "avg_attention": 0.44769182801246643,
52
+ "confidence": "medium"
53
+ },
54
+ {
55
+ "word": "don't",
56
+ "start_frame": 9,
57
+ "end_frame": 9,
58
+ "peak_frame": 9,
59
+ "avg_attention": 0.4446210265159607,
60
+ "confidence": "medium"
61
+ },
62
+ {
63
+ "word": "know\"",
64
+ "start_frame": 14,
65
+ "end_frame": 15,
66
+ "peak_frame": 15,
67
+ "avg_attention": 0.17181915044784546,
68
+ "confidence": "low"
69
+ }
70
+ ],
71
+ "statistics": {
72
+ "avg_confidence": 0.3851089520113809,
73
+ "high_confidence_words": 1,
74
+ "medium_confidence_words": 4,
75
+ "low_confidence_words": 2
76
+ }
77
+ }
SignX/inference_output/detailed_prediction_20260102_183038/97998032/frame_alignment.pdf ADDED
Binary file (32 kB). View file
 
SignX/inference_output/detailed_prediction_20260102_183038/97998032/frame_alignment.png ADDED

Git LFS Details

  • SHA256: d8b54790ad7e2d7e08bad4288069a8a517c5f729f99be26ff99abc5fbe86a064
  • Pointer size: 131 Bytes
  • Size of remote file: 141 kB
SignX/inference_output/detailed_prediction_20260102_183038/97998032/frame_alignment_short.pdf ADDED
Binary file (32 kB). View file
 
SignX/inference_output/detailed_prediction_20260102_183038/97998032/frame_alignment_short.png ADDED

Git LFS Details

  • SHA256: 93a8fcf21e2ae06fe60fabe5ab2fdb3c54337e5c9207a20fffc6215b17fb5086
  • Pointer size: 131 Bytes
  • Size of remote file: 147 kB
SignX/inference_output/detailed_prediction_20260102_183038/97998032/gloss_to_frames.png ADDED

Git LFS Details

  • SHA256: 7cc862d3580bf49556978eee1584391784e6d7d0fc05ef523d7cce8436e31ce6
  • Pointer size: 132 Bytes
  • Size of remote file: 3.32 MB
SignX/inference_output/{detailed_prediction_20260102_180915/23881350 → detailed_prediction_20260102_183038/97998032}/interactive_alignment.html RENAMED
@@ -1,5 +1,5 @@
1
  <!DOCTYPE html>
2
- <html lang="zh-CN">
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -135,9 +135,9 @@
135
  <h1>🎯 Interactive Word-to-Frame Alignment Visualizer</h1>
136
 
137
  <div class="stats">
138
- <strong>Translation:</strong> HAPPEN RAIN IX-1p STAY HOME<br>
139
- <strong>Total Words:</strong> 5 |
140
- <strong>Total Features:</strong> 22
141
  </div>
142
 
143
  <div class="controls">
@@ -149,7 +149,7 @@
149
  <span class="value-display" id="peak-threshold-value">90%</span>
150
  <br>
151
  <small style="margin-left: 255px; color: #666;">
152
- 帧的注意力权重 ≥ (峰值权重 × 阈值%) 时被认为是"显著帧"
153
  </small>
154
  </div>
155
 
@@ -173,7 +173,7 @@
173
  <div>
174
  <h3>Word-to-Frame Alignment</h3>
175
  <p style="color: #666; font-size: 13px;">
176
- 每个词显示为彩色矩形,宽度表示该词对应的特征帧范围。★ = 峰值帧。矩形内部显示注意力权重波形。
177
  </p>
178
  <canvas id="alignment-canvas" width="1600" height="600"></canvas>
179
 
@@ -207,9 +207,9 @@
207
 
208
  <script>
209
  // Attention data from Python
210
- const attentionData = [{"word": "HAPPEN", "word_idx": 0, "weights": [0.01291993260383606, 0.22621376812458038, 0.33764514327049255, 0.27050673961639404, 0.09817569702863693, 0.02714376524090767, 0.011113409884274006, 0.005296836141496897, 0.0037311457563191652, 0.003827065462246537, 0.0006870391080155969, 0.0002082101273117587, 0.00037049551610834897, 0.00017867473070509732, 0.00019952311413362622, 0.0002196609857492149, 0.0002739514457061887, 0.0002957700635306537, 0.0002758886548690498, 0.00030245655216276646, 0.00020353472791612148, 0.00021125243802089244]}, {"word": "RAIN", "word_idx": 1, "weights": [0.3576834201812744, 0.06338081508874893, 0.04800238460302353, 0.049258649349212646, 0.05412573739886284, 0.05381090193986893, 0.030251972377300262, 0.02207508496940136, 0.02118324674665928, 0.023231113329529762, 0.010185010731220245, 0.003157678060233593, 0.0062621720135211945, 0.04268598556518555, 0.029935674741864204, 0.006265602074563503, 0.004162208177149296, 0.00504302280023694, 0.008224229328334332, 0.010121803730726242, 0.034552425146102905, 0.11640084534883499]}, {"word": "IX-1p", "word_idx": 2, "weights": [0.3532525599002838, 0.04980245977640152, 0.04337240383028984, 0.06047032028436661, 0.06392523646354675, 0.03436466306447983, 0.02429746463894844, 0.02106122486293316, 0.02133776992559433, 0.025554073974490166, 0.016313916072249413, 0.003731244709342718, 0.007006840314716101, 0.04077312350273132, 0.02346269227564335, 0.0029797866009175777, 0.0017814883030951023, 0.00229285447858274, 0.004264588467776775, 0.005742882378399372, 0.03171425312757492, 0.16249814629554749]}, {"word": "STAY", "word_idx": 3, "weights": [0.40251624584198, 0.029755407944321632, 0.014557132497429848, 0.01463515404611826, 0.019380902871489525, 0.014376296661794186, 0.007390746846795082, 0.006403730250895023, 0.007509394083172083, 0.011107773520052433, 0.015461954288184643, 0.008160914294421673, 0.015393615700304508, 0.049521077424287796, 0.02762117236852646, 0.0039024795405566692, 0.0022697332315146923, 0.002971042413264513, 0.0064276838675141335, 0.00918453000485897, 0.059506580233573914, 0.27194643020629883]}, {"word": "HOME", "word_idx": 4, "weights": [0.004598479717969894, 0.004125811159610748, 0.010973671451210976, 0.027834169566631317, 0.05619348585605621, 0.11399403214454651, 0.1471027433872223, 0.24049112200737, 0.18445074558258057, 0.13784004747867584, 0.052242521196603775, 0.00787721760571003, 0.00459145987406373, 0.0007465958478860557, 0.0008116196841001511, 0.0007541333325207233, 0.0007234851364046335, 0.000789315381553024, 0.0007666726596653461, 0.0007141060195863247, 0.0008214113186113536, 0.001557175419293344]}];
211
- const numGlosses = 5;
212
- const numFeatures = 22;
213
 
214
  // Colors for different words (matching matplotlib tab20)
215
  const colors = [
 
1
  <!DOCTYPE html>
2
+ <html lang="en">
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
 
135
  <h1>🎯 Interactive Word-to-Frame Alignment Visualizer</h1>
136
 
137
  <div class="stats">
138
+ <strong>Translation:</strong> BOX/ROOM REALLY BIG #DOG "I don't know"<br>
139
+ <strong>Total Words:</strong> 7 |
140
+ <strong>Total Features:</strong> 19
141
  </div>
142
 
143
  <div class="controls">
 
149
  <span class="value-display" id="peak-threshold-value">90%</span>
150
  <br>
151
  <small style="margin-left: 255px; color: #666;">
152
+ A frame is considered “significant” if its attention ≥ (peak × threshold%)
153
  </small>
154
  </div>
155
 
 
173
  <div>
174
  <h3>Word-to-Frame Alignment</h3>
175
  <p style="color: #666; font-size: 13px;">
176
+ Each word appears as a colored block. Width = frame span, ★ = peak frame, waveform = attention trace.
177
  </p>
178
  <canvas id="alignment-canvas" width="1600" height="600"></canvas>
179
 
 
207
 
208
  <script>
209
  // Attention data from Python
210
+ const attentionData = [{"word": "BOX/ROOM", "word_idx": 0, "weights": [0.002408777829259634, 0.0024341775570064783, 0.03761057183146477, 0.557424008846283, 0.352936714887619, 0.03772226721048355, 0.005863560829311609, 0.0013187339063733816, 0.0006791671621613204, 0.00032966560684144497, 9.721100650494918e-05, 8.92743410076946e-05, 9.339430107502267e-05, 0.00012962566688656807, 0.0002221816248493269, 0.00024164406931959093, 0.00015803848509676754, 0.0001251799112651497, 0.0001158745726570487]}, {"word": "REALLY", "word_idx": 1, "weights": [0.0026851091533899307, 0.0017755258595570922, 0.0021002113353461027, 0.00464355293661356, 0.009926511906087399, 0.05862388014793396, 0.07301068305969238, 0.4792027473449707, 0.24775737524032593, 0.09779708087444305, 0.013734006322920322, 0.0036178771406412125, 0.00126516108866781, 0.0006283684633672237, 0.0005421006353572011, 0.0004540205409284681, 0.0005231587565504014, 0.0008070130716077983, 0.0009056107373908162]}, {"word": "BIG", "word_idx": 2, "weights": [0.0033648894168436527, 0.0024659072514623404, 0.001798246055841446, 0.0024246324319392443, 0.003872026689350605, 0.033719416707754135, 0.04568067193031311, 0.04394841566681862, 0.27093446254730225, 0.43524169921875, 0.10514841973781586, 0.02633197419345379, 0.00916079618036747, 0.004303758963942528, 0.002990439534187317, 0.001977356616407633, 0.001934203552082181, 0.002392182359471917, 0.002310538897290826]}, {"word": "#DOG", "word_idx": 3, "weights": [0.003395852167159319, 0.0022946521639823914, 0.0013094337191432714, 0.001907510682940483, 0.0014237307477742434, 0.0012601837515830994, 0.0016997121274471283, 0.002569732256233692, 0.007368206512182951, 0.022247344255447388, 0.08171797543764114, 0.13777881860733032, 0.151152104139328, 0.16236612200737, 0.16576839983463287, 0.14751452207565308, 0.0665179044008255, 0.025248302146792412, 0.016459539532661438]}, {"word": "\"I", "word_idx": 4, "weights": [0.0019984443206340075, 0.0012192379217594862, 0.0013845543144270778, 0.0029638358391821384, 0.006774703040719032, 0.04147785156965256, 0.04095124825835228, 0.44769182801246643, 0.3094656765460968, 0.1222718134522438, 0.01613483391702175, 0.003763768821954727, 0.001163386506959796, 0.0004717711126431823, 0.0003339226823300123, 0.0002554724342189729, 0.0003666701668407768, 0.000614481046795845, 0.0006964970380067825]}, {"word": "don't", "word_idx": 5, "weights": [0.003398515982553363, 0.0023782167118042707, 0.0015607323730364442, 0.0018948124488815665, 0.0028244417626410723, 0.02270398661494255, 0.026757270097732544, 0.03139280155301094, 0.2563266456127167, 0.4446210265159607, 0.12968029081821442, 0.0390482135117054, 0.014498664066195488, 0.006633279379457235, 0.00436902791261673, 0.0027454677037894726, 0.002826108131557703, 0.0032868734560906887, 0.0030536367557942867]}, {"word": "know\"", "word_idx": 6, "weights": [0.019786883145570755, 0.015500817447900772, 0.013907048851251602, 0.009185242466628551, 0.005570622161030769, 0.0035703633911907673, 0.0028947137761861086, 0.0038008512929081917, 0.005732583813369274, 0.004597889259457588, 0.008673366159200668, 0.03249302878975868, 0.06597991287708282, 0.10256516188383102, 0.1631372570991516, 0.1805010437965393, 0.15080885589122772, 0.11721422523260117, 0.09408010542392731]}];
211
+ const numGlosses = 7;
212
+ const numFeatures = 19;
213
 
214
  // Colors for different words (matching matplotlib tab20)
215
  const colors = [
SignX/inference_output/detailed_prediction_20260102_183038/97998032/translation.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ With BPE: BOX/ROOM REALLY BIG #DOG "@@ I d@@ on@@ '@@ t know"
2
+ Clean: BOX/ROOM REALLY BIG #DOG "I don't know"
3
+ Ground Truth: BOX/ROOM BIG