FangSen9000 Claude commited on
Commit
cfee709
·
1 Parent(s): 7162aa8

Add a progress bar corresponding to the gloss that can control the threshold.

Browse files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

SignX/eval/generate_gloss_frames.py CHANGED
@@ -15,6 +15,11 @@ import cv2
15
  from pathlib import Path
16
  import matplotlib.pyplot as plt
17
  import matplotlib.patches as mpatches
 
 
 
 
 
18
 
19
  def extract_video_frames(video_path, frame_indices):
20
  """从视频中提取指定索引的帧"""
@@ -136,19 +141,26 @@ def generate_gloss_to_frames_visualization(sample_dir, video_path, output_path):
136
  confidence = info.get('confidence', 'unknown')
137
  avg_attn = info.get('avg_attention', 0.0)
138
 
139
- info_text = f"""特征帧: {feat_start} → {feat_peak} → {feat_end}
140
- 相对时间: {rel_start:.1f}% {rel_end:.1f}%
141
- 原始帧: {vid_start} {vid_peak} → {vid_end}
 
 
 
 
142
 
143
- 总特征帧: {total_feat}
144
- 总视频帧: {total_video_frames}
145
 
146
- 置信度: {confidence}
147
- 注意力: {avg_attn:.3f}"""
148
 
149
- ax_info.text(0.1, 0.5, info_text,
150
- fontsize=10, family='monospace',
151
  ha='left', va='center')
 
 
 
152
  ax_info.axis('off')
153
 
154
  # 列3:视频帧(Start | Peak | End)横向拼接
 
15
  from pathlib import Path
16
  import matplotlib.pyplot as plt
17
  import matplotlib.patches as mpatches
18
+ import matplotlib.font_manager as fm
19
+
20
+ # 设置中文字体支持
21
+ plt.rcParams['font.sans-serif'] = ['WenQuanYi Micro Hei', 'DejaVu Sans'] # Linux中文字体
22
+ plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
23
 
24
  def extract_video_frames(video_path, frame_indices):
25
  """从视频中提取指定索引的帧"""
 
141
  confidence = info.get('confidence', 'unknown')
142
  avg_attn = info.get('avg_attention', 0.0)
143
 
144
+ # 置信度颜色
145
+ conf_colors = {'high': 'green', 'medium': 'orange', 'low': 'red', 'unknown': 'gray'}
146
+ conf_color = conf_colors.get(confidence, 'gray')
147
+
148
+ info_text = f"""Feature idx: {feat_start} -> {feat_peak} -> {feat_end}
149
+ Rel. time: {rel_start:.1f}% -> {rel_end:.1f}%
150
+ Video frame: {vid_start} -> {vid_peak} -> {vid_end}
151
 
152
+ Total features: {total_feat}
153
+ Total frames: {total_video_frames}
154
 
155
+ Confidence: {confidence.upper()}
156
+ Attention: {avg_attn:.3f}"""
157
 
158
+ ax_info.text(0.05, 0.5, info_text,
159
+ fontsize=9, family='monospace',
160
  ha='left', va='center')
161
+ # 添加置信度颜色条
162
+ ax_info.add_patch(mpatches.Rectangle((0.85, 0.2), 0.1, 0.6,
163
+ facecolor=conf_color, alpha=0.3))
164
  ax_info.axis('off')
165
 
166
  # 列3:视频帧(Start | Peak | End)横向拼接
