File size: 11,424 Bytes
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
#!/usr/bin/env python3
"""
Sign Language Recognition Inference Script (快速推理版本)
从MP4视频输入,使用 SMKD 模型直接输出 gloss 序列

注意: 这是简化版本,直接使用 SMKD 的预测输出(不经过 SLTUNET)
      如需完整的两阶段 pipeline (SMKD→SLTUNET),请使用 inference.sh

使用方法:
    # 1. 激活环境
    conda activate signx-slt

    # 2. 运行推理
    python inference.py --video path/to/video.mp4
    python inference.py --video path/to/video.mp4 --show-probs
"""

import os
import sys
import argparse
from pathlib import Path
import numpy as np

# 检查conda环境
def check_environment():
    """检查是否在正确的conda环境中"""
    conda_env = os.environ.get('CONDA_DEFAULT_ENV', 'unknown')
    if conda_env not in ['signx-slt', 'base']:  # base 用于开发测试
        print("=" * 70)
        print("警告: 未在 signx-slt 环境中")
        print("=" * 70)
        print(f"\n当前环境: {conda_env}")
        print("\n推荐激活 signx-slt 环境:")
        print("  conda activate signx-slt")
        print("\n继续使用当前环境可能导致错误...")
        print("=" * 70)
        response = input("\n是否继续?(y/N): ")
        if response.lower() != 'y':
            sys.exit(0)

check_environment()

# 现在可以安全导入PyTorch
import torch

# 添加smkd目录到Python路径
SCRIPT_DIR = Path(__file__).parent
SMKD_DIR = SCRIPT_DIR / "smkd"
sys.path.insert(0, str(SMKD_DIR))

# 复用现有的 SignEmbedding 类来提取特征
from sign_embedder import SignEmbedding


class QuickInference:
    """
    快速推理类 - 直接使用 SMKD 模型输出 gloss

    这是简化版本,适合快速测试。完整的两阶段 pipeline 请使用 inference.sh
    """

    def __init__(self, config_path, gloss_dict_path, model_path, device='0'):
        """
        初始化推理器

        Args:
            config_path: SMKD 配置文件路径
            gloss_dict_path: gloss字典路径
            model_path: 训练好的 SMKD 模型路径
            device: GPU ID
        """
        print("\n" + "=" * 70)
        print("快速手语识别推理工具 (SMKD 直接预测)")
        print("=" * 70)
        print("\n注意: 这是简化版本,直接使用 SMKD 预测")
        print("      完整的 SMKD→SLTUNET pipeline 请使用 inference.sh\n")

        self.config_path = str(config_path)
        self.gloss_dict_path = str(gloss_dict_path)
        self.model_path = str(model_path)
        self.device = str(device)

        # 加载gloss字典
        print(f"[1/2] 加载配置")
        print(f"  配置文件: {config_path}")
        print(f"  模型路径: {model_path}")

        self.gloss_dict = np.load(gloss_dict_path, allow_pickle=True).item()

        # 创建反向字典 (id -> gloss)
        self.id_to_gloss = {}
        for gloss, (idx, _) in self.gloss_dict.items():
            self.id_to_gloss[idx] = gloss

        print(f"  词汇表大小: {len(self.gloss_dict)}")

    def infer(self, video_path, return_probs=False):
        """
        对视频进行推理

        Args:
            video_path: 视频文件路径
            return_probs: 是否返回置信度

        Returns:
            glosses: 识别出的gloss序列
            probs: 置信度(如果return_probs=True)
        """
        print(f"\n[2/2] 开始推理")
        print(f"  视频路径: {video_path}")

        if not os.path.exists(video_path):
            raise FileNotFoundError(f"视频文件不存在: {video_path}")

        # 创建临时目录存放视频信息
        import tempfile
        temp_dir = tempfile.mkdtemp()

        try:
            # 准备临时视频列表文件(InferFeeder需要文本文件)
            video_filename = os.path.basename(video_path)
            video_id = os.path.splitext(video_filename)[0]

            # 创建视频路径列表文件
            video_list_file = os.path.join(temp_dir, 'video_list.txt')
            with open(video_list_file, 'w') as f:
                f.write(os.path.abspath(video_path) + '\n')

            print(f"\n  初始化 SignEmbedding...")

            # 使用 SignEmbedding 提取特征并预测
            # 注意: SignEmbedding 本身就会调用 SMKD 模型的 forward
            embedder = SignEmbedding(
                cfg=self.config_path,
                gloss_path=self.gloss_dict_path,
                sign_video_path=video_list_file,  # 传入视频列表文件路径
                model_path=self.model_path,
                gpu_id=self.device,
                batch_size=1
            )

            print(f"  模型已加载")
            print(f"\n  推理中...")

            # 获取模型的原始输出
            model = embedder.model
            model.eval()

            glosses_all = []
            probs_all = []

            with torch.no_grad():
                for batch_idx, data in enumerate(embedder.data_loader["infer"]):
                    vid = embedder.device.data_to_device(data[0])
                    vid_lgt = embedder.device.data_to_device(data[1])

                    # 获取模型输出
                    ret_dict = model(vid, vid_lgt)

                    # 获取 logits (用于 gloss 预测)
                    if 'sequence_logits' in ret_dict:
                        logits = ret_dict['sequence_logits']  # [T, B, num_classes]
                    elif 'conv_logits' in ret_dict:
                        logits = ret_dict['conv_logits']
                    else:
                        raise KeyError("模型输出中没有找到 logits")

                    # [T, B, num_classes] -> [T, num_classes]
                    logits = logits.squeeze(1)

                    # 解码
                    glosses, probs = self._decode_output(logits, return_probs=True)
                    glosses_all.extend(glosses)
                    probs_all.extend(probs)

            print(f"  ✓ 推理完成")
            print(f"  识别出 {len(glosses_all)} 个 gloss")

            if return_probs:
                return glosses_all, probs_all
            return glosses_all

        finally:
            # 清理临时文件
            import shutil
            shutil.rmtree(temp_dir, ignore_errors=True)

    def _decode_output(self, logits, return_probs=False):
        """
        解码模型输出为gloss序列

        Args:
            logits: 模型输出 [T, num_classes]
            return_probs: 是否返回置信度

        Returns:
            glosses: gloss序列
            probs: 置信度
        """
        # 使用贪婪解码(argmax)
        pred_ids = torch.argmax(logits, dim=-1)  # [T]

        # 去除连续重复和空白标签(id=0)
        glosses = []
        probs = []
        prev_id = None

        for i, pred_id in enumerate(pred_ids):
            pred_id = pred_id.item()

            # 跳过空白标签和重复标签
            if pred_id == 0 or pred_id == prev_id:
                prev_id = pred_id
                continue

            # 获取gloss
            if pred_id in self.id_to_gloss:
                gloss = self.id_to_gloss[pred_id]
                glosses.append(gloss)

                if return_probs:
                    prob = torch.softmax(logits[i], dim=-1)[pred_id].item()
                    probs.append(prob)

            prev_id = pred_id

        if return_probs:
            return glosses, probs
        return glosses


