File size: 4,111 Bytes
741864d
 
9f9e779
741864d
9f9e779
741864d
 
9f9e779
741864d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
741864d
 
 
9f9e779
741864d
 
 
 
 
 
 
9f9e779
741864d
 
 
 
 
 
9f9e779
741864d
 
 
 
 
 
9f9e779
741864d
9f9e779
741864d
 
 
 
 
 
 
9f9e779
741864d
 
 
 
 
 
 
 
 
 
 
 
9f9e779
 
741864d
 
9f9e779
741864d
9f9e779
741864d
 
 
9f9e779
741864d
 
 
 
 
 
9f9e779
 
741864d
 
 
 
 
 
 
9f9e779
741864d
 
 
9f9e779
741864d
 
9f9e779
 
 
741864d
 
 
 
eaf4dff
 
 
741864d
9f9e779
741864d
 
 
 
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
#!/usr/bin/env python3
"""
Regenerate visualization assets (using the latest attention_analysis.py).

Usage:
    python regenerate_visualizations.py <detailed_prediction_dir> <video_path>

Example:
    python regenerate_visualizations.py detailed_prediction_20251226_161117 ./eval/tiny_test_data/videos/632051.mp4
"""

import sys
import os
from pathlib import Path

# 添加项目根目录到path
SCRIPT_DIR = Path(__file__).parent.parent
sys.path.insert(0, str(SCRIPT_DIR))

from eval.attention_analysis import AttentionAnalyzer
import numpy as np


def regenerate_sample_visualizations(sample_dir, video_path):
    """Regenerate every visualization asset for a single sample directory."""
    sample_dir = Path(sample_dir)

    if not sample_dir.exists():
        print(f"Error: sample directory not found: {sample_dir}")
        return False

    # 加载数据
    attn_file = sample_dir / "attention_weights.npy"
    trans_file = sample_dir / "translation.txt"

    if not attn_file.exists() or not trans_file.exists():
        print(f"  Skipping {sample_dir.name}: required files are missing")
        return False

    # 读取数据
    attention_weights = np.load(attn_file)
    with open(trans_file, 'r') as f:
        lines = f.readlines()
        # Prefer the translation following the "Clean:" line
        translation = None
        for line in lines:
            if line.startswith('Clean:'):
                translation = line.replace('Clean:', '').strip()
                break
        if translation is None:
            translation = lines[0].strip()  # fallback

    # Determine feature count (video_frames)
    if len(attention_weights.shape) == 4:
        video_frames = attention_weights.shape[3]
    elif len(attention_weights.shape) == 3:
        video_frames = attention_weights.shape[2]
    else:
        video_frames = attention_weights.shape[1]

    print(f"  Sample: {sample_dir.name}")
    print(f"    Attention shape: {attention_weights.shape}")
    print(f"    Translation: {translation}")
    print(f"    Features: {video_frames}")

    # 创建分析器
    analyzer = AttentionAnalyzer(
        attentions=attention_weights,
        translation=translation,
        video_frames=video_frames,
        video_path=str(video_path) if video_path else None
    )

    # Regenerate frame_alignment.png (with original-frame layer)
    print("    Regenerating frame_alignment.png...")
    analyzer.plot_frame_alignment(sample_dir / "frame_alignment.png")

    # Regenerate gloss_to_frames.png (feature index overlay)
    if video_path and Path(video_path).exists():
        print("    Regenerating gloss_to_frames.png...")
        try:
            analyzer.generate_gloss_to_frames_visualization(sample_dir / "gloss_to_frames.png")
        except Exception as e:
            print(f"      Warning: failed to create gloss_to_frames.png: {e}")

    return True


def main():
    if len(sys.argv) < 2:
        print("Usage: python regenerate_visualizations.py <detailed_prediction_dir> [<video_path>]")
        print("\nExample:")
        print("  python regenerate_visualizations.py detailed_prediction_20251226_161117 ./eval/tiny_test_data/videos/632051.mp4")
        sys.exit(1)

    pred_dir = Path(sys.argv[1])
    video_path = Path(sys.argv[2]) if len(sys.argv) > 2 else None

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

    if video_path and not video_path.exists():
        print(f"Warning: video file not found, disabling video overlays: {video_path}")
        video_path = None

    print("Regenerating visualizations:")
    print(f"  Detailed prediction dir: {pred_dir}")
    print(f"  Video path: {video_path if video_path else 'N/A'}")
    print()

    # 处理所有样本
    success_count = 0
    for sample_dir in sorted([d for d in pred_dir.iterdir() if d.is_dir()]):
        if regenerate_sample_visualizations(sample_dir, video_path):
            success_count += 1

    print(f"\n✓ Done! Successfully processed {success_count} sample(s)")


if __name__ == "__main__":
    main()