File size: 24,611 Bytes
29c2c7a
 
ac71c07
 
29c2c7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
 
 
 
29c2c7a
 
 
 
 
 
 
 
 
 
 
ac71c07
29c2c7a
 
ac71c07
 
29c2c7a
 
ac71c07
29c2c7a
 
 
ac71c07
 
 
29c2c7a
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
 
 
ac71c07
 
29c2c7a
ac71c07
29c2c7a
 
ac71c07
 
29c2c7a
 
 
ac71c07
29c2c7a
ac71c07
29c2c7a
 
 
 
 
ac71c07
29c2c7a
 
 
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
 
 
ac71c07
29c2c7a
 
ac71c07
 
29c2c7a
ac71c07
29c2c7a
 
 
 
 
 
ac71c07
29c2c7a
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
 
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
 
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
29c2c7a
ac71c07
29c2c7a
 
 
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
 
 
 
 
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
 
 
 
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
ac71c07
29c2c7a
 
 
 
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
29c2c7a
 
 
 
ac71c07
29c2c7a
 
ac71c07
 
 
 
 
 
 
 
29c2c7a
 
 
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
 
 
ac71c07
29c2c7a
 
 
 
 
ac71c07
29c2c7a
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
 
 
ac71c07
 
 
29c2c7a
 
 
 
 
 
 
ac71c07
 
 
29c2c7a
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
 
 
 
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
 
 
 
 
 
 
ac71c07
29c2c7a
 
 
 
ac71c07
29c2c7a
 
 
 
 
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
 
 
 
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
 
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
ac71c07
29c2c7a
 
 
 
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
ac71c07
29c2c7a
 
ac71c07
29c2c7a
ac71c07
29c2c7a
ac71c07
 
 
 
29c2c7a
 
 
 
ac71c07
29c2c7a
 
 
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
ac71c07
29c2c7a
ac71c07
29c2c7a
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
ac71c07
29c2c7a
 
 
 
ac71c07
 
 
 
 
29c2c7a
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
ac71c07
29c2c7a
 
 
 
 
ac71c07
 
29c2c7a
 
 
 
 
 
 
 
 
ac71c07
29c2c7a
ac71c07
 
29c2c7a
ac71c07
29c2c7a
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
ac71c07
29c2c7a
ac71c07
 
 
 
 
 
29c2c7a
ac71c07
 
 
 
29c2c7a
 
 
 
ac71c07
29c2c7a
ac71c07
29c2c7a
ac71c07
29c2c7a
ac71c07
29c2c7a
ac71c07
29c2c7a
ac71c07
29c2c7a
ac71c07
29c2c7a
 
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
ac71c07
29c2c7a
 
 
 
 
 
 
 
 
ac71c07
29c2c7a
ac71c07
29c2c7a
 
 
 
 
 
 
ac71c07
 
29c2c7a
 
 
ac71c07
29c2c7a
ac71c07
29c2c7a
 
 
 
 
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
#!/usr/bin/env python3
"""

Sign Language Gloss Q&A System

User inputs gloss, system generates corresponding pose video

"""

import torch
from PIL import Image
import numpy as np
import json
import os
import sys
import argparse
from pathlib import Path
import cv2
from tqdm import tqdm
import re

from easy_dwpose import DWposeDetector
from easy_dwpose.draw.controlnext import draw_pose, process_pose_data

# Fixed configuration
DATABASE_PATH = "output/merge/merged_database.npz"  # Database file path
MAPPING_FILE = "output/gloss_mapping.json"  # Mapping file path
OUTPUT_DIR = "output/video"  # Output video directory


