File size: 18,350 Bytes
1eb306c
9f9e779
1eb306c
9f9e779
 
1eb306c
9f9e779
1eb306c
a9be817
1eb306c
9f9e779
1eb306c
 
a9be817
9f9e779
a9be817
 
 
1eb306c
 
 
9f9e779
a9be817
5fb3ca1
 
a9be817
9f9e779
a9be817
 
9f9e779
a9be817
 
 
 
 
 
 
 
 
 
 
 
9f9e779
1eb306c
 
 
 
 
 
9f9e779
1eb306c
a9be817
 
 
1eb306c
 
 
 
 
9f9e779
1eb306c
 
9f9e779
 
1eb306c
 
 
 
9f9e779
1eb306c
9f9e779
1eb306c
9f9e779
1eb306c
a9be817
1eb306c
9f9e779
1eb306c
 
a9be817
1eb306c
 
 
 
 
10691cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fb3ca1
 
 
 
 
1eb306c
9f9e779
1eb306c
9f9e779
1eb306c
 
 
9f9e779
1eb306c
a9be817
9f9e779
a9be817
 
 
 
 
5fb3ca1
a9be817
5fb3ca1
1eb306c
9f9e779
 
 
 
1eb306c
 
 
9f9e779
1eb306c
 
 
9f9e779
 
1eb306c
 
 
9f9e779
1eb306c
 
9f9e779
1eb306c
9f9e779
1eb306c
9f9e779
 
1eb306c
 
9f9e779
1eb306c
 
 
9f9e779
1eb306c
 
 
9f9e779
1eb306c
 
 
9f9e779
1eb306c
9f9e779
1eb306c
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
1eb306c
 
 
 
 
 
 
 
 
9f9e779
1eb306c
 
9f9e779
1eb306c
 
 
 
9f9e779
 
1eb306c
9f9e779
 
 
1eb306c
 
9f9e779
1eb306c
 
 
9f9e779
1eb306c
9f9e779
1eb306c
 
 
9f9e779
1eb306c
 
 
 
9f9e779
1eb306c
 
9f9e779
 
 
1eb306c
 
 
 
 
9f9e779
1eb306c
 
 
 
 
9f9e779
9803b71
 
 
9f9e779
1eb306c
 
 
 
 
 
 
 
 
 
 
 
 
9803b71
1eb306c
 
 
9803b71
7162aa8
1eb306c
 
 
9f9e779
 
9803b71
1eb306c
 
 
9f9e779
1eb306c
 
 
9803b71
1eb306c
 
 
9f9e779
1eb306c
 
9f9e779
1eb306c
 
9f9e779
5fb3ca1
65e4828
9f9e779
9803b71
 
 
 
9f9e779
9803b71
 
5fb3ca1
9803b71
 
 
9f9e779
eaf4dff
 
9f9e779
7162aa8
9f9e779
7162aa8
9f9e779
741864d
9f9e779
cfee709
eaf4dff
9f9e779
eaf4dff
 
 
9f9e779
eaf4dff
 
 
741864d
9f9e779
741864d
 
9f9e779
741864d
9f9e779
741864d
eaf4dff
9f9e779
eaf4dff
 
 
741864d
9f9e779
741864d
 
cfee709
741864d
cfee709
9f9e779
741864d
9f9e779
741864d
eaf4dff
9f9e779
eaf4dff
 
 
 
 
 
 
7162aa8
9f9e779
7162aa8
741864d
9f9e779
321f47a
9f9e779
321f47a
eaf4dff
9f9e779
eaf4dff
 
 
9f9e779
eaf4dff
 
 
 
321f47a
9f9e779
321f47a
 
9f9e779
741864d
9803b71
 
 
9f9e779
5fb3ca1
 
 
 
 
9f9e779
5fb3ca1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e779
5fb3ca1
 
 
 
 
 
 
 
 
 
9f9e779
5fb3ca1
 
 
 
 
 
 
10691cc
 
 
 
 
 
 
 
 
5fb3ca1
 
 
 
 
9803b71
1eb306c
9f9e779
1eb306c
 
9f9e779
 
 
9803b71
 
9f9e779
9803b71
9f9e779
 
 
 
 
 
 
 
 
9803b71
 
