File size: 26,443 Bytes
cfee709
 
9f9e779
 
 
 
cfee709
 
9f9e779
cfee709
 
 
 
 
 
 
 
 
9f9e779
cfee709
 
 
9f9e779
cfee709
a9be817
 
 
 
 
 
 
cfee709
9f9e779
cfee709
 
 
 
 
 
 
 
 
9f9e779
cfee709
 
 
 
 
 
9f9e779
 
cfee709
 
9f9e779
cfee709
 
 
 
 
 
 
 
 
9f9e779
cfee709
9f9e779
cfee709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
741864d
 
cfee709
 
9f9e779
cfee709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
cfee709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
741864d
cfee709
 
741864d
cfee709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
cfee709
 
 
9f9e779
 
cfee709
 
 
9f9e779
 
cfee709
 
 
 
 
9f9e779
cfee709
 
 
 
 
9f9e779
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
#!/usr/bin/env python3
"""
Generate an interactive HTML visualization for the gloss-to-feature alignment.
This mirrors the frame_alignment.png layout but lets viewers adjust confidence thresholds.

Usage:
    python generate_interactive_alignment.py <sample_dir>

Example:
    python generate_interactive_alignment.py detailed_prediction_20251226_022246/sample_000
"""

import sys
import json
import numpy as np
from pathlib import Path