class SignLanguageQA:
    def __init__(self):
        self.data = None
        self.metadata = None
        self.gloss_mapping = None
        self.load_database()
        self.load_mapping()

    def load_database(self):
        """Load database"""
        try:
            if not Path(DATABASE_PATH).exists():
                print(f"❌ Database file does not exist: {DATABASE_PATH}")
                print("   Please ensure merge_all_to_database.py has been run to generate database file")
                sys.exit(1)

            print(f"📚 Loading database: {DATABASE_PATH}")
            self.data = np.load(DATABASE_PATH, allow_pickle=True)
            self.metadata = self.data['_metadata'].item()

            print(f"✅ Database loaded successfully!")
            print(f"   📊 Total frames: {self.metadata['total_frames']}")
            print(f"   🎬 Video count: {self.metadata['video_count']}")

        except Exception as e:
            print(f"❌ Database loading failed: {e}")
            sys.exit(1)

    def load_mapping(self):
        """Load gloss mapping file"""
        if Path(MAPPING_FILE).exists():
            try:
                with open(MAPPING_FILE, 'r', encoding='utf-8') as f:
                    self.gloss_mapping = json.load(f)
                print(f"✅ Mapping file loaded successfully: {MAPPING_FILE}")
                print(f"   📝 Contains {len(self.gloss_mapping)} gloss mappings")
            except Exception as e:
                print(f"⚠️  Mapping file loading failed: {e}")
                self.gloss_mapping = None
        else:
            print(f"ℹ️  Mapping file does not exist: {MAPPING_FILE}")
            print("   Will use intelligent matching mode")
            self.gloss_mapping = None

    def find_gloss_videos(self, gloss):
        """Find corresponding video_ids based on a single gloss"""
        if self.gloss_mapping and gloss.upper() in self.gloss_mapping:
            # Use mapping file
            video_ids = self.gloss_mapping[gloss.upper()]
            if not isinstance(video_ids, list):
                video_ids = [video_ids]
            return video_ids
        else:
            # Intelligent matching mode
            gloss_upper = gloss.upper()
            matched_videos = []

            for video_id in self.metadata['video_index'].keys():
                # Multiple matching strategies
                if (gloss_upper == video_id.upper() or
                        gloss_upper in video_id.upper() or
                        video_id.upper().endswith(f"_{gloss_upper}") or
                        video_id.upper().startswith(f"{gloss_upper}_") or
                        f"_{gloss_upper}_" in video_id.upper()):
                    matched_videos.append(video_id)

            return matched_videos

    def get_frames_for_glosses(self, gloss_list, one_video_per_gloss=True):
        """Get all frames corresponding to gloss list



        Args:

            gloss_list: gloss list

            one_video_per_gloss: whether to select only one video per gloss

        """
        all_frame_groups = []  # Frames grouped by gloss
        video_info = []

        for gloss in gloss_list:
            matched_videos = self.find_gloss_videos(gloss)

            if matched_videos:
                print(f"🎯 '{gloss}' -> Found {len(matched_videos)} videos")

                # If selecting only one video, find the first valid one (existing in database)
                videos_to_use = []
                if one_video_per_gloss:
                    # Find the first video that exists in the database
                    for video_id in matched_videos:
                        if video_id in self.metadata['video_index']:
                            videos_to_use = [video_id]
                            if len(matched_videos) > 1:
                                print(f"   💡 Selecting first valid video: {video_id}, skipping other {len(matched_videos) - 1}")
                            break

                    if not videos_to_use:
                        print(f"   ❌ No valid videos found (all video_ids not in database)")
                        continue
                else:
                    videos_to_use = matched_videos

                gloss_frames = []  # All frames for current gloss
                for video_id in videos_to_use:
                    if video_id in self.metadata['video_index']:
                        start_frame = self.metadata['video_index'][video_id]['start_frame']
                        end_frame = self.metadata['video_index'][video_id]['end_frame']
                        frames = list(range(start_frame, end_frame + 1))
                        gloss_frames.extend(frames)
                        video_info.append({
                            'gloss': gloss,
                            'video_id': video_id,
                            'start_frame': start_frame,
                            'end_frame': end_frame,
                            'frame_count': len(frames)
                        })
                        print(f"   📹 {video_id}: {len(frames)} frames ({start_frame}-{end_frame})")
                    else:
                        print(f"   ⚠️  {video_id}: Not found in database")

                if gloss_frames:
                    all_frame_groups.append(gloss_frames)
            else:
                print(f"❌ '{gloss}' -> No matching videos found")
                self.suggest_similar_glosses(gloss)

        # Concatenate frames from all glosses in order
        all_frames = []
        for frame_group in all_frame_groups:
            all_frames.extend(frame_group)

        return all_frames, video_info

    def suggest_similar_glosses(self, gloss):
        """Provide similar suggestions for unfound gloss"""
        gloss_upper = gloss.upper()
        similar_videos = []

        # Find video_id containing partial characters
        for video_id in self.metadata['video_index'].keys():
            score = 0
            for char in gloss_upper:
                if char in video_id.upper():
                    score += 1

            if score >= len(gloss_upper) * 0.5:  # At least 50% character match
                similar_videos.append(video_id)

        if similar_videos:
            print(f"   💡 Similar video_ids: {similar_videos[:5]}")

        # If mapping file exists, show available glosses
        if self.gloss_mapping:
            available_glosses = list(self.gloss_mapping.keys())
            similar_glosses = [g for g in available_glosses if
                               any(char in g for char in gloss_upper)]
            if similar_glosses:
                print(f"   💡 Similar glosses: {similar_glosses[:5]}")

    def create_pose_frame(self, frame_data, width=480, height=480):
        """Create single frame pose image"""
        try:
            processed_pred = process_pose_data(frame_data, height, width)

            vis_img = draw_pose(
                pose=processed_pred,
                H=height,
                W=width,
                include_body=True,
                include_hand=True,
                include_face=True
            )

            return vis_img.transpose(1, 2, 0)

        except Exception as e:
            print(f"⚠️  Failed to create pose frame: {e}")
            return None

    def generate_video(self, frame_indices, output_path, video_info, fps=30, width=480, height=480,

                       smoothing_frames=5, smoothing_method='none'):
        """Generate pose video



        Args:

            frame_indices: frame index list

            output_path: output path

            video_info: video info list

            fps: frame rate

            width: width

            height: height

            smoothing_frames: number of smoothing transition frames

            smoothing_method: smoothing method ('fade', 'blend', 'pause', 'none')

        """
        if not frame_indices:
            return False

        # Create output directory
        output_path.parent.mkdir(parents=True, exist_ok=True)

        # Set video encoder
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        video_writer = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))

        if not video_writer.isOpened():
            print("❌ Unable to create video file")
            return False

        original_keys = self.metadata['original_keys']
        successful_frames = 0

        print(f"🎬 Generating video (smoothing method: {smoothing_method})...")

        # Generate pose frames grouped by gloss
        all_pose_frame_groups = []

        print("🔄 Rendering pose frames...")
        current_frame_idx = 0

        for info in video_info:
            gloss_frames = []
            frame_count = info['frame_count']

            for _ in range(frame_count):
                if current_frame_idx < len(frame_indices):
                    frame_idx = frame_indices[current_frame_idx]
                    frame_key = f"frame_{frame_idx:08d}"
                    frame_data = {}

                    for key in original_keys:
                        combined_key = f"{frame_key}_{key}"
                        if combined_key in self.data:
                            frame_data[key] = self.data[combined_key]

                    if frame_data:
                        pose_frame = self.create_pose_frame(frame_data, width, height)
                        if pose_frame is not None:
                            gloss_frames.append(pose_frame)

                    current_frame_idx += 1

            if gloss_frames:
                all_pose_frame_groups.append(gloss_frames)
                print(f"   ✅ {info['gloss']}: {len(gloss_frames)} frames")

        if not all_pose_frame_groups:
            print("❌ No frames generated successfully")
            video_writer.release()
            return False

        # Apply smoothing
        if smoothing_method != 'none' and len(all_pose_frame_groups) > 1:
            final_frames = self.apply_group_smoothing(all_pose_frame_groups, smoothing_frames, smoothing_method)
        else:
            # Directly concatenate all frames
            final_frames = []
            for group in all_pose_frame_groups:
                final_frames.extend(group)

        # Write video
        print("💾 Writing video file...")
        for pose_frame in tqdm(final_frames, desc="Writing frames"):
            pose_frame_bgr = cv2.cvtColor(pose_frame, cv2.COLOR_RGB2BGR)
            video_writer.write(pose_frame_bgr)
            successful_frames += 1

        video_writer.release()

        if successful_frames > 0:
            print(f"✅ Video generated successfully!")
            print(f"   📁 File: {output_path}")
            print(f"   📊 {successful_frames} frames, {fps}fps, {width}x{height}")
            if output_path.exists():
                print(f"   💾 Size: {output_path.stat().st_size / 1024 / 1024:.2f} MB")
            return True
        else:
            print(f"❌ Video generation failed")
            return False

    def apply_group_smoothing(self, frame_groups, smoothing_frames, method):
        """Apply smoothing transition effects to gloss groups"""
        if len(frame_groups) <= 1 or smoothing_frames <= 0:
            final_frames = []
            for group in frame_groups:
                final_frames.extend(group)
            return final_frames

        print(f"🌊 Applying {method} smoothing transition ({smoothing_frames} frames)...")

        if method == 'fade':
            return self.apply_group_fade_smoothing(frame_groups, smoothing_frames)
        elif method == 'blend':
            return self.apply_group_blend_smoothing(frame_groups, smoothing_frames)
        elif method == 'pause':
            return self.apply_group_pause_smoothing(frame_groups, smoothing_frames)
        else:
            final_frames = []
            for group in frame_groups:
                final_frames.extend(group)
            return final_frames

    def apply_group_fade_smoothing(self, frame_groups, fade_frames):
        """Apply fade in/out smoothing to gloss groups"""
        smoothed_frames = []

        for i, group in enumerate(frame_groups):
            if i == 0:
                # First group: fade in
                for f in range(fade_frames):
                    alpha = f / fade_frames
                    black_frame = np.zeros_like(group[0])
                    faded_frame = (black_frame * (1 - alpha) + group[0] * alpha).astype(np.uint8)
                    smoothed_frames.append(faded_frame)

            # Add all frames from current group
            smoothed_frames.extend(group)

            if i < len(frame_groups) - 1:
                # Inter-group transition: fade from last frame of current group to first frame of next group
                next_group = frame_groups[i + 1]
                current_last = group[-1]
                next_first = next_group[0]

                for f in range(fade_frames):
                    alpha = f / fade_frames
                    blended_frame = (current_last * (1 - alpha) + next_first * alpha).astype(np.uint8)
                    smoothed_frames.append(blended_frame)

        return smoothed_frames

    def apply_group_blend_smoothing(self, frame_groups, blend_frames):
        """Apply blend smoothing to gloss groups"""
        smoothed_frames = []

        for i, group in enumerate(frame_groups):
            smoothed_frames.extend(group)

            if i < len(frame_groups) - 1:
                next_group = frame_groups[i + 1]
                current_last = group[-1]
                next_first = next_group[0]

                # Insert blended frames between two groups
                for f in range(1, blend_frames + 1):
                    alpha = f / (blend_frames + 1)
                    blended_frame = (current_last * (1 - alpha) + next_first * alpha).astype(np.uint8)
                    smoothed_frames.append(blended_frame)

        return smoothed_frames

    def apply_group_pause_smoothing(self, frame_groups, pause_frames):
        """Apply pause smoothing to gloss groups"""
        smoothed_frames = []

        for i, group in enumerate(frame_groups):
            smoothed_frames.extend(group)

            # Add pause frames after each group (repeat last frame)
            if i < len(frame_groups) - 1:
                last_frame = group[-1]
                for _ in range(pause_frames):
                    smoothed_frames.append(last_frame.copy())

        return smoothed_frames

    def show_available_glosses(self, limit=20):
        """Show available glosses or video_ids"""
        if self.gloss_mapping:
            glosses = list(self.gloss_mapping.keys())
            print(f"\n📋 Available Glosses ({len(glosses)}):")
            for i, gloss in enumerate(glosses[:limit]):
                videos = self.gloss_mapping[gloss]
                if isinstance(videos, list):
                    print(f"  {gloss} -> {len(videos)} videos")
                else:
                    print(f"  {gloss} -> {videos}")
            if len(glosses) > limit:
                print(f"  ... and {len(glosses) - limit} more")
        else:
            video_ids = list(self.metadata['video_index'].keys())
            print(f"\n📋 Available Video IDs ({len(video_ids)}):")
            for i, vid in enumerate(video_ids[:limit]):
                frame_count = (self.metadata['video_index'][vid]['end_frame'] -
                               self.metadata['video_index'][vid]['start_frame'] + 1)
                print(f"  {vid} ({frame_count} frames)")
            if len(video_ids) > limit:
                print(f"  ... and {len(video_ids) - limit} more")

    def run_qa_system(self):
        """Run QA system"""
        print("\n" + "=" * 60)
        print("🤖 Sign Language Gloss Q&A System")
        print("=" * 60)
        print("💬 Enter gloss to convert, separate multiple words with spaces")
        print("📋 Enter 'list' to view available glosses/videos")
        print("🔧 Enter 'help' to view help")
        print("👋 Enter 'quit' to exit system")
        print("=" * 60)

        while True:
            try:
                user_input = input("\n🤖 Please enter gloss: ").strip()

                if not user_input:
                    continue
                elif user_input.lower() == 'quit':
                    print("👋 Thank you for using!")
                    break
                elif user_input.lower() == 'list':
                    self.show_available_glosses()
                    continue
                elif user_input.lower() == 'help':
                    self.show_help()
                    continue

                # Parse input gloss
                gloss_list = user_input.upper().split()
                print(f"\n🎯 Query: {' + '.join(gloss_list)}")

                # Get corresponding frames (select only one video per gloss)
                frame_indices, video_info = self.get_frames_for_glosses(gloss_list, one_video_per_gloss=True)

                if not frame_indices:
                    print("❌ No matching video frames found")
                    continue

                print(f"\n📊 Total found {len(frame_indices)} frames from {len(video_info)} videos")

                # If multiple videos, ask for smoothing options
                smoothing_method = 'none'
                smoothing_frames = 0

                if len(video_info) > 1:
                    print(f"\n🌊 Multiple video segments detected, choose smoothing transition method:")
                    print(f"   1. none - No smoothing (direct concatenation)")
                    print(f"   2. fade - Fade in/out transition")
                    print(f"   3. blend - Frame blending transition")
                    print(f"   4. pause - Add pause interval")

                    smooth_choice = input(f"Choose smoothing method [1-4, default 1]: ").strip()

                    if smooth_choice == '2':
                        smoothing_method = 'fade'
                        smoothing_frames = int(input("Fade in/out frames [default 5]: ").strip() or "5")
                    elif smooth_choice == '3':
                        smoothing_method = 'blend'
                        smoothing_frames = int(input("Blend frames [default 3]: ").strip() or "3")
                    elif smooth_choice == '4':
                        smoothing_method = 'pause'
                        smoothing_frames = int(input("Pause frames [default 10]: ").strip() or "10")

                # Generate output filename
                gloss_str = "_".join(gloss_list)
                timestamp = __import__('datetime').datetime.now().strftime("%Y%m%d_%H%M%S")
                suffix = f"_{smoothing_method}" if smoothing_method != 'none' else ""
                output_file = Path(OUTPUT_DIR) / f"{gloss_str}_{timestamp}{suffix}.mp4"

                # Ask user whether to generate video
                confirm = input(f"\n❓ Generate video to {output_file}? [y/n]: ").strip().lower()

                if confirm in ['y', 'yes', '']:
                    success = self.generate_video(
                        frame_indices, output_file, video_info,
                        smoothing_frames=smoothing_frames,
                        smoothing_method=smoothing_method
                    )

                    if success:
                        print(f"\n🎉 Video generated: {output_file}")

                        # Show video details
                        print(f"\n📈 Video details:")
                        for info in video_info:
                            print(f"   {info['gloss']}: {info['video_id']} ({info['frame_count']} frames)")
                else:
                    print("⏭️  Skipping video generation")

            except KeyboardInterrupt:
                print("\n\n👋 System exited")
                break
            except Exception as e:
                print(f"❌ Error occurred: {e}")

    def show_help(self):
        """Show help information"""
        print("\n" + "=" * 50)
        print("📖 Help Information")
        print("=" * 50)
        print("🔹 Enter single gloss: HELLO")
        print("🔹 Enter multiple glosses: HELLO WORLD GOODBYE")
        print("🔹 View available content: list")
        print("🔹 System will automatically match corresponding sign language videos")
        print(f"🔹 Generated videos are saved in {OUTPUT_DIR}/ directory")
        print("🔹 Supported mapping file format (gloss_mapping.json):")
        print('   {"HELLO": ["video1", "video2"], "WORLD": "video3"}')
        print("🔹 Smoothing transition options:")
        print("   - fade: Fade in/out transition")
        print("   - blend: Frame blending transition")
        print("   - pause: Add pause interval")
        print("=" * 50)


