FangSen9000
Attempted to submit 4 changes, although the reasoning degraded, the reasoning could still run.
1eb306c
| #!/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() | |