#!/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 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""" Interactive Word-Frame Alignment

🎯 Interactive Word-to-Frame Alignment Visualizer

Translation: {' '.join(glosses)}
Total Words: {num_glosses} | Total Features: {num_features}

βš™οΈ Threshold Controls

90%
A frame is considered β€œsignificant” if its attention β‰₯ (peak Γ— threshold%)
0.50
0.20

Word-to-Frame Alignment

Each word appears as a colored block. Width = frame span, β˜… = peak frame, waveform = attention trace.

Timeline Progress Bar

Legend:

High Medium Low Confidence Levels (opacity reflects confidence)
β˜… Peak Frame (highest attention)
━ Attention Waveform (within word region)

Alignment Details

""" # 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 ") 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.")