File size: 39,605 Bytes
9803b71
 
9f9e779
9803b71
9f9e779
 
 
 
 
9803b71
9f9e779
9803b71
 
 
 
 
 
 
 
 
 
 
 
7162aa8
9803b71
7162aa8
 
9803b71
 
 
 
 
 
9f9e779
9803b71
7162aa8
 
9803b71
 
 
9f9e779
 
 
 
 
 
 
 
9803b71
 
 
 
9f9e779
9803b71
 
 
9f9e779
7162aa8
 
 
 
 
 
9f9e779
7162aa8
 
 
 
 
 
 
9f9e779
7162aa8
9f9e779
9803b71
 
 
 
 
 
 
9f9e779
9803b71
64c94cf
9803b71
 
 
9f9e779
9803b71
 
9f9e779
9803b71
 
 
 
 
9f9e779
9803b71
 
 
 
 
 
 
 
 
 
 
 
9f9e779
9803b71
 
 
9f9e779
741864d
9803b71
 
 
 
 
 
 
 
 
 
 
9f9e779
9803b71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64c94cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9803b71
 
9f9e779
9803b71
 
 
 
9f9e779
9803b71
9f9e779
9803b71
 
9f9e779
9803b71
 
9f9e779
9803b71
 
9f9e779
9803b71
 
9f9e779
9803b71
 
9f9e779
7162aa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
9803b71
 
9f9e779
9803b71
 
 
 
 
9f9e779
9803b71
 
 
 
9f9e779
9803b71
 
 
9f9e779
9803b71
 
 
 
 
9f9e779
9803b71
 
 
 
9f9e779
9803b71
 
 
 
 
eaf4dff
 
 
9803b71
 
eaf4dff
9803b71
 
9f9e779
9803b71
 
 
 
 
 
 
9f9e779
9803b71
 
de8597b
 
741864d
 
de8597b
741864d
 
 
 
 
 
 
 
de8597b
 
741864d
de8597b
 
 
 
 
 
 
 
64c94cf
741864d
de8597b
 
 
 
 
 
64c94cf
de8597b
 
 
64c94cf
 
de8597b
64c94cf
 
741864d
9f9e779
de8597b
 
741864d
 
de8597b
 
 
741864d
 
 
de8597b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
de8597b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64c94cf
 
 
 
 
de8597b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64c94cf
 
 
 
 
de8597b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9803b71
 
9f9e779
9803b71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
9803b71
 
9f9e779
9803b71
 
9f9e779
9803b71
9f9e779
9803b71
 
 
9f9e779
9803b71
9f9e779
 
9803b71
9f9e779
9803b71
9f9e779
 
9803b71
9f9e779
9803b71
9f9e779
 
9803b71
 
9f9e779
9803b71
 
 
 
 
 
 
 
 
 
 
9f9e779
9803b71
 
 
 
 
 
 
9f9e779
9803b71
9f9e779
 
 
 
9803b71
 
 
 
 
7162aa8
 
9f9e779
7162aa8
 
9f9e779
7162aa8
 
9f9e779
7162aa8
 
 
 
9f9e779
7162aa8
 
9f9e779
7162aa8
 
 
 
 
 
9f9e779
7162aa8
 
9f9e779
7162aa8
 
9f9e779
7162aa8
 
 
 
 
 
 
 
 
 
 
9f9e779
7162aa8
 
 
 
 
 
 
 
 
 
 
 
9f9e779
7162aa8
 
 
9f9e779
7162aa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
7162aa8
9f9e779
7162aa8
 
 
 
 
9f9e779
7162aa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
7162aa8
9f9e779
7162aa8
 
9f9e779
7162aa8
9f9e779
7162aa8
 
 
 
9f9e779
 
 
 
7162aa8
 
 
 
 
 
 
 
 
 
 
 
9f9e779
193d58a
 
 
 
 
 
 
 
 
 
 
9f9e779
7162aa8
 
9f9e779
7162aa8
 
 
9f9e779
193d58a
9f9e779
193d58a
 
9f9e779
193d58a
 
 
 
9f9e779
193d58a
 
 
 
7162aa8
9f9e779
 
7162aa8
 
 
 
 
 
9f9e779
7162aa8
193d58a
 
7162aa8
 
9f9e779
7162aa8
 
 
 
 
9f9e779
741864d
7162aa8
9f9e779
7162aa8
 
 
 
741864d
 
 
 
3a4b7bf
741864d
 
 
 
 
 
 
9f9e779
193d58a
 
 
 
 
9f9e779
193d58a
 
 
 
9f9e779
193d58a
 
 
 
 
9f9e779
193d58a
 
 
9f9e779
193d58a
 
 
 
 
 
 
 
 
 
9f9e779
193d58a
 
 
 
 
9f9e779
193d58a
 
 
 
9f9e779
193d58a
 
 
 
 
9f9e779
193d58a
 
 
9f9e779
193d58a
 
 
 
 
7162aa8
193d58a
 
7162aa8
193d58a
7162aa8
741864d
7162aa8
 
 
 
 
 
 
 
9f9e779
7162aa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
7162aa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9803b71
 