def main():
    parser = argparse.ArgumentParser(description='Sign Language Gloss Q&A System')
    parser.add_argument('--gloss', '-g',
                        help='Directly input gloss to generate video, separated by spaces')
    parser.add_argument('--fps', type=int, default=30,
                        help='Video frame rate (default: 30)')
    parser.add_argument('--width', type=int, default=480,
                        help='Video width (default: 480)')
    parser.add_argument('--height', type=int, default=480,
                        help='Video height (default: 480)')
    parser.add_argument('--smoothing', choices=['none', 'fade', 'blend', 'pause'],
                        default='none', help='Smoothing transition method (default: none)')
    parser.add_argument('--smoothing-frames', type=int, default=5,
                        help='Smoothing transition frames (default: 5)')

    args = parser.parse_args()

    # Initialize QA system
    qa_system = SignLanguageQA()

    # If gloss parameter is provided, process directly
    if args.gloss:
        gloss_list = args.gloss.upper().split()
        print(f"🎯 Processing gloss: {' + '.join(gloss_list)}")

        frame_indices, video_info = qa_system.get_frames_for_glosses(gloss_list, one_video_per_gloss=True)

        if frame_indices:
            gloss_str = "_".join(gloss_list)
            timestamp = __import__('datetime').datetime.now().strftime("%Y%m%d_%H%M%S")
            suffix = f"_{args.smoothing}" if args.smoothing != 'none' else ""
            output_file = Path(OUTPUT_DIR) / f"{gloss_str}_{timestamp}{suffix}.mp4"

            print(f"📊 Found {len(frame_indices)} frames from {len(video_info)} videos")
            if args.smoothing != 'none':
                print(f"🌊 Using {args.smoothing} smoothing transition ({args.smoothing_frames} frames)")

            success = qa_system.generate_video(
                frame_indices, output_file, video_info, args.fps, args.width, args.height,
                args.smoothing_frames, args.smoothing
            )

            if success:
                print(f"🎉 Video generated: {output_file}")
                print(f"\n📈 Video details:")
                for info in video_info:
                    print(f"   {info['gloss']}: {info['video_id']} ({info['frame_count']} 帧)")
        else:
            print("❌ No matching videos found")
    else:
        # Start interactive QA system
        qa_system.run_qa_system()


if __name__ == "__main__":
    main()