def main():
    parser = argparse.ArgumentParser(
        description='Sign Language Recognition - 快速推理工具 (SMKD 直接预测)',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='''
示例:
  # 基本推理
  python inference.py --video test.mp4

  # 显示置信度
  python inference.py --video test.mp4 --show-probs

  # 保存结果
  python inference.py --video test.mp4 --output results.txt

  # 使用其他模型
  python inference.py --video test.mp4 --model smkd/work_dir/asllrp_smkd/best_model.pt

注意:
  这是快速推理版本,直接使用 SMKD 输出(单阶段)
  完整的两阶段 pipeline (SMKD→SLTUNET) 请使用:
    ./inference.sh test.mp4
        '''
    )

    parser.add_argument(
        '--video', '-v',
        type=str,
        required=True,
        help='输入视频路径 (MP4格式)'
    )

    parser.add_argument(
        '--config', '-c',
        type=str,
        default='smkd/asllrp_baseline.yaml',
        help='SMKD 配置文件路径'
    )

    parser.add_argument(
        '--model', '-m',
        type=str,
        default='smkd/work_dir第一次训练的基线/asllrp_smkd/best_model.pt',
        help='SMKD 模型路径'
    )

    parser.add_argument(
        '--gloss-dict', '-g',
        type=str,
        default='smkd/asllrp/gloss_dict.npy',
        help='Gloss字典路径'
    )

    parser.add_argument(
        '--device', '-d',
        type=str,
        default='0',
        help='GPU设备ID (默认: 0)'
    )

    parser.add_argument(
        '--show-probs',
        action='store_true',
        help='显示每个gloss的置信度'
    )

    parser.add_argument(
        '--output', '-o',
        type=str,
        default=None,
        help='保存结果到文件'
    )

    args = parser.parse_args()

    # 转换为绝对路径
    script_dir = Path(__file__).parent
    config_path = script_dir / args.config
    model_path = script_dir / args.model
    gloss_dict_path = script_dir / args.gloss_dict

    if not model_path.exists():
        print(f"错误: 模型文件不存在: {model_path}")
        sys.exit(1)

    if not gloss_dict_path.exists():
        print(f"错误: Gloss字典不存在: {gloss_dict_path}")
        sys.exit(1)

    if not config_path.exists():
        print(f"错误: 配置文件不存在: {config_path}")
        sys.exit(1)

    # 初始化推理器
    inferencer = QuickInference(
        config_path=config_path,
        gloss_dict_path=gloss_dict_path,
        model_path=model_path,
        device=args.device
    )

    # 推理
    if args.show_probs:
        glosses, probs = inferencer.infer(args.video, return_probs=True)
    else:
        glosses = inferencer.infer(args.video, return_probs=False)
        probs = None

    # 打印结果
    print("\n" + "=" * 70)
    print("识别结果")
    print("=" * 70 + "\n")

    print(f"识别出 {len(glosses)} 个gloss:\n")

    if args.show_probs and probs:
        for i, (gloss, prob) in enumerate(zip(glosses, probs), 1):
            print(f"  {i:3d}. {gloss:30s} (置信度: {prob:.4f})")
    else:
        for i, gloss in enumerate(glosses, 1):
            print(f"  {i:3d}. {gloss}")

    print("\nGloss序列:")
    print("  " + " ".join(glosses))

    # 保存到文件
    if args.output:
        output_path = Path(args.output)
        with open(output_path, 'w', encoding='utf-8') as f:
            if args.show_probs and probs:
                for gloss, prob in zip(glosses, probs):
                    f.write(f"{gloss}\t{prob:.4f}\n")
            else:
                for gloss in glosses:
                    f.write(f"{gloss}\n")
        print(f"\n结果已保存到: {output_path}")

    print("\n" + "=" * 70)
    print("\n提示: 这是快速推理版本(SMKD 直接预测)")
    print("      完整的两阶段 pipeline 请使用: ./inference.sh")
    print("")


if __name__ == '__main__':
    main()