SignX/eval/generate_interactive_alignment.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
12
+ import sys
13
+ import json
14
+ 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
+ # shape: [time_steps, src_len, beam_size]
25
+ # 取beam 0的权重
26
+ attn_weights = attention_weights[:, :, 0] # [time_steps, src_len]
27
+
28
+ # 2. 读取翻译结果
29
+ with open(sample_dir / "translation.txt", 'r') as f:
30
+ lines = f.readlines()
31
+ gloss_sequence = None
32
+ for line in lines:
33
+ if line.startswith('Clean:'):
34
+ gloss_sequence = line.replace('Clean:', '').strip()
35
+ break
36
+
37
+ if not gloss_sequence:
38
+ print("无法找到翻译结果")
39
+ return
40
+
41
+ glosses = gloss_sequence.split()
42
+ num_glosses = len(glosses)
43
+ num_features = attn_weights.shape[1]
44
+
45
+ print(f"Gloss序列: {glosses}")
46
+ print(f"特征数量: {num_features}")
47
+ print(f"Attention shape: {attn_weights.shape}")
48
+
49
+ # 3. 将attention权重转换为JSON可序列化格式
50
+ # 只取前num_glosses行(实际的gloss,不包括padding)
51
+ attn_data = []
52
+ for word_idx in range(min(num_glosses, attn_weights.shape[0])):
53
+ weights = attn_weights[word_idx, :].tolist()
54
+ attn_data.append({
55
+ 'word': glosses[word_idx],
56
+ 'word_idx': word_idx,
57
+ 'weights': weights
58
+ })
59
+
60
+ # 4. 生成HTML内容
61
+ html_content = f"""<!DOCTYPE html>
62
+ <html lang="zh-CN">
63
+ <head>
64
+ <meta charset="UTF-8">
65
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
66
+ <title>Interactive Word-Frame Alignment</title>
67
+ <style>
68
+ body {{
69
+ font-family: 'Arial', sans-serif;
70
+ margin: 20px;
71
+ background-color: #f5f5f5;
72
+ }}
73
+ .container {{
74
+ max-width: 1800px;
75
+ margin: 0 auto;
76
+ background-color: white;
77
+ padding: 30px;
78
+ border-radius: 8px;
79
+ box-shadow: 0 2px 10px rgba(0,0,0,0.1);
80
+ }}
81
+ h1 {{
82
+ color: #333;
83
+ border-bottom: 3px solid #4CAF50;
84
+ padding-bottom: 10px;
85
+ margin-bottom: 20px;
86
+ }}
87
+ .stats {{
88
+ background-color: #E3F2FD;
89
+ padding: 15px;
90
+ border-radius: 5px;
91
+ margin-bottom: 20px;
92
+ border-left: 4px solid #2196F3;
93
+ font-size: 14px;
94
+ }}
95
+ .controls {{
96
+ background-color: #f9f9f9;
97
+ padding: 20px;
98
+ border-radius: 5px;
99
+ margin-bottom: 30px;
100
+ border: 1px solid #ddd;
101
+ }}
102
+ .control-group {{
103
+ margin-bottom: 15px;
104
+ }}
105
+ label {{
106
+ font-weight: bold;
107
+ display: inline-block;
108
+ width: 250px;
109
+ color: #555;
110
+ }}
111
+ input[type="range"] {{
112
+ width: 400px;
113
+ vertical-align: middle;
114
+ }}
115
+ .value-display {{
116
+ display: inline-block;
117
+ width: 80px;
118
+ font-family: monospace;
119
+ font-size: 14px;
120
+ color: #2196F3;
121
+ font-weight: bold;
122
+ }}
123
+ .reset-btn {{
124
+ margin-top: 15px;
125
+ padding: 10px 25px;
126
+ background-color: #2196F3;
127
+ color: white;
128
+ border: none;
129
+ border-radius: 5px;
130
+ cursor: pointer;
131
+ font-size: 14px;
132
+ font-weight: bold;
133
+ }}
134
+ .reset-btn:hover {{
135
+ background-color: #1976D2;
136
+ }}
137
+ canvas {{
138
+ border: 1px solid #999;
139
+ display: block;
140
+ margin: 20px auto;
141
+ background: white;
142
+ }}
143
+ .legend {{
144
+ margin-top: 20px;
145
+ padding: 15px;
146
+ background-color: #fff;
147
+ border: 1px solid #ddd;
148
+ border-radius: 5px;
149
+ }}
150
+ .legend-item {{
151
+ display: inline-block;
152
+ margin-right: 25px;
153
+ font-size: 13px;
154
+ margin-bottom: 10px;
155
+ }}
156
+ .color-box {{
157
+ display: inline-block;
158
+ width: 30px;
159
+ height: 15px;
160
+ margin-right: 8px;
161
+ vertical-align: middle;
162
+ border: 1px solid #666;
163
+ }}
164
+ .info-panel {{
165
+ margin-top: 20px;
166
+ padding: 15px;
167
+ background-color: #f9f9f9;
168
+ border-radius: 5px;
169
+ border: 1px solid #ddd;
170
+ }}
171
+ .confidence {{
172
+ display: inline-block;
173
+ padding: 3px 10px;
174
+ border-radius: 10px;
175
+ font-weight: bold;
176
+ font-size: 11px;
177
+ text-transform: uppercase;
178
+ }}
179
+ .confidence.high {{
180
+ background-color: #4CAF50;
181
+ color: white;
182
+ }}
183
+ .confidence.medium {{
184
+ background-color: #FF9800;
185
+ color: white;
186
+ }}
187
+ .confidence.low {{
188
+ background-color: #f44336;
189
+ color: white;
190
+ }}
191
+ </style>
192
+ </head>
193
+ <body>
194
+ <div class="container">
195
+ <h1>🎯 Interactive Word-to-Frame Alignment Visualizer</h1>
196
+
197
+ <div class="stats">
198
+ <strong>Translation:</strong> {' '.join(glosses)}<br>
199
+ <strong>Total Words:</strong> {num_glosses} |
200
+ <strong>Total Features:</strong> {num_features}
201
+ </div>
202
+
203
+ <div class="controls">
204
+ <h3>⚙️ Threshold Controls</h3>
205
+
206
+ <div class="control-group">
207
+ <label for="peak-threshold">Peak Threshold (% of max):</label>
208
+ <input type="range" id="peak-threshold" min="1" max="100" value="30" step="1">
209
+ <span class="value-display" id="peak-threshold-value">30%</span>
210
+ <br>
211
+ <small style="margin-left: 255px; color: #666;">
212
+ 帧的注意力权重 ≥ (峰值权重 × 阈值%) 时被认为是"显著帧"
213
+ </small>
214
+ </div>
215
+
216
+ <div class="control-group">
217
+ <label for="confidence-high">High Confidence (avg attn >):</label>
218
+ <input type="range" id="confidence-high" min="0" max="100" value="50" step="1">
219
+ <span class="value-display" id="confidence-high-value">0.50</span>
220
+ </div>
221
+
222
+ <div class="control-group">
223
+ <label for="confidence-medium">Medium Confidence (avg attn >):</label>
224
+ <input type="range" id="confidence-medium" min="0" max="100" value="20" step="1">
225
+ <span class="value-display" id="confidence-medium-value">0.20</span>
226
+ </div>
227
+
228
+ <button class="reset-btn" onclick="resetDefaults()">
229
+ Reset to Defaults
230
+ </button>
231
+ </div>
232
+
233
+ <div>
234
+ <h3>Word-to-Frame Alignment</h3>
235
+ <p style="color: #666; font-size: 13px;">
236
+ 每个词显示为彩色矩形,宽度表示该词对应的特征帧范围。★ = 峰值帧。矩形内部显示注意力权重波形。
237
+ </p>
238
+ <canvas id="alignment-canvas" width="1600" height="600"></canvas>
239
+
240
+ <h3 style="margin-top: 30px;">Timeline Progress Bar</h3>
241
+ <canvas id="timeline-canvas" width="1600" height="100"></canvas>
242
+
243
+ <div class="legend">
244
+ <strong>Legend:</strong><br><br>
245
+ <div class="legend-item">
246
+ <span class="confidence high">High</span>
247
+ <span class="confidence medium">Medium</span>
248
+ <span class="confidence low">Low</span>
249
+ Confidence Levels (opacity reflects confidence)
250
+ </div>
251
+ <div class="legend-item">
252
+ <span style="color: red; font-size: 20px;">★</span>
253
+ Peak Frame (highest attention)
254
+ </div>
255
+ <div class="legend-item">
256
+ <span style="color: blue;">━</span>
257
+ Attention Waveform (within word region)
258
+ </div>
259
+ </div>
260
+ </div>
261
+
262
+ <div class="info-panel">
263
+ <h3>Alignment Details</h3>
264
+ <div id="alignment-details"></div>
265
+ </div>
266
+ </div>
267
+
268
+ <script>
269
+ // Attention data from Python
270
+ const attentionData = {json.dumps(attn_data, ensure_ascii=False)};
271
+ const numGlosses = {num_glosses};
272
+ const numFeatures = {num_features};
273
+
274
+ // Colors for different words (matching matplotlib tab20)
275
+ const colors = [
276
+ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
277
+ '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf',
278
+ '#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#c5b0d5',
279
+ '#c49c94', '#f7b6d2', '#c7c7c7', '#dbdb8d', '#9edae5'
280
+ ];
281
+
282
+ // Get controls
283
+ const peakThresholdSlider = document.getElementById('peak-threshold');
284
+ const peakThresholdValue = document.getElementById('peak-threshold-value');
285
+ const confidenceHighSlider = document.getElementById('confidence-high');
286
+ const confidenceHighValue = document.getElementById('confidence-high-value');
287
+ const confidenceMediumSlider = document.getElementById('confidence-medium');
288
+ const confidenceMediumValue = document.getElementById('confidence-medium-value');
289
+ const alignmentCanvas = document.getElementById('alignment-canvas');
290
+ const timelineCanvas = document.getElementById('timeline-canvas');
291
+ const alignmentCtx = alignmentCanvas.getContext('2d');
292
+ const timelineCtx = timelineCanvas.getContext('2d');
293
+
294
+ // Update displays when sliders change
295
+ peakThresholdSlider.oninput = function() {{
296
+ peakThresholdValue.textContent = this.value + '%';
297
+ updateVisualization();
298
+ }};
299
+
300
+ confidenceHighSlider.oninput = function() {{
301
+ confidenceHighValue.textContent = (this.value / 100).toFixed(2);
302
+ updateVisualization();
303
+ }};
304
+
305
+ confidenceMediumSlider.oninput = function() {{
306
+ confidenceMediumValue.textContent = (this.value / 100).toFixed(2);
307
+ updateVisualization();
308
+ }};
309
+
310
+ function resetDefaults() {{
311
+ peakThresholdSlider.value = 30;
312
+ confidenceHighSlider.value = 50;
313
+ confidenceMediumSlider.value = 20;
314
+ peakThresholdValue.textContent = '30%';
315
+ confidenceHighValue.textContent = '0.50';
316
+ confidenceMediumValue.textContent = '0.20';
317
+ updateVisualization();
318
+ }}
319
+
320
+ function calculateAlignment(weights, peakThreshold) {{
321
+ // Find peak
322
+ let peakIdx = 0;
323
+ let peakWeight = weights[0];
324
+ for (let i = 1; i < weights.length; i++) {{
325
+ if (weights[i] > peakWeight) {{
326
+ peakWeight = weights[i];
327
+ peakIdx = i;
328
+ }}
329
+ }}
330
+
331
+ // Find significant frames
332
+ const threshold = peakWeight * (peakThreshold / 100);
333
+ let startIdx = peakIdx;
334
+ let endIdx = peakIdx;
335
+ let sumWeight = 0;
336
+ let count = 0;
337
+
338
+ for (let i = 0; i < weights.length; i++) {{
339
+ if (weights[i] >= threshold) {{
340
+ if (i < startIdx) startIdx = i;
341
+ if (i > endIdx) endIdx = i;
342
+ sumWeight += weights[i];
343
+ count++;
344
+ }}
345
+ }}
346
+
347
+ const avgWeight = count > 0 ? sumWeight / count : peakWeight;
348
+
349
+ return {{
350
+ startIdx: startIdx,
351
+ endIdx: endIdx,
352
+ peakIdx: peakIdx,
353
+ peakWeight: peakWeight,
354
+ avgWeight: avgWeight,
355
+ threshold: threshold
356
+ }};
357
+ }}
358
+
359
+ function getConfidenceLevel(avgWeight, highThreshold, mediumThreshold) {{
360
+ if (avgWeight > highThreshold) return 'high';
361
+ if (avgWeight > mediumThreshold) return 'medium';
362
+ return 'low';
363
+ }}
364
+
365
+ function drawAlignmentChart() {{
366
+ const peakThreshold = parseInt(peakThresholdSlider.value);
367
+ const highThreshold = parseInt(confidenceHighSlider.value) / 100;
368
+ const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;
369
+
370
+ // Canvas dimensions
371
+ const width = alignmentCanvas.width;
372
+ const height = alignmentCanvas.height;
373
+ const leftMargin = 180;
374
+ const rightMargin = 50;
375
+ const topMargin = 60;
376
+ const bottomMargin = 80;
377
+
378
+ const plotWidth = width - leftMargin - rightMargin;
379
+ const plotHeight = height - topMargin - bottomMargin;
380
+
381
+ const rowHeight = plotHeight / numGlosses;
382
+ const featureWidth = plotWidth / numFeatures;
383
+
384
+ // Clear canvas
385
+ alignmentCtx.clearRect(0, 0, width, height);
386
+
387
+ // Draw title
388
+ alignmentCtx.fillStyle = '#333';
389
+ alignmentCtx.font = 'bold 18px Arial';
390
+ alignmentCtx.textAlign = 'center';
391
+ alignmentCtx.fillText('Word-to-Frame Alignment', width / 2, 30);
392
+ alignmentCtx.font = '13px Arial';
393
+ alignmentCtx.fillText('(based on attention peaks, ★ = peak frame)', width / 2, 48);
394
+
395
+ // Calculate alignments
396
+ const alignments = [];
397
+ for (let wordIdx = 0; wordIdx < numGlosses; wordIdx++) {{
398
+ const data = attentionData[wordIdx];
399
+ const alignment = calculateAlignment(data.weights, peakThreshold);
400
+ alignment.word = data.word;
401
+ alignment.wordIdx = wordIdx;
402
+ alignment.weights = data.weights;
403
+ alignments.push(alignment);
404
+ }}
405
+
406
+ // Draw grid
407
+ alignmentCtx.strokeStyle = '#e0e0e0';
408
+ alignmentCtx.lineWidth = 0.5;
409
+ for (let i = 0; i <= numFeatures; i++) {{
410
+ const x = leftMargin + i * featureWidth;
411
+ alignmentCtx.beginPath();
412
+ alignmentCtx.moveTo(x, topMargin);
413
+ alignmentCtx.lineTo(x, topMargin + plotHeight);
414
+ alignmentCtx.stroke();
415
+ }}
416
+
417
+ // Draw word regions
418
+ for (let wordIdx = 0; wordIdx < numGlosses; wordIdx++) {{
419
+ const alignment = alignments[wordIdx];
420
+ const confidence = getConfidenceLevel(alignment.avgWeight, highThreshold, mediumThreshold);
421
+ const y = topMargin + wordIdx * rowHeight;
422
+
423
+ // Alpha based on confidence
424
+ const alpha = confidence === 'high' ? 0.9 : confidence === 'medium' ? 0.7 : 0.5;
425
+
426
+ // Draw rectangle for word region
427
+ const startX = leftMargin + alignment.startIdx * featureWidth;
428
+ const rectWidth = (alignment.endIdx - alignment.startIdx + 1) * featureWidth;
429
+
430
+ alignmentCtx.fillStyle = colors[wordIdx % 20];
431
+ alignmentCtx.globalAlpha = alpha;
432
+ alignmentCtx.fillRect(startX, y, rectWidth, rowHeight * 0.8);
433
+ alignmentCtx.globalAlpha = 1.0;
434
+
435
+ // Draw border
436
+ alignmentCtx.strokeStyle = '#000';
437
+ alignmentCtx.lineWidth = 2;
438
+ alignmentCtx.strokeRect(startX, y, rectWidth, rowHeight * 0.8);
439
+
440
+ // Draw attention waveform inside rectangle
441
+ alignmentCtx.strokeStyle = 'rgba(0, 0, 255, 0.8)';
442
+ alignmentCtx.lineWidth = 1.5;
443
+ alignmentCtx.beginPath();
444
+ for (let i = alignment.startIdx; i <= alignment.endIdx; i++) {{
445
+ const x = leftMargin + i * featureWidth + featureWidth / 2;
446
+ const weight = alignment.weights[i];
447
+ const maxWeight = alignment.peakWeight;
448
+ const normalizedWeight = weight / (maxWeight * 1.2); // Scale for visibility
449
+ const waveY = y + rowHeight * 0.8 - (normalizedWeight * rowHeight * 0.6);
450
+
451
+ if (i === alignment.startIdx) {{
452
+ alignmentCtx.moveTo(x, waveY);
453
+ }} else {{
454
+ alignmentCtx.lineTo(x, waveY);
455
+ }}
456
+ }}
457
+ alignmentCtx.stroke();
458
+
459
+ // Draw word label
460
+ const labelX = startX + rectWidth / 2;
461
+ const labelY = y + rowHeight * 0.4;
462
+
463
+ alignmentCtx.fillStyle = 'rgba(0, 0, 0, 0.7)';
464
+ alignmentCtx.fillRect(labelX - 60, labelY - 12, 120, 24);
465
+ alignmentCtx.fillStyle = '#fff';
466
+ alignmentCtx.font = 'bold 13px Arial';
467
+ alignmentCtx.textAlign = 'center';
468
+ alignmentCtx.textBaseline = 'middle';
469
+ alignmentCtx.fillText(alignment.word, labelX, labelY);
470
+
471
+ // Mark peak frame with star
472
+ const peakX = leftMargin + alignment.peakIdx * featureWidth + featureWidth / 2;
473
+ const peakY = y + rowHeight * 0.4;
474
+
475
+ // Draw star
476
+ alignmentCtx.fillStyle = '#ff0000';
477
+ alignmentCtx.strokeStyle = '#ffff00';
478
+ alignmentCtx.lineWidth = 1.5;
479
+ alignmentCtx.font = '20px Arial';
480
+ alignmentCtx.textAlign = 'center';
481
+ alignmentCtx.strokeText('★', peakX, peakY);
482
+ alignmentCtx.fillText('★', peakX, peakY);
483
+
484
+ // Y-axis label (word names)
485
+ alignmentCtx.fillStyle = '#333';
486
+ alignmentCtx.font = '12px Arial';
487
+ alignmentCtx.textAlign = 'right';
488
+ alignmentCtx.textBaseline = 'middle';
489
+ alignmentCtx.fillText(alignment.word, leftMargin - 10, y + rowHeight * 0.4);
490
+ }}
491
+
492
+ // Draw horizontal grid lines
493
+ alignmentCtx.strokeStyle = '#ccc';
494
+ alignmentCtx.lineWidth = 0.5;
495
+ for (let i = 0; i <= numGlosses; i++) {{
496
+ const y = topMargin + i * rowHeight;
497
+ alignmentCtx.beginPath();
498
+ alignmentCtx.moveTo(leftMargin, y);
499
+ alignmentCtx.lineTo(leftMargin + plotWidth, y);
500
+ alignmentCtx.stroke();
501
+ }}
502
+
503
+ // Draw axes
504
+ alignmentCtx.strokeStyle = '#000';
505
+ alignmentCtx.lineWidth = 2;
506
+ alignmentCtx.strokeRect(leftMargin, topMargin, plotWidth, plotHeight);
507
+
508
+ // X-axis labels (frame indices)
509
+ alignmentCtx.fillStyle = '#000';
510
+ alignmentCtx.font = '11px Arial';
511
+ alignmentCtx.textAlign = 'center';
512
+ alignmentCtx.textBaseline = 'top';
513
+ for (let i = 0; i < numFeatures; i++) {{
514
+ const x = leftMargin + i * featureWidth + featureWidth / 2;
515
+ alignmentCtx.fillText(i.toString(), x, topMargin + plotHeight + 10);
516
+ }}
517
+
518
+ // Axis titles
519
+ alignmentCtx.fillStyle = '#333';
520
+ alignmentCtx.font = 'bold 14px Arial';
521
+ alignmentCtx.textAlign = 'center';
522
+ alignmentCtx.fillText('Feature Frame Index', leftMargin + plotWidth / 2, height - 20);
523
+
524
+ alignmentCtx.save();
525
+ alignmentCtx.translate(30, topMargin + plotHeight / 2);
526
+ alignmentCtx.rotate(-Math.PI / 2);
527
+ alignmentCtx.fillText('Generated Word', 0, 0);
528
+ alignmentCtx.restore();
529
+
530
+ return alignments;
531
+ }}
532
+
533
+ function drawTimeline(alignments) {{
534
+ const highThreshold = parseInt(confidenceHighSlider.value) / 100;
535
+ const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;
536
+
537
+ const width = timelineCanvas.width;
538
+ const height = timelineCanvas.height;
539
+ const leftMargin = 180;
540
+ const rightMargin = 50;
541
+ const plotWidth = width - leftMargin - rightMargin;
542
+ const featureWidth = plotWidth / numFeatures;
543
+
544
+ // Clear canvas
545
+ timelineCtx.clearRect(0, 0, width, height);
546
+
547
+ // Background bar
548
+ timelineCtx.fillStyle = '#ddd';
549
+ timelineCtx.fillRect(leftMargin, 30, plotWidth, 40);
550
+ timelineCtx.strokeStyle = '#000';
551
+ timelineCtx.lineWidth = 2;
552
+ timelineCtx.strokeRect(leftMargin, 30, plotWidth, 40);
553
+
554
+ // Draw word regions on timeline
555
+ for (let wordIdx = 0; wordIdx < alignments.length; wordIdx++) {{
556
+ const alignment = alignments[wordIdx];
557
+ const confidence = getConfidenceLevel(alignment.avgWeight, highThreshold, mediumThreshold);
558
+ const alpha = confidence === 'high' ? 0.9 : confidence === 'medium' ? 0.7 : 0.5;
559
+
560
+ const startX = leftMargin + alignment.startIdx * featureWidth;
561
+ const rectWidth = (alignment.endIdx - alignment.startIdx + 1) * featureWidth;
562
+
563
+ timelineCtx.fillStyle = colors[wordIdx % 20];
564
+ timelineCtx.globalAlpha = alpha;
565
+ timelineCtx.fillRect(startX, 30, rectWidth, 40);
566
+ timelineCtx.globalAlpha = 1.0;
567
+ timelineCtx.strokeStyle = '#000';
568
+ timelineCtx.lineWidth = 0.5;
569
+ timelineCtx.strokeRect(startX, 30, rectWidth, 40);
570
+ }}
571
+
572
+ // Title
573
+ timelineCtx.fillStyle = '#333';
574
+ timelineCtx.font = 'bold 13px Arial';
575
+ timelineCtx.textAlign = 'left';
576
+ timelineCtx.fillText('Timeline Progress Bar', leftMargin, 20);
577
+ }}
578
+
579
+ function updateDetailsPanel(alignments, highThreshold, mediumThreshold) {{
580
+ const panel = document.getElementById('alignment-details');
581
+ let html = '<table style="width: 100%; border-collapse: collapse;">';
582
+ html += '<tr style="background: #f0f0f0; font-weight: bold;">';
583
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Word</th>';
584
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Feature Range</th>';
585
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Peak</th>';
586
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Span</th>';
587
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Avg Attention</th>';
588
+ html += '<th style="padding: 8px; border: 1px solid #ddd;">Confidence</th>';
589
+ html += '</tr>';
590
+
591
+ for (const align of alignments) {{
592
+ const confidence = getConfidenceLevel(align.avgWeight, highThreshold, mediumThreshold);
593
+ const span = align.endIdx - align.startIdx + 1;
594
+
595
+ html += '<tr>';
596
+ html += `<td style="padding: 8px; border: 1px solid #ddd;"><strong>${{align.word}}</strong></td>`;
597
+ html += `<td style="padding: 8px; border: 1px solid #ddd;">${{align.startIdx}} → ${{align.endIdx}}</td>`;
598
+ html += `<td style="padding: 8px; border: 1px solid #ddd;">${{align.peakIdx}}</td>`;
599
+ html += `<td style="padding: 8px; border: 1px solid #ddd;">${{span}}</td>`;
600
+ html += `<td style="padding: 8px; border: 1px solid #ddd;">${{align.avgWeight.toFixed(4)}}</td>`;
601
+ html += `<td style="padding: 8px; border: 1px solid #ddd;"><span class="confidence ${{confidence}}">${{confidence}}</span></td>`;
602
+ html += '</tr>';
603
+ }}
604
+
605
+ html += '</table>';
606
+ panel.innerHTML = html;
607
+ }}
608
+
609
+ function updateVisualization() {{
610
+ const alignments = drawAlignmentChart();
611
+ drawTimeline(alignments);
612
+ const highThreshold = parseInt(confidenceHighSlider.value) / 100;
613
+ const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;
614
+ updateDetailsPanel(alignments, highThreshold, mediumThreshold);
615
+ }}
616
+
617
+ // Event listeners for sliders
618
+ peakSlider.addEventListener('input', function() {{
619
+ peakValue.textContent = peakSlider.value + '%';
620
+ updateVisualization();
621
+ }});
622
+
623
+ confidenceHighSlider.addEventListener('input', function() {{
624
+ const val = parseInt(confidenceHighSlider.value) / 100;
625
+ confidenceHighValue.textContent = val.toFixed(2);
626
+ updateVisualization();
627
+ }});
628
+
629
+ confidenceMediumSlider.addEventListener('input', function() {{
630
+ const val = parseInt(confidenceMediumSlider.value) / 100;
631
+ confidenceMediumValue.textContent = val.toFixed(2);
632
+ updateVisualization();
633
+ }});
634
+
635
+ // Initial visualization
636
+ updateVisualization();
637
+ </script>
638
+ </body>
639
+ </html>
640
+ """
641
+
642
+ # 5. 保存HTML文件
643
+ with open(output_path, 'w', encoding='utf-8') as f:
644
+ f.write(html_content)
645
+
646
+ print(f"✓ 已生成交互式HTML: {output_path}")
647
+ print(f" 在浏览器中打开此文件,使用滑块调整阈值")
648
+
649
+ if __name__ == "__main__":
650
+ if len(sys.argv) != 2:
651
+ print("使用方法: python generate_interactive_alignment.py <sample_dir>")
652
+ print("例如: python generate_interactive_alignment.py detailed_prediction_20251226_022246/sample_000")
653
+ sys.exit(1)
654
+
655
+ sample_dir = Path(sys.argv[1])
656
+
657
+ if not sample_dir.exists():
658
+ print(f"错误: 目录不存在: {sample_dir}")
659
+ sys.exit(1)
660
+
661
+ output_path = sample_dir / "interactive_alignment.html"
662
+ generate_interactive_html(sample_dir, output_path)
663
+
664
+ print(f"\n使用方法:")
665
+ print(f" 在浏览器中打开: {output_path.absolute()}")
666
+ print(f" 调整滑块实时查看不同阈值下的对齐效果")
SignX/inference.sh CHANGED
@@ -251,7 +251,26 @@ if [ -f "$TEMP_DIR/prediction.txt" ]; then
251
  echo ""