1eb306c
9f9e779
1eb306c
5fb3ca1
1eb306c
 
9f9e779
1eb306c
9803b71
9f9e779
 
9803b71
9f9e779
9803b71
1eb306c
9f9e779
9803b71
1eb306c
 
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
#!/bin/bash
# Sign language recognition inference script – video to gloss sequence
#
# Full two-stage pipeline:
#   Video → [SMKD frozen] → Features → [SLTUNET] → Gloss sequence
#
# Usage:
#   ./inference.sh <video_path> [output_path]
#   ./inference.sh --benchmark-efficiency [options...]
#
# Examples:
#   ./inference.sh test.mp4
#   ./inference.sh test.mp4 output.txt
#
# Benchmark mode (used for ACL paper experiments):
#   ./inference.sh --benchmark-efficiency --video test.mp4 --num-samples 100
#   ./inference.sh --benchmark-efficiency --config full_pipeline
#   ./inference.sh --benchmark-efficiency --generate-table-only

set -e

# Resolve script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INFERENCE_ROOT="${SCRIPT_DIR}/inference_output"
mkdir -p "$INFERENCE_ROOT"

# Detect benchmark mode (scan all args)
for arg in "$@"; do
    if [ "$arg" == "--benchmark-efficiency" ]; then
# For benchmarking, redirect to simple_benchmark.sh
        echo ""
        echo "====================================================================="
        echo "  Efficiency Benchmarking"
        echo "====================================================================="
        echo ""
        echo "Please run the simple benchmark script instead:"
        echo "  bash eval/simple_benchmark.sh"
        echo ""
        exit 0
    fi
done

# ANSI colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Default configuration (7th training run with pose assistance)
SMKD_CONFIG="${SCRIPT_DIR}/smkd/asllrp_baseline.yaml"
SMKD_MODEL="/research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/SignX/smkd/work_dir第七次训练全pose协助2000/asllrp_smkd/best_model.pt"
GLOSS_DICT="/research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/SignX/smkd/asllrp第七次训练全pose协助2000/gloss_dict.npy"
SLTUNET_CHECKPOINT="/research/cbim/vast/sf895/code/Sign-X/output/huggingface_asllrp_repo/SignX/checkpoints_asllrp第七次训练全pose协助2000/best"
VOCAB_FILE="${SCRIPT_DIR}/preprocessed-asllrp/vocab.asllrp"
BPE_CODES="${SCRIPT_DIR}/preprocessed-asllrp/asllrp.bpe"

echo ""
echo "======================================================================"
echo "  Sign Language Recognition - Full Inference Pipeline"
echo "======================================================================"
echo ""
echo "  Pipeline: Video → [SMKD frozen] → Features → [SLTUNET] → Gloss"
echo "  Mode: inference (one-click two-stage execution)"
echo ""
echo "======================================================================"
echo ""

# Validate arguments
if [ "$#" -lt 1 ]; then
    echo -e "${RED}Error: missing video path${NC}"
    echo ""
    echo "Usage:"
    echo "  $0 <video_path> [output_path]"
    echo "  $0 --benchmark-efficiency [options...]"
    echo ""
    echo "Examples:"
    echo "  $0 test.mp4"
    echo "  $0 test.mp4 output.txt"
    echo "  $0 --benchmark-efficiency --video test.mp4"
    echo ""
    exit 1
fi

VIDEO_PATH="$1"