9f9e779
9803b71
 
9f9e779
 
 
 
9803b71
 
 
 
 
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
#!/usr/bin/env python3
"""
Attention weight analysis and visualization helpers for SignX.

Capabilities:
1. Parse attention weight tensors
2. Map each generated gloss to video frame ranges
3. Render visual assets (heatmaps, alignment plots, timelines)
4. Write detailed analysis reports

Example:
    from eval.attention_analysis import AttentionAnalyzer

    analyzer = AttentionAnalyzer(
        attentions=attention_weights,  # [time, batch, beam, src_len]
        translation="WORD1 WORD2 WORD3",
        video_frames=100
    )

    analyzer.generate_all_visualizations(output_dir="results/")
"""

import os
import io
import json
import shutil
import subprocess
import numpy as np
from pathlib import Path
from datetime import datetime


class AttentionAnalyzer:
    """Analyze attention tensors and generate visual/debug artifacts."""

    def __init__(self, attentions, translation, video_frames, beam_sequences=None, beam_scores=None,
                 video_path=None, original_video_fps=30, original_video_total_frames=None):
        """
        Args:
            attentions: numpy array, shape [time_steps, batch, beam, src_len]
                       or [time_steps, src_len] (best beam already selected)
            translation: str, BPE-removed gloss sequence
            video_frames: int, number of SMKD feature frames
            beam_sequences: list, optional beam texts
            beam_scores: list, optional beam scores
            video_path: str, optional path to original video (for frame grabs)
            original_video_fps: int, FPS of original video (default 30)
            original_video_total_frames: optional exact frame count
        """
        self.attentions = attentions
        self.translation = translation
        self.words = translation.split()
        self.video_frames = video_frames
        self.beam_sequences = beam_sequences
        self.beam_scores = beam_scores

        # Video metadata
        self.video_path = video_path
        self.original_video_fps = original_video_fps
        self.original_video_total_frames = original_video_total_frames
        self._cv2_module = None
        self._cv2_checked = False

        # Auto-read metadata if only video path is given
        if video_path and original_video_total_frames is None:
            metadata = self._read_video_metadata()
            if metadata:
                self.original_video_total_frames = metadata.get('frames')
                if metadata.get('fps'):
                    self.original_video_fps = metadata['fps']
            elif video_path:
                print(f"Warning: failed to parse video metadata; gloss-to-frame visualization may be misaligned ({video_path})")

        # Always operate on the best path (batch=0, beam=0)
        if len(attentions.shape) == 4:
            self.attn_best = attentions[:, 0, 0, :]  # [time, src_len]
        elif len(attentions.shape) == 3:
            self.attn_best = attentions[:, 0, :]  # [time, src_len]
        else:
            self.attn_best = attentions  # [time, src_len]

        # Pre-compute gloss-to-frame ranges
        self.word_frame_ranges = self._compute_word_frame_ranges()
        self.frame_attention_strength = self._compute_frame_attention_strength()

    def _compute_word_frame_ranges(self):
        """
        Compute the dominant video frame range for each generated word.

        Returns:
            list of dict entries containing word, frame range, peak, and confidence.
        """
        word_ranges = []

        for word_idx, word in enumerate(self.words):
            if word_idx >= self.attn_best.shape[0]:
                # Out of range
                word_ranges.append({
                    'word': word,
                    'start_frame': 0,
                    'end_frame': 0,
                    'peak_frame': 0,
                    'avg_attention': 0.0,
                    'confidence': 'unknown'
                })
                continue

            attn_weights = self.attn_best[word_idx, :]

            # Peak frame for this word
            peak_frame = int(np.argmax(attn_weights))
            peak_weight = attn_weights[peak_frame]

            # Frames whose weight >= 90% of the peak
            threshold = peak_weight * 0.9
            significant_frames = np.where(attn_weights >= threshold)[0]

            if len(significant_frames) > 0:
                start_frame = int(significant_frames[0])
                end_frame = int(significant_frames[-1])
                avg_weight = float(attn_weights[significant_frames].mean())
            else:
                start_frame = peak_frame
                end_frame = peak_frame
                avg_weight = float(peak_weight)

            # Qualitative confidence bucket
            if avg_weight > 0.5:
                confidence = 'high'
            elif avg_weight > 0.2:
                confidence = 'medium'
            else:
                confidence = 'low'

            word_ranges.append({
                'word': word,
                'start_frame': start_frame,
                'end_frame': end_frame,
                'peak_frame': peak_frame,
                'avg_attention': avg_weight,
                'confidence': confidence
            })

        return word_ranges

    def _compute_frame_attention_strength(self):
        """Compute average attention per feature frame (normalized 0-1)."""
        if self.attn_best.size == 0:
            return np.zeros(self.video_frames, dtype=np.float32)

        if self.attn_best.ndim == 1:
            frame_strength = self.attn_best.copy()
        else:
            frame_strength = self.attn_best.mean(axis=0)

        if frame_strength.shape[0] != self.video_frames:
            frame_strength = np.resize(frame_strength, self.video_frames)

        max_val = frame_strength.max()
        if max_val > 0:
            frame_strength = frame_strength / max_val
        return frame_strength

    def _map_strength_to_original_frames(self, mapping_list, original_frame_count):
        """Map latent attention strength to original video frame resolution."""
        if not mapping_list or original_frame_count <= 0:
            return None

        orig_strength = np.zeros(original_frame_count, dtype=np.float32)
        counts = np.zeros(original_frame_count, dtype=np.float32)

        for feat_idx, mapping in enumerate(mapping_list):
            if feat_idx >= len(self.frame_attention_strength):
                break
            start = int(mapping.get('frame_start', 0))
            end = int(mapping.get('frame_end', start))
            end = max(end, start + 1)
            start = max(start, 0)
            end = min(end, original_frame_count)
            if start >= end:
                continue
            orig_strength[start:end] += self.frame_attention_strength[feat_idx]
            counts[start:end] += 1

        mask = counts > 0
        if mask.any():
            orig_strength[mask] = orig_strength[mask] / counts[mask]

        max_val = orig_strength.max()
        if max_val > 0:
            orig_strength = orig_strength / max_val
        return orig_strength

    def generate_all_visualizations(self, output_dir):
        """
        Generate every visualization artifact to the provided directory.
        """
        output_dir = Path(output_dir)
        output_dir.mkdir(parents=True, exist_ok=True)

        print(f"\nGenerating visualization assets in: {output_dir}")

        # 1. Attention heatmap
        self.plot_attention_heatmap(output_dir / "attention_heatmap.png")

        # 2. Frame alignment
        self.plot_frame_alignment(output_dir / "frame_alignment.png")

        # 3. JSON metadata
        self.save_alignment_data(output_dir / "frame_alignment.json")

        # 4. Text report
        self.save_text_report(output_dir / "analysis_report.txt")

        # 5. Raw numpy dump (for downstream tooling)
        np.save(output_dir / "attention_weights.npy", self.attentions)

        # 6. Gloss-to-Frames visualization (if video is available)
        # Write debug info to file
        debug_file = output_dir / "debug_video_path.txt"
        with open(debug_file, 'w') as f:
            f.write(f"video_path = {repr(self.video_path)}\n")
            f.write(f"video_path type = {type(self.video_path)}\n")
            f.write(f"video_path is None: {self.video_path is None}\n")
            f.write(f"bool(video_path): {bool(self.video_path)}\n")

        print(f"[DEBUG] video_path = {self.video_path}")
        if self.video_path:
            print(f"[DEBUG] Generating gloss-to-frames visualization with video: {self.video_path}")
            try:
                self.generate_gloss_to_frames_visualization(output_dir / "gloss_to_frames.png")
                print(f"[DEBUG] Successfully generated gloss_to_frames.png")
            except Exception as e:
                print(f"[DEBUG] Failed to generate gloss_to_frames.png: {e}")
                import traceback
                traceback.print_exc()
        else:
            print("[DEBUG] Skipping gloss-to-frames visualization (no video path provided)")

        print(f"βœ“ Wrote {len(list(output_dir.glob('*')))} file(s)")

    def plot_attention_heatmap(self, output_path):
        """Render the attention heatmap (image + PDF copy)."""
        try:
            import matplotlib
            matplotlib.use('Agg')
            import matplotlib.pyplot as plt
        except ImportError:
            print("  Skipping heatmap: matplotlib is not available")
            return

        fig, ax = plt.subplots(figsize=(14, 8))

        # Heatmap
        im = ax.imshow(self.attn_best.T, cmap='hot', aspect='auto',
                      interpolation='nearest', origin='lower')

        # Axis labels
        ax.set_xlabel('Generated Word Index', fontsize=13)
        ax.set_ylabel('Video Frame Index', fontsize=13)
        ax.set_title('Cross-Attention Weights\n(Decoder β†’ Video Frames)',
                    fontsize=15, pad=20, fontweight='bold')

        # Word labels on the x-axis
        if len(self.words) <= self.attn_best.shape[0]:
            ax.set_xticks(range(len(self.words)))
            ax.set_xticklabels(self.words, rotation=45, ha='right', fontsize=10)

        # Color bar
        cbar = plt.colorbar(im, ax=ax, label='Attention Weight', fraction=0.046, pad=0.04)
        cbar.ax.tick_params(labelsize=10)

        plt.tight_layout()
        plt.savefig(output_path, dpi=150, bbox_inches='tight')
        # also save PDF copy for high-res usage
        pdf_path = Path(output_path).with_suffix('.pdf')
        plt.savefig(str(pdf_path), format='pdf', bbox_inches='tight')
        plt.close()

        print(f"  βœ“ {output_path.name} (PDF copy saved)")

    def plot_frame_alignment(self, output_path):
        """Render the frame-alignment charts (full + compact)."""
        try:
            import matplotlib
            matplotlib.use('Agg')
            import matplotlib.pyplot as plt
            import matplotlib.patches as patches
            from matplotlib.gridspec import GridSpec
        except ImportError:
            print("  Skipping alignment plot: matplotlib is not available")
            return

        output_path = Path(output_path)

        # Try to load feature-to-frame mapping
        feature_mapping = None
        output_dir = output_path.parent
        mapping_file = output_dir / "feature_frame_mapping.json"
        if mapping_file.exists():
            try:
                with open(mapping_file, 'r') as f:
                    feature_mapping = json.load(f)
            except Exception as e:
                print(f"  Warning: Failed to load feature mapping: {e}")

        if self.word_frame_ranges:
            max_feat_end = max(w['end_frame'] for w in self.word_frame_ranges)
        else:
            max_feat_end = self.video_frames - 1
        latent_full_limit = self.video_frames + 2
        latent_short_limit = max(min(latent_full_limit, max_feat_end + 2), 5)

        original_frame_count = None
        mapping_list = None
        orig_full_limit = None
        orig_short_limit = None
        pixel_strength_curve = None
        if feature_mapping:
            original_frame_count = feature_mapping.get('original_frame_count', self.video_frames)
            mapping_list = feature_mapping.get('mapping', [])
            orig_full_limit = original_frame_count + 2
            if mapping_list:
                idx = min(max_feat_end, len(mapping_list) - 1)
                orig_short_limit = mapping_list[idx]['frame_end'] + 2
            pixel_strength_curve = self._map_strength_to_original_frames(mapping_list, original_frame_count)

        def render_alignment(out_path, latent_xlim_end, orig_xlim_end=None):
            if feature_mapping:
                fig = plt.figure(figsize=(18, 9))
                gs = GridSpec(3, 1, height_ratios=[4, 1, 1], hspace=0.32)
            else:
                fig = plt.figure(figsize=(18, 7.5))
                gs = GridSpec(2, 1, height_ratios=[4, 1], hspace=0.32)

            # === Top plot: word-to-frame alignment ===
            ax1 = fig.add_subplot(gs[0])
            colors = plt.cm.tab20(np.linspace(0, 1, max(len(self.words), 20)))

            for i, word_info in enumerate(self.word_frame_ranges):
                start = word_info['start_frame']
                end = word_info['end_frame']
                word = word_info['word']
                confidence = word_info['confidence']
                alpha = 0.9 if confidence == 'high' else 0.7 if confidence == 'medium' else 0.5

                rect = patches.Rectangle(
                    (start, i), end - start + 1, 0.8,
                    linewidth=2, edgecolor='black',
                    facecolor=colors[i % 20], alpha=alpha
                )
                ax1.add_patch(rect)

                ax1.text(start + (end - start) / 2, i + 0.4, word,
                        ha='center', va='center', fontsize=11,
                        fontweight='bold', color='white',
                        bbox=dict(boxstyle='round,pad=0.3', facecolor='black', alpha=0.5))

                peak = word_info['peak_frame']
                ax1.plot(peak, i + 0.4, 'r*', markersize=15, markeredgecolor='yellow',
                        markeredgewidth=1.5)

            ax1.set_xlim(-2, latent_xlim_end)
            ax1.set_ylim(-0.5, len(self.words))
            ax1.set_xlabel('')
            ax1.set_ylabel('')
            ax1.set_title('Word-to-Frame Alignment\n(based on attention peaks, β˜… = peak frame)',
                         fontsize=15, pad=15, fontweight='bold')
            ax1.grid(True, alpha=0.3, axis='x', linestyle='--')
            ax1.set_yticks(range(len(self.words)))
            ax1.set_yticklabels([w['word'] for w in self.word_frame_ranges], fontsize=10)

            # === Middle plot: latent timeline ===
            ax2 = fig.add_subplot(gs[1])
            ax2.barh(0, self.video_frames, height=0.6, color='lightgray',
                    edgecolor='black', linewidth=2)
            for i, word_info in enumerate(self.word_frame_ranges):
                start = word_info['start_frame']
                end = word_info['end_frame']
                confidence = word_info['confidence']
                alpha = 0.9 if confidence == 'high' else 0.7 if confidence == 'medium' else 0.5
                ax2.barh(0, end - start + 1, left=start, height=0.6,
                        color=colors[i % 20], alpha=alpha, edgecolor='black', linewidth=0.5)

            ax2.set_xlim(-2, latent_xlim_end)
            ax2.set_ylim(-0.4, 0.4)
            ax2.set_xlabel('')
            ax2.set_yticks([0])
            ax2.set_yticklabels(['Latent Space'], fontsize=11, fontweight='bold')
            ax2.tick_params(axis='y', length=0)
            ax2.set_title('Latent Feature Timeline', fontsize=13, fontweight='bold')
            ax2.grid(True, alpha=0.3, axis='x', linestyle='--')

            if self.frame_attention_strength is not None and len(self.frame_attention_strength) >= self.video_frames:
                latent_curve_x = np.arange(self.video_frames)
                latent_curve_y = self.frame_attention_strength[:self.video_frames] * 0.6 - 0.3
                ax2.plot(latent_curve_x, latent_curve_y, color='#E53935', linewidth=1.5, alpha=0.9)

            timeline_axes = [ax2]

            if feature_mapping:
                ax3 = fig.add_subplot(gs[2])
                ax3.barh(0, original_frame_count, height=0.6, color='lightgray',
                        edgecolor='black', linewidth=2)

                for i, word_info in enumerate(self.word_frame_ranges):
                    feat_start = word_info['start_frame']
                    feat_end = word_info['end_frame']
                    confidence = word_info['confidence']
                    alpha = 0.9 if confidence == 'high' else 0.7 if confidence == 'medium' else 0.5
                    if mapping_list and feat_start < len(mapping_list) and feat_end < len(mapping_list):
                        orig_start = mapping_list[feat_start]['frame_start']
                        orig_end = mapping_list[feat_end]['frame_end']
                        ax3.barh(0, orig_end - orig_start, left=orig_start, height=0.6,
                                color=colors[i % 20], alpha=alpha, edgecolor='black', linewidth=0.5)

                ax3_xlim = orig_xlim_end if orig_xlim_end is not None else original_frame_count + 2
                ax3.set_xlim(-2, ax3_xlim)
                ax3.set_ylim(-0.4, 0.4)
                ax3.set_xlabel('')
                ax3.set_yticks([0])
                ax3.set_yticklabels(['Pixel Space'], fontsize=11, fontweight='bold')
                ax3.tick_params(axis='y', length=0)
                ax3.set_title(f'Original Video Timeline ({original_frame_count} frames, '
                             f'{feature_mapping["downsampling_ratio"]:.2f}x downsampling)',
                             fontsize=13, fontweight='bold')
                ax3.grid(True, alpha=0.3, axis='x', linestyle='--')

                if pixel_strength_curve is not None and len(pixel_strength_curve) >= original_frame_count:
                    pixel_curve_x = np.arange(original_frame_count)
                    pixel_curve_y = pixel_strength_curve[:original_frame_count] * 0.6 - 0.3
                    ax3.plot(pixel_curve_x, pixel_curve_y, color='#E53935', linewidth=1.5, alpha=0.9)
                timeline_axes.append(ax3)

            plt.tight_layout()
            fig.canvas.draw()

            ax1_pos = ax1.get_position()
            renderer = fig.canvas.get_renderer()
            ytick_extents = [tick.get_window_extent(renderer) for tick in ax1.get_yticklabels() if tick.get_text()]
            fig_width_px = fig.get_size_inches()[0] * fig.dpi
            if ytick_extents:
                min_x_px = min(ext.x0 for ext in ytick_extents)
            else:
                min_x_px = ax1_pos.x0 * fig_width_px
            line_x = max(0.01, (min_x_px / fig_width_px) - 0.01)
            gw_center = 0.5 * (ax1_pos.y0 + ax1_pos.y1)
            timeline_bounds = [ax.get_position() for ax in timeline_axes]
            timeline_center = 0.5 * (min(pos.y0 for pos in timeline_bounds) + max(pos.y1 for pos in timeline_bounds))
            fig.text(line_x, gw_center, 'Generated Word', rotation='vertical',
                     ha='right', va='center', fontsize=12, fontweight='bold')
            fig.text(line_x, timeline_center, 'Timeline', rotation='vertical',
                     ha='right', va='center', fontsize=12, fontweight='bold')

            png_path = Path(out_path)
            plt.savefig(str(png_path), dpi=150, bbox_inches='tight')
            pdf_path = png_path.with_suffix('.pdf')
            plt.savefig(str(pdf_path), format='pdf', bbox_inches='tight')
            plt.close()

            print(f"  βœ“ {png_path.name} (PDF copy saved)")

        render_alignment(output_path, latent_full_limit, orig_full_limit)

        if latent_short_limit < latent_full_limit - 1e-6:
            short_path = output_path.with_name("frame_alignment_short.png")
            render_alignment(short_path, latent_short_limit, orig_short_limit if orig_short_limit else orig_full_limit)

    def save_alignment_data(self, output_path):
        """Persist frame-alignment metadata to JSON."""
        data = {
            'translation': self.translation,
            'words': self.words,
            'total_video_frames': self.video_frames,
            'frame_ranges': self.word_frame_ranges,
            'statistics': {
                'avg_confidence': np.mean([w['avg_attention'] for w in self.word_frame_ranges]),
                'high_confidence_words': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'high'),
                'medium_confidence_words': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'medium'),
                'low_confidence_words': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'low'),
            }
        }

        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)

        print(f"  βœ“ {output_path.name}")

    def save_text_report(self, output_path):
        """Write a plain-text report (used for analysis_report.txt)."""
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write("=" * 80 + "\n")
            f.write("  Sign Language Recognition - Attention Analysis Report\n")
            f.write("=" * 80 + "\n\n")

            f.write(f"Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")

            f.write("Translation:\n")
            f.write("-" * 80 + "\n")
            f.write(f"{self.translation}\n\n")

            f.write("Video info:\n")
            f.write("-" * 80 + "\n")
            f.write(f"Total feature frames: {self.video_frames}\n")
            f.write(f"Word count: {len(self.words)}\n\n")

            f.write("Attention tensor:\n")
            f.write("-" * 80 + "\n")
            f.write(f"Shape: {self.attentions.shape}\n")
            f.write(f"  - Decoder steps: {self.attentions.shape[0]}\n")
            if len(self.attentions.shape) >= 3:
                f.write(f"  - Batch size: {self.attentions.shape[1]}\n")
            if len(self.attentions.shape) >= 4:
                f.write(f"  - Beam size: {self.attentions.shape[2]}\n")
                f.write(f"  - Source length: {self.attentions.shape[3]}\n")
            f.write("\n")

            f.write("Word-to-frame details:\n")
            f.write("=" * 80 + "\n")
            f.write(f"{'No.':<5} {'Word':<20} {'Frames':<15} {'Peak':<8} {'Attn':<8} {'Conf':<10}\n")
            f.write("-" * 80 + "\n")

            for i, w in enumerate(self.word_frame_ranges):
                frame_range = f"{w['start_frame']}-{w['end_frame']}"
                f.write(f"{i+1:<5} {w['word']:<20} {frame_range:<15} "
                       f"{w['peak_frame']:<8} {w['avg_attention']:<8.3f} {w['confidence']:<10}\n")

            f.write("\n" + "=" * 80 + "\n")

            # Summary
            stats = {
                'avg_confidence': np.mean([w['avg_attention'] for w in self.word_frame_ranges]),
                'high': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'high'),
                'medium': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'medium'),
                'low': sum(1 for w in self.word_frame_ranges if w['confidence'] == 'low'),
            }

            f.write("\nSummary:\n")
            f.write("-" * 80 + "\n")
            f.write(f"Average attention weight: {stats['avg_confidence']:.3f}\n")
            f.write(f"High-confidence words: {stats['high']} ({stats['high']/len(self.words)*100:.1f}%)\n")
            f.write(f"Medium-confidence words: {stats['medium']} ({stats['medium']/len(self.words)*100:.1f}%)\n")
            f.write(f"Low-confidence words: {stats['low']} ({stats['low']/len(self.words)*100:.1f}%)\n")
            f.write("\n" + "=" * 80 + "\n")

        print(f"  βœ“ {output_path.name}")


    def _map_feature_frame_to_original(self, feature_frame_idx):
        """
        Map a SMKD feature frame index back to the original video frame index.

        Args:
            feature_frame_idx: Zero-based feature frame index

        Returns:
            int: Original frame index, or None if unavailable.
        """
        if self.original_video_total_frames is None:
            return None

        # Approximate downsampling ratio between latent frames and original frames
        downsample_ratio = self.original_video_total_frames / self.video_frames

        # Map latent index to original frame index
        original_frame_idx = int(feature_frame_idx * downsample_ratio)

        return min(original_frame_idx, self.original_video_total_frames - 1)

    def _extract_video_frames(self, frame_indices):
        """
        Extract the requested original video frames (best-effort).

        Args:
            frame_indices: list[int] of original frame IDs to load

        Returns:
            dict mapping frame index to numpy array (BGR).
        """
        if not self.video_path:
            return {}

        cv2 = self._get_cv2_module()
        if cv2 is not None:
            return self._extract_frames_with_cv2(cv2, frame_indices)

        return self._extract_frames_with_ffmpeg(frame_indices)

    def _get_cv2_module(self):
        """Lazy-load cv2 and cache the import outcome."""
        if self._cv2_checked:
            return self._cv2_module

        try:
            import cv2
            self._cv2_module = cv2
        except ImportError:
            self._cv2_module = None
        finally:
            self._cv2_checked = True

        if self._cv2_module is None:
            print("Warning: opencv-python is missing; falling back to ffmpeg grabs")
        return self._cv2_module

    def _extract_frames_with_cv2(self, cv2, frame_indices):
        """Extract frames via OpenCV if available."""
        frames = {}
        cap = cv2.VideoCapture(self.video_path)

        if not cap.isOpened():
            print(f"Warning: Cannot open video file: {self.video_path}")
            return {}

        for frame_idx in sorted(frame_indices):
            cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
            ret, frame = cap.read()
            if ret:
                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                frames[frame_idx] = frame_rgb

        cap.release()
        return frames

    def _extract_frames_with_ffmpeg(self, frame_indices):
        """Extract frames via ffmpeg + Pillow (OpenCV fallback)."""
        if shutil.which("ffmpeg") is None:
            print("Warning: ffmpeg not found; cannot extract frames")
            return {}

        try:
            from PIL import Image
        except ImportError:
            print("Warning: Pillow not installed; cannot decode ffmpeg output")
            return {}

        frames = {}
        for frame_idx in sorted(frame_indices):
            cmd = [
                "ffmpeg",
                "-v", "error",
                "-i", str(self.video_path),
                "-vf", f"select=eq(n\\,{frame_idx})",
                "-vframes", "1",
                "-f", "image2pipe",
                "-vcodec", "png",
                "-"
            ]
            try:
                result = subprocess.run(
                    cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )
                if not result.stdout:
                    continue
                image = Image.open(io.BytesIO(result.stdout)).convert("RGB")
                frames[frame_idx] = np.array(image)
            except subprocess.CalledProcessError as e:
                print(f"Warning: ffmpeg failed to extract frame {frame_idx}: {e}")
            except Exception as ex:
                print(f"Warning: failed to decode frame {frame_idx}: {ex}")

        if frames:
            print(f"  βœ“ Extracted {len(frames)} frame(s) via ffmpeg")
        else:
            print("  β“˜ ffmpeg did not return any frames")
        return frames

    def generate_gloss_to_frames_visualization(self, output_path):
        """
        Create the gloss-to-frames visualization:
            Column 1: gloss text
            Column 2: relative time + frame indices
            Column 3: representative video thumbnails
        """
        if not self.video_path:
            print("  β“˜ Skipping gloss-to-frames visualization (no video path provided)")
            return

        try:
            import matplotlib.pyplot as plt
            import matplotlib.gridspec as gridspec
        except ImportError:
            print("Warning: matplotlib not installed")
            return

        # Load feature-to-frame mapping if available
        feature_mapping = None
        output_dir = Path(output_path).parent
        mapping_file = output_dir / "feature_frame_mapping.json"
        if mapping_file.exists():
            try:
                with open(mapping_file, 'r') as f:
                    mapping_data = json.load(f)
                    feature_mapping = mapping_data['mapping']
            except Exception as e:
                print(f"  Warning: Failed to load feature mapping: {e}")

        # Collect every original frame we need to grab
        all_original_frames = set()
        for word_info in self.word_frame_ranges:
            # Feature frame range
            start_feat = word_info['start_frame']
            end_feat = word_info['end_frame']

            # Map the feature range onto original video frames
            if feature_mapping:
                # Use the precomputed mapping data
                for feat_idx in range(start_feat, end_feat + 1):
                    if feat_idx < len(feature_mapping):
                        # Pull every original frame for that feature segment
                        feat_info = feature_mapping[feat_idx]
                        for orig_idx in range(feat_info['frame_start'], feat_info['frame_end']):
                            all_original_frames.add(orig_idx)
            else:
                # Fallback: assume uniform downsampling
                for feat_idx in range(start_feat, end_feat + 1):
                    orig_idx = self._map_feature_frame_to_original(feat_idx)
                    if orig_idx is not None:
                        all_original_frames.add(orig_idx)

        # Extract the necessary frames
        print(f"  Extracting {len(all_original_frames)} original video frame(s)...")
        video_frames_dict = self._extract_video_frames(list(all_original_frames))

        if not video_frames_dict:
            print("  β“˜ No video frames extracted, skipping visualization")
            return

        # Create figure (4 columns: Gloss | Feature Index | Peak Frame | Full Span)
        n_words = len(self.words)
        fig = plt.figure(figsize=(28, 3 * n_words))
        gs = gridspec.GridSpec(n_words, 4, width_ratios=[1.5, 1.5, 2.5, 8], hspace=0.3, wspace=0.2)

        for row_idx, (word, word_info) in enumerate(zip(self.words, self.word_frame_ranges)):
            # Column 1: Gloss label
            ax_gloss = fig.add_subplot(gs[row_idx, 0])
            ax_gloss.text(0.5, 0.5, word, fontsize=24, weight='bold',
                         ha='center', va='center', wrap=True)
            ax_gloss.axis('off')

            # Column 2: Feature index info
            ax_feature = fig.add_subplot(gs[row_idx, 1])

            # Feature frame details
            feat_start = word_info['start_frame']
            feat_end = word_info['end_frame']
            feat_peak = word_info['peak_frame']

            feature_text = f"SMKD Feature Index\n"
            feature_text += f"{'='*20}\n\n"
            feature_text += f"Range:\n  {feat_start} β†’ {feat_end}\n\n"
            feature_text += f"Peak:\n  {feat_peak}\n\n"
            feature_text += f"Count:\n  {feat_end - feat_start + 1} features"

            ax_feature.text(0.5, 0.5, feature_text, fontsize=11, family='monospace',
                           va='center', ha='center',
                           bbox=dict(boxstyle='round,pad=0.8', facecolor='lightblue',
                                   edgecolor='darkblue', linewidth=2, alpha=0.7))
            ax_feature.axis('off')

            # Column 3: Original frames for the peak feature
            ax_peak_frames = fig.add_subplot(gs[row_idx, 2])

            peak_frames_to_show = []
            orig_peak_start, orig_peak_end = None, None
            if feature_mapping and feat_peak is not None and feat_peak < len(feature_mapping):
                # Use detailed mapping to determine the original frame span
                peak_info = feature_mapping[feat_peak]
                orig_peak_start = peak_info['frame_start']
                orig_peak_end = peak_info['frame_end']

                # Show each original frame linked to the peak feature range
                for orig_idx in range(orig_peak_start, orig_peak_end):
                    if orig_idx in video_frames_dict:
                        peak_frames_to_show.append(video_frames_dict[orig_idx])

            if peak_frames_to_show:
                # Horizontally stitch frames
                combined_peak = np.hstack(peak_frames_to_show)
                ax_peak_frames.imshow(combined_peak)

                # Add caption
                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)",
                                   ha='center', va='top', transform=ax_peak_frames.transAxes,
                                   fontsize=10, weight='bold', color='red',
                                   bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7))
            else:
                ax_peak_frames.text(0.5, 0.5, "No peak frames",
                                   ha='center', va='center', transform=ax_peak_frames.transAxes)

            ax_peak_frames.axis('off')

            # Column 4: All frames covered by the gloss span
            ax_all_frames = fig.add_subplot(gs[row_idx, 3])

            all_frames_to_show = []
            orig_start, orig_end = None, None
            if feature_mapping:
                # Determine range via mapping
                if feat_start < len(feature_mapping) and feat_end < len(feature_mapping):
                    orig_start = feature_mapping[feat_start]['frame_start']
                    orig_end = feature_mapping[feat_end]['frame_end']

                    # Collect every frame in the span
                    for orig_idx in range(orig_start, orig_end):
                        if orig_idx in video_frames_dict:
                            all_frames_to_show.append(video_frames_dict[orig_idx])

            if all_frames_to_show:
                # Stitch all frames horizontally
                combined_all = np.hstack(all_frames_to_show)
                ax_all_frames.imshow(combined_all)

                # Add caption showing total
                frame_count = len(all_frames_to_show)
                ax_all_frames.text(0.5, -0.05, f"All Frames ({frame_count} frames)\nRange: {orig_start}-{orig_end-1}",
                                  ha='center', va='top', transform=ax_all_frames.transAxes,
                                  fontsize=10, weight='bold', color='blue',
                                  bbox=dict(boxstyle='round,pad=0.3', facecolor='lightblue', alpha=0.7))
            else:
                ax_all_frames.text(0.5, 0.5, "No frames available",
                                  ha='center', va='center', transform=ax_all_frames.transAxes)

            ax_all_frames.axis('off')

        plt.suptitle(f"Three-Layer Alignment: Gloss ↔ Feature Index ↔ Original Frames\nTranslation: {self.translation}",
                     fontsize=16, weight='bold', y=0.995)

        plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white')
        plt.close()

        print(f"  βœ“ {Path(output_path).name}")

    def _read_video_metadata(self):
        """Attempt to read the original video's frame count and FPS."""
        metadata = self._read_metadata_with_cv2()
        if metadata:
            return metadata
        return self._read_metadata_with_ffprobe()

    def _read_metadata_with_cv2(self):
        cv2 = self._get_cv2_module()
        if cv2 is None:
            return None

        cap = cv2.VideoCapture(self.video_path)
        if not cap.isOpened():
            return None

        total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        fps = cap.get(cv2.CAP_PROP_FPS)
        cap.release()

        if total_frames <= 0:
            return None

        return {'frames': total_frames, 'fps': fps or self.original_video_fps}

    def _read_metadata_with_ffprobe(self):
        if shutil.which("ffprobe") is None:
            return None

        cmd = [
            "ffprobe",
            "-v", "error",
            "-select_streams", "v:0",
            "-show_entries", "stream=nb_frames,r_frame_rate,avg_frame_rate,duration",
            "-of", "json",
            str(self.video_path)
        ]

        try:
            result = subprocess.run(
                cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
            )
        except subprocess.CalledProcessError:
            return None

        try:
            info = json.loads(result.stdout)
        except json.JSONDecodeError:
            return None

        streams = info.get("streams") or []
        if not streams:
            return None

        stream = streams[0]
        total_frames = stream.get("nb_frames")
        fps = stream.get("avg_frame_rate") or stream.get("r_frame_rate")
        duration = stream.get("duration")

        fps_value = self._parse_ffprobe_fps(fps)
        total_frames_value = None

        if isinstance(total_frames, str) and total_frames.isdigit():
            total_frames_value = int(total_frames)

        if total_frames_value is None and duration and fps_value:
            try:
                total_frames_value = int(round(float(duration) * fps_value))
            except ValueError:
                total_frames_value = None

        if total_frames_value is None:
            return None

        return {'frames': total_frames_value, 'fps': fps_value or self.original_video_fps}

    @staticmethod
    def _parse_ffprobe_fps(rate_str):
        """Parse an ffprobe frame-rate string such as '30000/1001'."""
        if not rate_str or rate_str in ("0/0", "0"):
            return None

        if "/" in rate_str:
            num, denom = rate_str.split("/", 1)
            try:
                num = float(num)
                denom = float(denom)
                if denom == 0:
                    return None
                return num / denom
            except ValueError:
                return None

        try:
            return float(rate_str)
        except ValueError:
            return None


def analyze_from_numpy_file(attention_file, translation, video_frames, output_dir):
    """
    Load attention weights from a .npy file and generate visualization assets.

    Args:
        attention_file: Path to the numpy file
        translation: Clean translation string
        video_frames: Number of SMKD feature frames
        output_dir: Destination directory for outputs
    """
    attentions = np.load(attention_file)
    analyzer = AttentionAnalyzer(attentions, translation, video_frames)
    analyzer.generate_all_visualizations(output_dir)
    return analyzer