252
  echo -e "${BLUE}生成 Gloss-to-Frames 可视化...${NC}"
253
  if [ -f "$SCRIPT_DIR/eval/generate_gloss_frames.py" ]; then
254
- python "$SCRIPT_DIR/eval/generate_gloss_frames.py" "$dest_path" "$VIDEO_PATH" 2>&1 | grep -E "(处理|提取|生成|完成|✓)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  else
256
  echo " ⓘ generate_gloss_frames.py 未找到,跳过后处理"
257
  fi
 
251
  echo ""
252
  echo -e "${BLUE}生成 Gloss-to-Frames 可视化...${NC}"
253
  if [ -f "$SCRIPT_DIR/eval/generate_gloss_frames.py" ]; then
254
+ # 切换回 signx-slt 环境 (有 matplotlib cv2)
255
+ conda activate signx-slt
256
+ python "$SCRIPT_DIR/eval/generate_gloss_frames.py" "$dest_path" "$VIDEO_PATH"
257
+
258
+ # 生成交互式HTML可视化
259
+ echo ""
260
+ echo -e "${BLUE}生成交互式HTML可视化...${NC}"
261
+ if [ -f "$SCRIPT_DIR/eval/generate_interactive_alignment.py" ]; then
262
+ # 处理所有样本
263
+ for sample_dir in "$dest_path"/sample_*; do
264
+ if [ -d "$sample_dir" ]; then
265
+ python "$SCRIPT_DIR/eval/generate_interactive_alignment.py" "$sample_dir"
266
+ fi
267
+ done
268
+ else
269
+ echo " ⓘ generate_interactive_alignment.py 未找到,跳过交互式HTML生成"
270
+ fi
271
+
272
+ # 切换回 slt_tf1 环境
273
+ conda activate slt_tf1
274
  else
275
  echo " ⓘ generate_gloss_frames.py 未找到,跳过后处理"
276
  fi