def generate_interactive_html(sample_dir, output_path):
    """Create the interactive alignment HTML for the given sample directory."""

    sample_dir = Path(sample_dir)

    # 1. Load attention weights
    attention_weights = np.load(sample_dir / "attention_weights.npy")
    # Handle both 2D (inference mode) and 3D (beam search) shapes
    if attention_weights.ndim == 2:
        attn_weights = attention_weights  # [time_steps, src_len] - already 2D
    elif attention_weights.ndim == 3:
        attn_weights = attention_weights[:, :, 0]  # [time_steps, src_len] - take beam 0
    else:
        raise ValueError(f"Unexpected attention weights shape: {attention_weights.shape}")

    # 2. Load translation output
    with open(sample_dir / "translation.txt", 'r') as f:
        lines = f.readlines()
        gloss_sequence = None
        for line in lines:
            if line.startswith('Clean:'):
                gloss_sequence = line.replace('Clean:', '').strip()
                break

    if not gloss_sequence:
        print("Error: translation text not found")
        return

    glosses = gloss_sequence.split()
    num_glosses = len(glosses)
    num_features = attn_weights.shape[1]

    print(f"Gloss sequence: {glosses}")
    print(f"Feature count: {num_features}")
    print(f"Attention shape: {attn_weights.shape}")

    # 3. Convert attention weights to JSON (only keep the num_glosses rows – ignore padding)
    attn_data = []
    for word_idx in range(min(num_glosses, attn_weights.shape[0])):
        weights = attn_weights[word_idx, :].tolist()
        attn_data.append({
            'word': glosses[word_idx],
            'word_idx': word_idx,
            'weights': weights
        })

    # 4. Build the HTML payload
    html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Word-Frame Alignment</title>
    <style>
        body {{
            font-family: 'Arial', sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }}
        .container {{
            max-width: 1800px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #333;
            border-bottom: 3px solid #4CAF50;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }}
        .stats {{
            background-color: #E3F2FD;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            border-left: 4px solid #2196F3;
            font-size: 14px;
        }}
        .controls {{
            background-color: #f9f9f9;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 30px;
            border: 1px solid #ddd;
        }}
        .control-group {{
            margin-bottom: 15px;
        }}
        label {{
            font-weight: bold;
            display: inline-block;
            width: 250px;
            color: #555;
        }}
        input[type="range"] {{
            width: 400px;
            vertical-align: middle;
        }}
        .value-display {{
            display: inline-block;
            width: 80px;
            font-family: monospace;
            font-size: 14px;
            color: #2196F3;
            font-weight: bold;
        }}
        .reset-btn {{
            margin-top: 15px;
            padding: 10px 25px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
        }}
        .reset-btn:hover {{
            background-color: #1976D2;
        }}
        canvas {{
            border: 1px solid #999;
            display: block;
            margin: 20px auto;
            background: white;
        }}
        .legend {{
            margin-top: 20px;
            padding: 15px;
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 5px;
        }}
        .legend-item {{
            display: inline-block;
            margin-right: 25px;
            font-size: 13px;
            margin-bottom: 10px;
        }}
        .color-box {{
            display: inline-block;
            width: 30px;
            height: 15px;
            margin-right: 8px;
            vertical-align: middle;
            border: 1px solid #666;
        }}
        .info-panel {{
            margin-top: 20px;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 5px;
            border: 1px solid #ddd;
        }}
        .confidence {{
            display: inline-block;
            padding: 3px 10px;
            border-radius: 10px;
            font-weight: bold;
            font-size: 11px;
            text-transform: uppercase;
        }}
        .confidence.high {{
            background-color: #4CAF50;
            color: white;
        }}
        .confidence.medium {{
            background-color: #FF9800;
            color: white;
        }}
        .confidence.low {{
            background-color: #f44336;
            color: white;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>🎯 Interactive Word-to-Frame Alignment Visualizer</h1>

        <div class="stats">
            <strong>Translation:</strong> {' '.join(glosses)}<br>
            <strong>Total Words:</strong> {num_glosses} |
            <strong>Total Features:</strong> {num_features}
        </div>

        <div class="controls">
            <h3>⚙️ Threshold Controls</h3>

            <div class="control-group">
                <label for="peak-threshold">Peak Threshold (% of max):</label>
                <input type="range" id="peak-threshold" min="1" max="100" value="90" step="1">
                <span class="value-display" id="peak-threshold-value">90%</span>
                <br>
                <small style="margin-left: 255px; color: #666;">
                    A frame is considered “significant” if its attention ≥ (peak × threshold%)
                </small>
            </div>

            <div class="control-group">
                <label for="confidence-high">High Confidence (avg attn >):</label>
                <input type="range" id="confidence-high" min="0" max="100" value="50" step="1">
                <span class="value-display" id="confidence-high-value">0.50</span>
            </div>

            <div class="control-group">
                <label for="confidence-medium">Medium Confidence (avg attn >):</label>
                <input type="range" id="confidence-medium" min="0" max="100" value="20" step="1">
                <span class="value-display" id="confidence-medium-value">0.20</span>
            </div>

            <button class="reset-btn" onclick="resetDefaults()">
                Reset to Defaults
            </button>
        </div>

        <div>
            <h3>Word-to-Frame Alignment</h3>
            <p style="color: #666; font-size: 13px;">
                Each word appears as a colored block. Width = frame span, ★ = peak frame, waveform = attention trace.
            </p>
            <canvas id="alignment-canvas" width="1600" height="600"></canvas>

            <h3 style="margin-top: 30px;">Timeline Progress Bar</h3>
            <canvas id="timeline-canvas" width="1600" height="100"></canvas>

            <div class="legend">
                <strong>Legend:</strong><br><br>
                <div class="legend-item">
                    <span class="confidence high">High</span>
                    <span class="confidence medium">Medium</span>
                    <span class="confidence low">Low</span>
                    Confidence Levels (opacity reflects confidence)
                </div>
                <div class="legend-item">
                    <span style="color: red; font-size: 20px;">★</span>
                    Peak Frame (highest attention)
                </div>
                <div class="legend-item">
                    <span style="color: blue;">━</span>
                    Attention Waveform (within word region)
                </div>
            </div>
        </div>

        <div class="info-panel">
            <h3>Alignment Details</h3>
            <div id="alignment-details"></div>
        </div>
    </div>

    <script>
        // Attention data from Python
        const attentionData = {json.dumps(attn_data, ensure_ascii=False)};
        const numGlosses = {num_glosses};
        const numFeatures = {num_features};

        // Colors for different words (matching matplotlib tab20)
        const colors = [
            '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
            '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf',
            '#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#c5b0d5',
            '#c49c94', '#f7b6d2', '#c7c7c7', '#dbdb8d', '#9edae5'
        ];

        // Get controls
        const peakThresholdSlider = document.getElementById('peak-threshold');
        const peakThresholdValue = document.getElementById('peak-threshold-value');
        const confidenceHighSlider = document.getElementById('confidence-high');
        const confidenceHighValue = document.getElementById('confidence-high-value');
        const confidenceMediumSlider = document.getElementById('confidence-medium');
        const confidenceMediumValue = document.getElementById('confidence-medium-value');
        const alignmentCanvas = document.getElementById('alignment-canvas');
        const timelineCanvas = document.getElementById('timeline-canvas');
        const alignmentCtx = alignmentCanvas.getContext('2d');
        const timelineCtx = timelineCanvas.getContext('2d');

        // Update displays when sliders change
        peakThresholdSlider.oninput = function() {{
            peakThresholdValue.textContent = this.value + '%';
            updateVisualization();
        }};

        confidenceHighSlider.oninput = function() {{
            confidenceHighValue.textContent = (this.value / 100).toFixed(2);
            updateVisualization();
        }};

        confidenceMediumSlider.oninput = function() {{
            confidenceMediumValue.textContent = (this.value / 100).toFixed(2);
            updateVisualization();
        }};

        function resetDefaults() {{
            peakThresholdSlider.value = 90;
            confidenceHighSlider.value = 50;
            confidenceMediumSlider.value = 20;
            peakThresholdValue.textContent = '90%';
            confidenceHighValue.textContent = '0.50';
            confidenceMediumValue.textContent = '0.20';
            updateVisualization();
        }}

        function calculateAlignment(weights, peakThreshold) {{
            // Find peak
            let peakIdx = 0;
            let peakWeight = weights[0];
            for (let i = 1; i < weights.length; i++) {{
                if (weights[i] > peakWeight) {{
                    peakWeight = weights[i];
                    peakIdx = i;
                }}
            }}

            // Find significant frames
            const threshold = peakWeight * (peakThreshold / 100);
            let startIdx = peakIdx;
            let endIdx = peakIdx;
            let sumWeight = 0;
            let count = 0;

            for (let i = 0; i < weights.length; i++) {{
                if (weights[i] >= threshold) {{
                    if (i < startIdx) startIdx = i;
                    if (i > endIdx) endIdx = i;
                    sumWeight += weights[i];
                    count++;
                }}
            }}

            const avgWeight = count > 0 ? sumWeight / count : peakWeight;

            return {{
                startIdx: startIdx,
                endIdx: endIdx,
                peakIdx: peakIdx,
                peakWeight: peakWeight,
                avgWeight: avgWeight,
                threshold: threshold
            }};
        }}

        function getConfidenceLevel(avgWeight, highThreshold, mediumThreshold) {{
            if (avgWeight > highThreshold) return 'high';
            if (avgWeight > mediumThreshold) return 'medium';
            return 'low';
        }}

        function drawAlignmentChart() {{
            const peakThreshold = parseInt(peakThresholdSlider.value);
            const highThreshold = parseInt(confidenceHighSlider.value) / 100;
            const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;

            // Canvas dimensions
            const width = alignmentCanvas.width;
            const height = alignmentCanvas.height;
            const leftMargin = 180;
            const rightMargin = 50;
            const topMargin = 60;
            const bottomMargin = 80;

            const plotWidth = width - leftMargin - rightMargin;
            const plotHeight = height - topMargin - bottomMargin;

            const rowHeight = plotHeight / numGlosses;
            const featureWidth = plotWidth / numFeatures;

            // Clear canvas
            alignmentCtx.clearRect(0, 0, width, height);

            // Draw title
            alignmentCtx.fillStyle = '#333';
            alignmentCtx.font = 'bold 18px Arial';
            alignmentCtx.textAlign = 'center';
            alignmentCtx.fillText('Word-to-Frame Alignment', width / 2, 30);
            alignmentCtx.font = '13px Arial';
            alignmentCtx.fillText('(based on attention peaks, ★ = peak frame)', width / 2, 48);

            // Calculate alignments
            const alignments = [];
            for (let wordIdx = 0; wordIdx < numGlosses; wordIdx++) {{
                const data = attentionData[wordIdx];
                const alignment = calculateAlignment(data.weights, peakThreshold);
                alignment.word = data.word;
                alignment.wordIdx = wordIdx;
                alignment.weights = data.weights;
                alignments.push(alignment);
            }}

            // Draw grid
            alignmentCtx.strokeStyle = '#e0e0e0';
            alignmentCtx.lineWidth = 0.5;
            for (let i = 0; i <= numFeatures; i++) {{
                const x = leftMargin + i * featureWidth;
                alignmentCtx.beginPath();
                alignmentCtx.moveTo(x, topMargin);
                alignmentCtx.lineTo(x, topMargin + plotHeight);
                alignmentCtx.stroke();
            }}

            // Draw word regions
            for (let wordIdx = 0; wordIdx < numGlosses; wordIdx++) {{
                const alignment = alignments[wordIdx];
                const confidence = getConfidenceLevel(alignment.avgWeight, highThreshold, mediumThreshold);
                const y = topMargin + wordIdx * rowHeight;

                // Alpha based on confidence
                const alpha = confidence === 'high' ? 0.9 : confidence === 'medium' ? 0.7 : 0.5;

                // Draw rectangle for word region
                const startX = leftMargin + alignment.startIdx * featureWidth;
                const rectWidth = (alignment.endIdx - alignment.startIdx + 1) * featureWidth;

                alignmentCtx.fillStyle = colors[wordIdx % 20];
                alignmentCtx.globalAlpha = alpha;
                alignmentCtx.fillRect(startX, y, rectWidth, rowHeight * 0.8);
                alignmentCtx.globalAlpha = 1.0;

                // Draw border
                alignmentCtx.strokeStyle = '#000';
                alignmentCtx.lineWidth = 2;
                alignmentCtx.strokeRect(startX, y, rectWidth, rowHeight * 0.8);

                // Draw attention waveform inside rectangle
                alignmentCtx.strokeStyle = 'rgba(0, 0, 255, 0.8)';
                alignmentCtx.lineWidth = 1.5;
                alignmentCtx.beginPath();
                for (let i = alignment.startIdx; i <= alignment.endIdx; i++) {{
                    const x = leftMargin + i * featureWidth + featureWidth / 2;
                    const weight = alignment.weights[i];
                    const maxWeight = alignment.peakWeight;
                    const normalizedWeight = weight / (maxWeight * 1.2); // Scale for visibility
                    const waveY = y + rowHeight * 0.8 - (normalizedWeight * rowHeight * 0.6);

                    if (i === alignment.startIdx) {{
                        alignmentCtx.moveTo(x, waveY);
                    }} else {{
                        alignmentCtx.lineTo(x, waveY);
                    }}
                }}
                alignmentCtx.stroke();

                // Draw word label
                const labelX = startX + rectWidth / 2;
                const labelY = y + rowHeight * 0.4;

                alignmentCtx.fillStyle = 'rgba(0, 0, 0, 0.7)';
                alignmentCtx.fillRect(labelX - 60, labelY - 12, 120, 24);
                alignmentCtx.fillStyle = '#fff';
                alignmentCtx.font = 'bold 13px Arial';
                alignmentCtx.textAlign = 'center';
                alignmentCtx.textBaseline = 'middle';
                alignmentCtx.fillText(alignment.word, labelX, labelY);

                // Mark peak frame with star
                const peakX = leftMargin + alignment.peakIdx * featureWidth + featureWidth / 2;
                const peakY = y + rowHeight * 0.4;

                // Draw star
                alignmentCtx.fillStyle = '#ff0000';
                alignmentCtx.strokeStyle = '#ffff00';
                alignmentCtx.lineWidth = 1.5;
                alignmentCtx.font = '20px Arial';
                alignmentCtx.textAlign = 'center';
                alignmentCtx.strokeText('★', peakX, peakY);
                alignmentCtx.fillText('★', peakX, peakY);

                // Y-axis label (word names)
                alignmentCtx.fillStyle = '#333';
                alignmentCtx.font = '12px Arial';
                alignmentCtx.textAlign = 'right';
                alignmentCtx.textBaseline = 'middle';
                alignmentCtx.fillText(alignment.word, leftMargin - 10, y + rowHeight * 0.4);
            }}

            // Draw horizontal grid lines
            alignmentCtx.strokeStyle = '#ccc';
            alignmentCtx.lineWidth = 0.5;
            for (let i = 0; i <= numGlosses; i++) {{
                const y = topMargin + i * rowHeight;
                alignmentCtx.beginPath();
                alignmentCtx.moveTo(leftMargin, y);
                alignmentCtx.lineTo(leftMargin + plotWidth, y);
                alignmentCtx.stroke();
            }}

            // Draw axes
            alignmentCtx.strokeStyle = '#000';
            alignmentCtx.lineWidth = 2;
            alignmentCtx.strokeRect(leftMargin, topMargin, plotWidth, plotHeight);

            // X-axis labels (frame indices)
            alignmentCtx.fillStyle = '#000';
            alignmentCtx.font = '11px Arial';
            alignmentCtx.textAlign = 'center';
            alignmentCtx.textBaseline = 'top';
            for (let i = 0; i < numFeatures; i++) {{
                const x = leftMargin + i * featureWidth + featureWidth / 2;
                alignmentCtx.fillText(i.toString(), x, topMargin + plotHeight + 10);
            }}

            // Axis titles
            alignmentCtx.fillStyle = '#333';
            alignmentCtx.font = 'bold 14px Arial';
            alignmentCtx.textAlign = 'center';
            alignmentCtx.fillText('Feature Frame Index', leftMargin + plotWidth / 2, height - 20);

            alignmentCtx.save();
            alignmentCtx.translate(30, topMargin + plotHeight / 2);
            alignmentCtx.rotate(-Math.PI / 2);
            alignmentCtx.fillText('Generated Word', 0, 0);
            alignmentCtx.restore();

            return alignments;
        }}

        function drawTimeline(alignments) {{
            const highThreshold = parseInt(confidenceHighSlider.value) / 100;
            const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;

            const width = timelineCanvas.width;
            const height = timelineCanvas.height;
            const leftMargin = 180;
            const rightMargin = 50;
            const plotWidth = width - leftMargin - rightMargin;
            const featureWidth = plotWidth / numFeatures;

            // Clear canvas
            timelineCtx.clearRect(0, 0, width, height);

            // Background bar
            timelineCtx.fillStyle = '#ddd';
            timelineCtx.fillRect(leftMargin, 30, plotWidth, 40);
            timelineCtx.strokeStyle = '#000';
            timelineCtx.lineWidth = 2;
            timelineCtx.strokeRect(leftMargin, 30, plotWidth, 40);

            // Draw word regions on timeline
            for (let wordIdx = 0; wordIdx < alignments.length; wordIdx++) {{
                const alignment = alignments[wordIdx];
                const confidence = getConfidenceLevel(alignment.avgWeight, highThreshold, mediumThreshold);
                const alpha = confidence === 'high' ? 0.9 : confidence === 'medium' ? 0.7 : 0.5;

                const startX = leftMargin + alignment.startIdx * featureWidth;
                const rectWidth = (alignment.endIdx - alignment.startIdx + 1) * featureWidth;

                timelineCtx.fillStyle = colors[wordIdx % 20];
                timelineCtx.globalAlpha = alpha;
                timelineCtx.fillRect(startX, 30, rectWidth, 40);
                timelineCtx.globalAlpha = 1.0;
                timelineCtx.strokeStyle = '#000';
                timelineCtx.lineWidth = 0.5;
                timelineCtx.strokeRect(startX, 30, rectWidth, 40);
            }}

            // Title
            timelineCtx.fillStyle = '#333';
            timelineCtx.font = 'bold 13px Arial';
            timelineCtx.textAlign = 'left';
            timelineCtx.fillText('Timeline Progress Bar', leftMargin, 20);
        }}

        function updateDetailsPanel(alignments, highThreshold, mediumThreshold) {{
            const panel = document.getElementById('alignment-details');
            let html = '<table style="width: 100%; border-collapse: collapse;">';
            html += '<tr style="background: #f0f0f0; font-weight: bold;">';
            html += '<th style="padding: 8px; border: 1px solid #ddd;">Word</th>';
            html += '<th style="padding: 8px; border: 1px solid #ddd;">Feature Range</th>';
            html += '<th style="padding: 8px; border: 1px solid #ddd;">Peak</th>';
            html += '<th style="padding: 8px; border: 1px solid #ddd;">Span</th>';
            html += '<th style="padding: 8px; border: 1px solid #ddd;">Avg Attention</th>';
            html += '<th style="padding: 8px; border: 1px solid #ddd;">Confidence</th>';
            html += '</tr>';

            for (const align of alignments) {{
                const confidence = getConfidenceLevel(align.avgWeight, highThreshold, mediumThreshold);
                const span = align.endIdx - align.startIdx + 1;

                html += '<tr>';
                html += `<td style="padding: 8px; border: 1px solid #ddd;"><strong>${{align.word}}</strong></td>`;
                html += `<td style="padding: 8px; border: 1px solid #ddd;">${{align.startIdx}} → ${{align.endIdx}}</td>`;
                html += `<td style="padding: 8px; border: 1px solid #ddd;">${{align.peakIdx}}</td>`;
                html += `<td style="padding: 8px; border: 1px solid #ddd;">${{span}}</td>`;
                html += `<td style="padding: 8px; border: 1px solid #ddd;">${{align.avgWeight.toFixed(4)}}</td>`;
                html += `<td style="padding: 8px; border: 1px solid #ddd;"><span class="confidence ${{confidence}}">${{confidence}}</span></td>`;
                html += '</tr>';
            }}

            html += '</table>';
            panel.innerHTML = html;
        }}

        function updateVisualization() {{
            const alignments = drawAlignmentChart();
            drawTimeline(alignments);
            const highThreshold = parseInt(confidenceHighSlider.value) / 100;
            const mediumThreshold = parseInt(confidenceMediumSlider.value) / 100;
            updateDetailsPanel(alignments, highThreshold, mediumThreshold);
        }}

        // Event listeners for sliders
        peakSlider.addEventListener('input', function() {{
            peakValue.textContent = peakSlider.value + '%';
            updateVisualization();
        }});

        confidenceHighSlider.addEventListener('input', function() {{
            const val = parseInt(confidenceHighSlider.value) / 100;
            confidenceHighValue.textContent = val.toFixed(2);
            updateVisualization();
        }});

        confidenceMediumSlider.addEventListener('input', function() {{
            const val = parseInt(confidenceMediumSlider.value) / 100;
            confidenceMediumValue.textContent = val.toFixed(2);
            updateVisualization();
        }});

        // Initial visualization
        updateVisualization();
    </script>
</body>
</html>
"""

    # 5. Write the HTML file
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(html_content)

    print(f"✓ Interactive HTML generated: {output_path}")
    print("  Open this file in a browser and use the sliders to adjust thresholds.")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python generate_interactive_alignment.py <sample_dir>")
        print("Example: python generate_interactive_alignment.py detailed_prediction_20251226_022246/sample_000")
        sys.exit(1)

    sample_dir = Path(sys.argv[1])

    if not sample_dir.exists():
        print(f"Error: directory not found: {sample_dir}")
        sys.exit(1)

    output_path = sample_dir / "interactive_alignment.html"
    generate_interactive_html(sample_dir, output_path)

    print("\nUsage:")
    print(f"  Open in a browser: {output_path.absolute()}")
    print("  Move the sliders to preview different threshold settings in real time.")