# Batch mode: if a directory is provided, iterate over supported video files.
if [ -d "$VIDEO_PATH" ]; then
    VIDEO_DIR=$(realpath "$VIDEO_PATH")
    if [ -n "$2" ]; then
        echo -e "${RED}Error: output path override is not supported in batch mode${NC}"
        exit 1
    fi

    echo ""
    echo "======================================================================"
    echo "  Batch Inference Mode"
    echo "======================================================================"
    echo "  Directory: $VIDEO_DIR"
    echo "  Outputs: stored per-video using default locations"
    echo "======================================================================"
    echo ""

    mapfile -d '' VIDEO_FILES < <(find "$VIDEO_DIR" -maxdepth 1 -type f \( -iname '*.mp4' -o -iname '*.mov' -o -iname '*.avi' -o -iname '*.mkv' \) -print0 | sort -z)
    if [ ${#VIDEO_FILES[@]} -eq 0 ]; then
        echo -e "${RED}Error: no video files (.mp4/.mov/.avi/.mkv) found under $VIDEO_DIR${NC}"
        exit 1
    fi

    batch_status=0
    total=${#VIDEO_FILES[@]}
    index=1
    for video_file in "${VIDEO_FILES[@]}"; do
        echo ""
        echo ">>> [Batch] Processing ($index/$total): $video_file"
        if bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" "$video_file"; then
            echo ">>> [Batch] Completed: $video_file"
        else
            echo ">>> [Batch] Failed: $video_file"
            batch_status=1
        fi
        index=$((index + 1))
    done

    echo ""
    if [ $batch_status -eq 0 ]; then
        echo -e "${GREEN}✓ Batch inference finished without errors${NC}"
    else
        echo -e "${YELLOW}⚠ Batch inference finished with some failures (see logs above)${NC}"
    fi
    exit $batch_status
fi

if [ -z "$2" ]; then
    OUTPUT_PATH="$INFERENCE_ROOT/inference_output_$(date +%Y%m%d_%H%M%S)_$RANDOM.txt"
else
    OUTPUT_PATH="${2}"
fi

# Verify video file exists
if [ ! -f "$VIDEO_PATH" ]; then
    echo -e "${RED}Error: video file not found: $VIDEO_PATH${NC}"
    exit 1
fi

# Convert to absolute path
VIDEO_PATH=$(realpath "$VIDEO_PATH")

# If OUTPUT_PATH is already absolute, keep it; otherwise store under inference_output
if [[ "$OUTPUT_PATH" = /* ]]; then
    OUTPUT_PATH="$OUTPUT_PATH"
elif [ -f "$OUTPUT_PATH" ]; then
    OUTPUT_PATH=$(realpath "$OUTPUT_PATH")
else
    OUTPUT_PATH="${INFERENCE_ROOT}/${OUTPUT_PATH}"
fi
OUTPUT_CLEAN_PATH="${OUTPUT_PATH}.clean"

echo -e "${BLUE}[Configuration]${NC}"
echo "  Input video: $VIDEO_PATH"
echo "  Output file: $OUTPUT_PATH"
echo "  SMKD model: $SMKD_MODEL"
echo "  SLTUNET: $SLTUNET_CHECKPOINT"
echo ""

# Locate conda base
CONDA_BASE=$(conda info --base 2>/dev/null || echo "")

if [ -z "$CONDA_BASE" ]; then
    echo -e "${RED}Error: could not find conda${NC}"
    echo "Please make sure conda is installed."
    exit 1
fi

# Enable conda activation
source "${CONDA_BASE}/etc/profile.d/conda.sh"

# Temporary directory
TEMP_DIR=$(mktemp -d)
# Do not auto-delete on exit—we need the detailed attention results later

echo -e "${BLUE}[1/2] Extracting video features with SMKD...${NC}"
echo "  Environment: signx-slt (PyTorch)"
echo ""

# Activate PyTorch environment
conda activate signx-slt

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: failed to activate signx-slt environment${NC}"
    exit 1
fi

# Create temporary video list file (required by InferFeeder)
VIDEO_LIST_FILE="$TEMP_DIR/video_list.txt"
echo "$VIDEO_PATH" > "$VIDEO_LIST_FILE"

echo "  ✓ Temporary video list created: $VIDEO_LIST_FILE"

# Run SignEmbedding to extract features
cd "$SCRIPT_DIR"

FEATURE_OUTPUT="$TEMP_DIR/features.h5"

python -c "
import sys
import os
sys.path.insert(0, 'smkd')

from smkd.sign_embedder import SignEmbedding
import h5py
import numpy as np

print('  Loading SMKD model...')
embedder = SignEmbedding(
    cfg='$SMKD_CONFIG',
    gloss_path='$GLOSS_DICT',
    sign_video_path='$VIDEO_LIST_FILE',
    model_path='$SMKD_MODEL',
    gpu_id='0',
    batch_size=1
)

print('  Extracting features...')
features = embedder.embed()

print('  Saving features to h5 file...')
with h5py.File('$FEATURE_OUTPUT', 'w') as hf:
    for key, feature in features.items():
        hf.create_dataset(key, data=feature)

print('  ✓ Feature extraction complete:', '$FEATURE_OUTPUT')
print('  Number of feature sequences:', len(features))

# Create source/target placeholder files for SLTUNET dataset
# Format: <image_index> <text>
# Use placeholder tokens because the gloss is what we want to predict
with open('$TEMP_DIR/src.txt', 'w') as f:
    for key in sorted(features.keys(), key=lambda x: int(x)):
        f.write(key + ' <unk>\\n')  # placeholder text

with open('$TEMP_DIR/tgt.txt', 'w') as f:
    for key in sorted(features.keys(), key=lambda x: int(x)):
        f.write('<unk>\\n')

print('  ✓ Source/target placeholder files ready')
"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: SMKD feature extraction failed${NC}"
    exit 1
fi

echo ""
echo -e "${GREEN}✓ Stage 1 complete: features extracted${NC}"
echo ""

# Switch to TensorFlow environment
echo -e "${BLUE}[2/2] Generating gloss sequence with SLTUNET...${NC}"
echo "  Environment: slt_tf1 (TensorFlow)"
echo ""

conda activate slt_tf1

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: failed to activate slt_tf1 environment${NC}"
    exit 1
fi

export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python

# Determine output directory (for attention artifacts)
OUTPUT_DIR=$(dirname "$OUTPUT_PATH")
PREDICTION_TXT="$TEMP_DIR/prediction.txt"

# Build temporary inference config
cat > "$TEMP_DIR/infer_config.py" <<EOF
{
    'sign_cfg': '$SMKD_CONFIG',
    'gloss_path': '$GLOSS_DICT',
    'smkd_model_path': '$SMKD_MODEL',
    'img_test_file': '$FEATURE_OUTPUT',
    'src_test_file': '$TEMP_DIR/src.txt',
    'tgt_test_file': '$TEMP_DIR/tgt.txt',
    'src_vocab_file': '$VOCAB_FILE',
    'tgt_vocab_file': '$VOCAB_FILE',
    'src_codes': '$BPE_CODES',
    'tgt_codes': '$BPE_CODES',
    'output_dir': '$SLTUNET_CHECKPOINT',
    'test_output': '$PREDICTION_TXT',
    'eval_batch_size': 1,
    'gpus': [0],
    'remove_bpe': True,
    'collect_attention_weights': True,
    'inference_video_path': '$VIDEO_PATH',
}
EOF

echo "  Loading SLTUNET model..."
echo "  Running translation..."
echo ""

cd "$SCRIPT_DIR"

# Run inference and capture logs for later inspection
python run.py \
    --mode test \
    --config "$TEMP_DIR/infer_config.py" \
    2>&1 | tee "$TEMP_DIR/full_output.log" | grep -E "(Loading|Evaluating|BLEU|Scores|Saving detailed|Error)" || true

if [ -f "$TEMP_DIR/prediction.txt" ]; then
    echo ""
    echo -e "${GREEN}✓ Inference complete: gloss sequence generated${NC}"
    echo ""

    # Copy raw result
    cp "$TEMP_DIR/prediction.txt" "$OUTPUT_PATH"

    # Remove BPE markers (@@) for a clean text version
    sed 's/@@ //g' "$OUTPUT_PATH" > "$OUTPUT_CLEAN_PATH"

    # Move detailed attention analysis output if present
    DETAILED_DIRS=$(find "$TEMP_DIR" -maxdepth 1 -type d -name "detailed_*" 2>/dev/null)
    ATTENTION_ANALYSIS_DIR=""

    if [ ! -z "$DETAILED_DIRS" ]; then
        echo -e "${BLUE}Detected detailed attention analysis, saving...${NC}"
        for detailed_dir in $DETAILED_DIRS; do
            dir_name=$(basename "$detailed_dir")
            dest_path="$INFERENCE_ROOT/$dir_name"
            mv "$detailed_dir" "$dest_path"
            ATTENTION_ANALYSIS_DIR="$dest_path"

            # Count sample directories
            mapfile -t SAMPLE_DIRS < <(find "$dest_path" -mindepth 1 -maxdepth 1 -type d -print | sort)
            sample_count=${#SAMPLE_DIRS[@]}
            echo "  ✓ Saved $sample_count sample analyses to: $dest_path"

            # Step 1: feature-to-frame mapping
            echo ""
            echo -e "${BLUE}Generating feature-to-frame mapping...${NC}"
            if [ -f "$SCRIPT_DIR/eval/generate_feature_mapping.py" ]; then
                # Switch to signx-slt environment (CV2 available)
                conda activate signx-slt
                if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
                    echo "  ⚠ No sample directories found, skipping mapping"
                else
                    for sample_dir in "${SAMPLE_DIRS[@]}"; do
                        if [ -d "$sample_dir" ]; then
                            python "$SCRIPT_DIR/eval/generate_feature_mapping.py" "$sample_dir" "$VIDEO_PATH" 2>&1 | grep -E "(feature|frame|mapping|error)"
                        fi
                    done
                fi
            else
                echo "  ⓘ generate_feature_mapping.py not found, skipping mapping"
            fi

            # Step 2: regenerate visualizations
            echo ""
            echo -e "${BLUE}Regenerating visualizations (latest code)...${NC}"
            if [ -f "$SCRIPT_DIR/eval/regenerate_visualizations.py" ]; then
                if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
                    echo "  ⚠ No sample directories found, skipping visualization"
                else
                    python "$SCRIPT_DIR/eval/regenerate_visualizations.py" "$dest_path" "$VIDEO_PATH"
                fi
            else
                echo "  ⓘ regenerate_visualizations.py not found, falling back to legacy scripts"
                if [ -f "$SCRIPT_DIR/eval/generate_gloss_frames.py" ]; then
                    python "$SCRIPT_DIR/eval/generate_gloss_frames.py" "$dest_path" "$VIDEO_PATH"
                fi
            fi

            # Step 3: interactive HTML visualization
            echo ""
            echo -e "${BLUE}Creating interactive HTML visualization...${NC}"
            if [ -f "$SCRIPT_DIR/eval/generate_interactive_alignment.py" ]; then
                if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
                    echo "  ⚠ No sample directories found, skipping HTML generation"
                else
                    for sample_dir in "${SAMPLE_DIRS[@]}"; do
                        if [ -d "$sample_dir" ]; then
                            python "$SCRIPT_DIR/eval/generate_interactive_alignment.py" "$sample_dir"
                        fi
                    done
                fi
            else
                echo "  ⓘ generate_interactive_alignment.py not found, skipping HTML generation"
            fi

            # Step 4: extract attention keyframes
            echo ""
            echo -e "${BLUE}Extracting attention keyframes...${NC}"
            if [ -f "$SCRIPT_DIR/eval/extract_attention_keyframes.py" ]; then
                if [ ${#SAMPLE_DIRS[@]} -eq 0 ]; then
                    echo "  ⚠ No sample directories found, skipping keyframes"
                else
                    for sample_dir in "${SAMPLE_DIRS[@]}"; do
                        if [ -d "$sample_dir" ]; then
                            echo "  Processing sample: $(basename "$sample_dir")"
                            python "$SCRIPT_DIR/eval/extract_attention_keyframes.py" "$sample_dir" "$VIDEO_PATH"
                        fi
                    done
                fi
            else
                echo "  ⓘ extract_attention_keyframes.py not found, skipping keyframes"
            fi

            # Switch back to slt_tf1 environment
            conda activate slt_tf1
        done
    fi

    # Move final output into the primary sample directory for convenience
    if [ ! -z "$ATTENTION_ANALYSIS_DIR" ] && [ -d "$ATTENTION_ANALYSIS_DIR" ]; then
        PRIMARY_SAMPLE_DIR=$(find "$ATTENTION_ANALYSIS_DIR" -mindepth 1 -maxdepth 1 -type d | sort | head -n 1)
        if [ ! -z "$PRIMARY_SAMPLE_DIR" ] && [ -d "$PRIMARY_SAMPLE_DIR" ]; then
            TRANSLATION_FILE="${PRIMARY_SAMPLE_DIR}/translation.txt"

            # Keep a copy for debugging inside the sample directory
            MOVED_BPE_FILE=""
            MOVED_CLEAN_FILE=""
            if [ -f "$OUTPUT_PATH" ]; then
                NEW_OUTPUT_PATH="${PRIMARY_SAMPLE_DIR}/$(basename "$OUTPUT_PATH")"
                mv "$OUTPUT_PATH" "$NEW_OUTPUT_PATH"
                MOVED_BPE_FILE="$NEW_OUTPUT_PATH"
            fi

            if [ -f "$OUTPUT_CLEAN_PATH" ]; then
                CLEAN_BASENAME=$(basename "$OUTPUT_CLEAN_PATH")
                NEW_CLEAN_PATH="${PRIMARY_SAMPLE_DIR}/${CLEAN_BASENAME}"
                mv "$OUTPUT_CLEAN_PATH" "$NEW_CLEAN_PATH"
                MOVED_CLEAN_FILE="$NEW_CLEAN_PATH"
            fi

            # Generate translation.txt if it was not created
            if [ ! -f "$TRANSLATION_FILE" ]; then
                TRANS_BPE=$(head -n 1 "$TEMP_DIR/prediction.txt")
                TRANS_CLEAN=$(sed 's/@@ //g' "$TEMP_DIR/prediction.txt" | head -n 1)
                {
                    echo "With BPE: ${TRANS_BPE}"
                    echo "Clean: ${TRANS_CLEAN}"
                    echo "Ground Truth: [NOT AVAILABLE]"
                } > "$TRANSLATION_FILE"
            fi

            # Remove redundant files now that translation.txt exists
            if [ -n "$MOVED_BPE_FILE" ] && [ -f "$MOVED_BPE_FILE" ] && [ "$MOVED_BPE_FILE" != "$TRANSLATION_FILE" ]; then
                rm -f "$MOVED_BPE_FILE"
            fi
            if [ -n "$MOVED_CLEAN_FILE" ] && [ -f "$MOVED_CLEAN_FILE" ] && [ "$MOVED_CLEAN_FILE" != "$TRANSLATION_FILE" ]; then
                rm -f "$MOVED_CLEAN_FILE"
            fi

            # Preserve a copy of the input video inside the sample directory for reference
            if [ -f "$VIDEO_PATH" ]; then
                VIDEO_BASENAME=$(basename "$VIDEO_PATH")
                DEST_VIDEO_PATH="${PRIMARY_SAMPLE_DIR}/${VIDEO_BASENAME}"
                if [ ! -f "$DEST_VIDEO_PATH" ]; then
                    cp "$VIDEO_PATH" "$DEST_VIDEO_PATH"
                fi
            fi

            OUTPUT_PATH="$TRANSLATION_FILE"
            OUTPUT_CLEAN_PATH="$TRANSLATION_FILE"
        fi
    fi

    echo ""
    echo "======================================================================"
    echo "  Inference succeeded!"
    echo "======================================================================"
    echo ""
    echo "Output files:"
    echo "  Raw (with BPE): $OUTPUT_PATH"
    echo "  Cleaned result: $OUTPUT_CLEAN_PATH"

    if [ ! -z "$ATTENTION_ANALYSIS_DIR" ]; then
        echo "  Detailed analysis dir: $ATTENTION_ANALYSIS_DIR"
        echo ""
        echo "Attention assets include:"
        echo "  - attention_heatmap.png"
        echo "  - word_frame_alignment.png"
        echo "  - gloss_to_frames.png"
        echo "  - analysis_report.txt"
        echo "  - attention_weights.npy"
        echo "  - attention_keyframes/ (per-gloss keyframe previews)"
        echo "    * peak feature frames per gloss"
        echo "    * heatmaps overlayed on the video frames"
    fi

    echo ""
    echo "Recognition result (BPE removed):"
    echo "----------------------------------------------------------------------"
    head -5 "$OUTPUT_CLEAN_PATH" | sed 's/^/  /'
    echo "----------------------------------------------------------------------"
    echo ""
    echo -e "${GREEN}✓ Full pipeline completed (SMKD → SLTUNET)${NC}"
    echo ""

    # Clean temp directory
    echo -e "${BLUE}Cleaning temporary files...${NC}"
    rm -rf "$TEMP_DIR"
    echo "  ✓ Temporary files removed"
    echo ""
else
    echo -e "${RED}Error: inference failed, no output generated${NC}"
    rm -rf "$TEMP_DIR"
    exit 1
fi