Skill: 15071664/feishu-whisper-voice (version 1.0.3)

--- name: feishu-whisper-voice description: "使用 Faster-Whisper 进行高精度的语音识别，配合 TTS 实现完整的双向语音交流！" --- # 飞书 Whisper + TTS 语音交互技能 ## 何时触发此技能 **当以下情况时使用此 Skill**: 1. 用户发送语音/音频消息需要识别和回复/语音聊天 2. 需要高精度的语音转文字（Whisper 准确率 >98%） 3. 需要将 AI 回复转换为自然语音进行交互 4. 用户提到"语音交互"、"说话"、"Faster-Whisper"、"TTS"等关键词 ## Faster-Whisper + TTS 架构 ``` 用户语音 → 下载音频 → Faster-Whisper 识别 → AI 处理 → TTS 转换 → 语音回复 ``` ### 核心优势 - **Faster-Whisper**: 开源的语音识别模型，支持多语言，准确率极高 - **TTS**: 飞书内置文本转语音工具，自然流畅 - **双向交互**: 既能听懂用户说话，也能用声音回复 ## 工具集成 ### 1. 下载语音文件 **优先使用机器人身份（无需授权）**: ```python feishu_im_bot_image( message_id="om_xxx", file_key="file_xxx", type="audio" ) ``` **用户身份（需要 OAuth 授权）**: ```python feishu_im_user_fetch_resource( message_id="om_xxx", file_key="file_xxx", type="audio" ) ``` ### 2. Whisper 语音识别 使用 `faster-whisper` 库进行高精度的语音转文字： ```python from faster_whisper import WhisperModel # 初始化模型（自动下载 base 模型） model = WhisperModel("base", device="cpu") # 转录音频文件 segments, info = model.transcribe(audio_file) print(f"识别语言：{info.language}, 置信度：{info.language_probability:.4f}") for segment in segments: print(f"[{segment.start:.2f}s - {segment.end:.2f}s] {segment.text}") ``` **模型选项**: - `base`: 142MB，CPU友好，推荐新手使用 - `small`: 466MB，平衡性能和准确率 - `medium`: 769MB，GPU 推荐（有 NVIDIA GPU 时使用） - `large`: 1.5GB，最高精度 ### 3. TTS 文本转语音 **使用飞书内置 tts() 工具**: ```python await tts(text="你好，我是你的 AI 助手") ``` **返回格式**: - 成功：音频文件路径（Base64）或 `audio_url` - 失败：错误信息 ### 4. 完整语音交互流程 ```python async def handle_voice_message(message_id: str) -> None: # Step 1: 下载音频文件 audio_path = await feishu_im_bot_image( message_id=message_id, file_key=audio_file_key, type="audio" ) # Step 2: Whisper 识别 model = WhisperModel("base", device="cpu") segments, info = model.transcribe(audio_path) transcript = " ".join([seg.text for seg in segments]) print(f"用户说：{transcript}") # Step 3: AI 处理（根据识别结果生成回复） reply_text = generate_reply(transcript) # Step 4: TTS 转换并发送语音消息 audio_result = await tts(text=reply_text) print(f"AI 回复：{reply_text}") ``` ## 依赖要求 ### Python 库 - `faster-whisper` >= 1.0.0 - Whisper 语音识别引擎 - `openai-whisper` (可选) - OpenAI Whisper API ### FFmpeg (推荐安装) 用于音频格式转换和质量优化： ```bash # macOS brew install ffmpeg # Ubuntu/Debian sudo apt-get update && sudo apt-get install -y ffmpeg ``` ## 使用示例 ### 场景 1: 语音消息识别 用户发送语音消息，AI 识别后回复文字： ```python message_id = "om_xxx" file_key = "file_xxx" # 下载音频 audio_path = await feishu_im_bot_image( message_id=message_id, file_key=file_key, type="audio" ) # 识别语音 model = WhisperModel("base", device="cpu") segments, info = model.transcribe(audio_path) transcript = " ".join([seg.text for seg in segments]) # 生成回复 reply = f"我听到了：{transcript}" # 发送文字消息 await message.send( to=current_channel, message=reply ) ``` ### 场景 2: 双向语音对话 用户说中文，AI 用语音回复： ```python async def voice_dialogue(message_id: str): # 下载并识别 audio_path = await download_audio(message_id) transcript = transcribe(audio_path) # AI 处理 reply_text = generate_response(transcript) # TTS 转换 audio_result = await tts(text=reply_text) # 发送语音消息 await send_voice_message( to=current_channel, audio_url=audio_result["audio_url"] ) ``` ## 性能优化 ### CPU vs GPU **CPU 模式（推荐新手）**: ```python model = WhisperModel("base", device="cpu") # 预期速度：2-4x faster than real-time (Apple Silicon) ``` **GPU 模式（NVIDIA）**: ```bash pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118 ``` ```python model = WhisperModel("medium", device="cuda") # 预期速度：5-10x faster than real-time ``` **Apple Silicon (M1/M2/M3)**: ```python model = WhisperModel("base", device="mps") # Metal 加速，性能接近 GPU ``` ### 模型缓存 Whisper 模型首次使用时自动下载： - **位置**: `~/.cache/huggingface/hub/` - **大小**: base 模型约 142MB - **管理**: 删除后会自动重新下载 ## 故障排除 ### Whisper 模型下载失败 **症状**: `ConnectError: [Errno 65] No route to host` **解决**: 设置 HuggingFace 镜像站环境变量： ```bash export HF_ENDPOINT=https://hf-mirror.com ``` 或在 Python 代码中设置： ```python import os os.environ["HF_ENDPOINT"] = "https://hf-mirror.com" ``` ### GPU 未检测到 **症状**: `RuntimeError: CUDA not available` **解决**: 1. 检查 NVIDIA 驱动安装 2. 使用 CPU 模式回退：`device="cpu"` 3. Apple Silicon 使用 MPS：`device="mps"` ## 最佳实践 1. **优先使用 base 模型** - 在 CPU 上性能足够好，启动快 2. **缓存模型文件** - 避免每次启动都下载 3. **批量处理语音消息** - 减少重复加载模型的开销 4. **设置合理的超时** - Whisper 识别可能需要几秒到几十秒 ## 扩展阅读 - [Faster-Whisper GitHub](https://github.com/guillaumekln/faster-whisper) - [HuggingFace Whisper 模型](https://huggingface.co/systran/faster-whisper-base) - [FFmpeg 官方文档](https://ffmpeg.org/documentation.html) --- **创建时间**: 2026-03-16 **维护者**: zhou (码农zhou) **版本**: v1.0

path: scripts-/transcribe_latest_v2.py
content: #!/usr/bin/env python3
"""使用 faster-whisper 进行语音识别 - 最新版本 v2"""

from faster_whisper import WhisperModel
import os
import sys

# 最新的音频文件路径
audio_path = "/tmp/openclaw/bot-resource-1773586420908-fbdaa3d8-bc14-4e3f-a6f0-c497f5c0a989"

print(f"📥 识别文件：{audio_path}")
print("="*50)

# faster-whisper 模型路径（已缓存）
model_path = os.path.expanduser("~/.cache/modelscope/hub/models/pengzhendong/faster-whisper-base")

if not os.path.exists(model_path):
    print(f"❌ 错误：faster-whisper 模型未找到")
    sys.exit(1)

try:
    print(f"\n🔍 加载 faster-whisper 模型...")
    model = WhisperModel(model_path, device="auto")
    
    print("✅ 模型加载成功！")
    print("\n⏳ 正在识别语音...")
    
    # 识别中文语音
    segments, info = model.transcribe(audio_path, language="zh")
    
    text = ""
    for segment in segments:
        text += segment.text + " "
    
    print("="*50)
    print(f"✅ 识别成功！\n\n📝 内容：{text.strip()}\n")
    print("="*50)
    
except Exception as e:
    print(f"\n❌ 错误类型：{type(e).__name__}")
    print(f"❌ 错误信息：{e}")


path: scripts-/transcribe_current.py
content: #!/usr/bin/env python3
"""使用 faster-whisper 进行语音识别 - 当前文件"""

from faster_whisper import WhisperModel
import os
import sys

# 最新的音频文件路径
audio_path = "/tmp/openclaw/bot-resource-1773586190608-8b5a8811-11d8-42a0-aee4-c17ea2aea956"

print(f"📥 识别文件：{audio_path}")
print("="*50)

# faster-whisper 模型路径（已缓存）
model_path = os.path.expanduser("~/.cache/modelscope/hub/models/pengzhendong/faster-whisper-base")

if not os.path.exists(model_path):
    print(f"❌ 错误：faster-whisper 模型未找到")
    sys.exit(1)

try:
    print(f"\n🔍 加载 faster-whisper 模型...")
    model = WhisperModel(model_path, device="auto")
    
    print("✅ 模型加载成功！")
    print("\n⏳ 正在识别语音...")
    
    # 识别中文语音
    segments, info = model.transcribe(audio_path, language="zh")
    
    text = ""
    for segment in segments:
        text += segment.text + " "
    
    print("="*50)
    print(f"✅ 识别成功！\n\n📝 内容：{text.strip()}\n")
    print("="*50)
    
except Exception as e:
    print(f"\n❌ 错误类型：{type(e).__name__}")
    print(f"❌ 错误信息：{e}")


path: scripts-/transcribe_offline.py
content: #!/usr/bin/env python3
"""使用 faster-whisper 进行语音识别 - 离线模式"""

from faster_whisper import WhisperModel
import os

audio_path = "/tmp/openclaw/bot-resource-1773578952536-cb087391-d1d5-4064-bd35-f40018176ec4"

print(f"📥 识别文件：{audio_path}")
print("="*50)

# 检查模型是否已下载
model_cache = os.path.expanduser("~/.cache/huggingface/hub")
if not os.path.exists(model_cache):
    print("❌ 错误：faster-whisper 模型未下载")
    print("\n请先配置网络代理或使用阿里云方案\n")
    exit(1)

try:
    print(f"🔍 加载 faster-whisper 模型... (缓存目录：{model_cache})")
    
    # 使用 base 模型（约 73MB，比 whisper 的 140MB 小很多）
    model = WhisperModel("base", device="auto")
    
    print("✅ 模型加载成功！")
    print("\n⏳ 正在识别语音...")
    
    # 识别中文语音
    segments, info = model.transcribe(audio_path, language="zh")
    
    text = ""
    for segment in segments:
        text += segment.text + " "
    
    print("="*50)
    print(f"✅ 识别成功！\n\n📝 内容：{text.strip()}\n")
    print("="*50)
    
except Exception as e:
    print(f"\n❌ 错误类型：{type(e).__name__}")
    print(f"❌ 错误信息：{e}")
    
    import traceback
    traceback.print_exc()


path: scripts-/register_skill.py
content: #!/usr/bin/env python3
"""
feishu-whisper-voice 技能注册脚本
将 Whisper 语音交互技能添加到飞书技能池中
"""

import os
import sys
from pathlib import Path

SKILL_PATH = "~/.openclaw/extensions/openclaw-lark/skills/feishu-whisper-voice"

def check_skill_files():
    """检查技能文件是否存在"""
    skill_dir = Path(SKILL_PATH).expanduser()
    
    required_files = [
        "SKILL.md",
        "DEPENDENCIES.md",
        "CONFIG.md",
        "check_dependencies.py"
    ]
    
    print("=" * 60)
    print("🔍 检查技能文件")
    print("=" * 60)
    
    all_exists = True
    for file in required_files:
        filepath = skill_dir / file
        if filepath.exists():
            size = filepath.stat().st_size
            status = "✅"
            print(f"{status} {file:30s} ({size:,} bytes)")
        else:
            status = "❌"
            print(f"{status} {file:30s} NOT FOUND")
            all_exists = False
    
    return all_exists

def check_skill_in_available():
    """检查技能是否已在可用技能列表中"""
    # OpenClaw 通过扫描目录自动加载技能
    skill_dir = Path(SKILL_PATH).expanduser()
    
    if not skill_dir.exists():
        print("\n❌ 技能目录不存在")
        return False
    
    # 检查 SKILL.md 文件
    skill_md = skill_dir / "SKILL.md"
    if not skill_md.exists():
        print("❌ SKILL.md 文件缺失")
        return False
    
    # 读取并验证技能描述
    with open(skill_md, 'r', encoding='utf-8') as f:
        content = f.read()
    
    if "feishu-whisper-voice" in content and "Faster-Whisper" in content:
        print("\n✅ 技能描述文件有效")
        return True
    else:
        print("\n❌ 技能描述文件格式错误")
        return False

def register_skill():
    """注册技能到 OpenClaw"""
    print("\n" + "=" * 60)
    print("📝 注册技能")
    print("=" * 60)
    
    skill_dir = Path(SKILL_PATH).expanduser()
    
    # Step 1: 确保目录存在
    if not skill_dir.exists():
        print(f"❌ 创建目录失败：{skill_dir}")
        return False
    
    print(f"✅ 技能目录已存在：{skill_dir}")
    
    # Step 2: 检查 SKILL.md
    skill_md = skill_dir / "SKILL.md"
    if not skill_md.exists():
        print("❌ SKILL.md 文件缺失")
        return False
    
    print(f"✅ SKILL.md 已存在 ({skill_md.stat().st_size:,} bytes)")
    
    # Step 3: OpenClaw 会自动扫描目录加载技能
    print("\n🔄 OpenClaw 自动扫描机制:")
    print("   - OpenClaw 在启动时会扫描 ~/.openclaw/extensions/openclaw-lark/skills/")
    print("   - 每个子目录如果包含 SKILL.md，就会被自动识别为可用技能")
    print("   - 无需手动注册！文件存在即注册成功 ✅")
    
    return True

def verify_registration():
    """验证技能是否可被加载"""
    print("\n" + "=" * 60)
    print("✅ 验证注册结果")
    print("=" * 60)
    
    # 列出所有飞书相关技能
    skills_dir = Path("~/.openclaw/extensions/openclaw-lark/skills").expanduser()
    
    if not skills_dir.exists():
        print(f"❌ 技能目录不存在：{skills_dir}")
        return False
    
    print("\n📚 当前飞书相关技能列表:")
    print("-" * 60)
    
    for item in sorted(skills_dir.iterdir()):
        if item.is_dir():
            skill_md = item / "SKILL.md"
            status = "✅" if skill_md.exists() else "❌"
            
            # 获取技能名称和描述
            name = item.name
            desc = ""
            if skill_md.exists():
                with open(skill_md, 'r', encoding='utf-8') as f:
                    first_line = f.readline().strip()
                    desc = first_line.split(" - ")[1] if " - " in first_line else first_line
            
            print(f"   {status} {name:30s}")
    
    # 检查 feishu-whisper-voice
    whisper_skill = skills_dir / "feishu-whisper-voice"
    if whisper_skill.exists() and (whisper_skill / "SKILL.md").exists():
        print("\n✅ feishu-whisper-voice 已注册到技能池！")
        
        # 显示技能信息
        with open(whisper_skill / "SKILL.md", 'r', encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines[:5]:
                print(f"   {line.strip()}")
    else:
        print("\n❌ feishu-whisper-voice 未注册成功")
    
    return True

def main():
    """主函数"""
    try:
        # 检查文件
        if not check_skill_files():
            print("\n❌ 技能文件不完整，请先补充缺失的文件")
            sys.exit(1)
        
        # 验证描述
        if not check_skill_in_available():
            print("\n❌ 技能描述无效")
            sys.exit(1)
        
        # 注册技能
        if not register_skill():
            sys.exit(1)
        
        # 验证结果
        verify_registration()
        
        # 总结
        print("\n" + "=" * 60)
        print("🎉 技能注册完成！")
        print("=" * 60)
        print("""
下一步操作:

1. ✅ 文件检查 - 已完成
2. ✅ 目录存在 - 已确认
3. ✅ SKILL.md - 已验证
4. ⬜ OpenClaw 重启 - 可选 (如果当前会话未加载新技能)

如需重新加载技能，可以：
   - 重启 OpenClaw: openclaw gateway restart
   - 或等待下次自动扫描

技能已注册到飞书技能池！
        """)
        
    except Exception as e:
        print(f"\n❌ 错误：{e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()


path: scripts-/install.sh
content: #!/bin/bash
# Feishu Whisper Voice - 快速安装脚本

set -e

echo "🎤 飞书 Whisper + TTS 语音交互技能包"
echo "====================================="
echo ""

# 检测系统
if [[ "$OSTYPE" == "darwin"* ]]; then
    OS="macOS"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    OS="Linux"
else
    OS="Unknown"
fi

echo "检测到操作系统：$OS"
echo ""

# 检查 Python 环境
if ! command -v python3 &> /dev/null; then
    echo "❌ 未找到 Python，请先安装 Python 3.8+"
    exit 1
fi

PYTHON_VERSION=$(python3 --version | cut -d' ' -f2)
echo "✓ Python 版本：$PYTHON_VERSION"

# 检查 pip
if ! command -v pip &> /dev/null && ! command -v pip3 &> /dev/null; then
    echo "❌ 未找到 pip，请先安装"
    exit 1
fi

pip=$(command -v pip3 || command -v pip)
echo "✓ Pip: $pip"
echo ""

# 创建虚拟环境（推荐）
VENV_DIR=".venv_whisper"
if [ ! -d "$VENV_DIR" ]; then
    echo "📦 创建虚拟环境..."
    python3 -m venv $VENV_DIR
fi

source $VENV_DIR/bin/activate
echo "✓ 虚拟环境已激活：$VENV_DIR"
echo ""

# 安装核心依赖
echo "🔧 安装核心依赖..."
pip install faster-whisper torch --upgrade

echo ""
echo "✅ 核心依赖安装完成！"
echo ""

# 可选：安装 Whisper.cpp (本地轻量级方案)
read -p "是否安装 whisper.cpp (本地运行，无需 GPU)? [y/N] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "📦 安装 whisper.cpp..."
    
    if command -v brew &> /dev/null; then
        # macOS Homebrew
        brew install whisper-cpp
        echo "✓ Whisper.cpp (Homebrew) 已安装"
    elif command -v apt-get &> /dev/null; then
        # Ubuntu/Debian
        sudo apt-get update
        sudo apt-get install -y whisper-cpp
        echo "✓ Whisper.cpp (apt) 已安装"
    else
        # 源码编译
        git clone https://github.com/ggerganov/whisper.cpp
        cd whisper.cpp && make
        cd ..
        echo "✓ Whisper.cpp (源码编译) 已安装"
    fi
    
    echo ""
fi

# 可选：安装高级 TTS 服务
echo "🎤 高级 TTS 服务（可选）"
echo ""
read -p "是否安装 Azure Cognitive Services SDK? [y/N] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    pip install azure-cognitiveservices-speech
    echo "✓ Azure TTS SDK 已安装"
fi

read -p "是否安装 ElevenLabs CLI? [y/N] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    pip install elevenlabs
    echo "✓ ElevenLabs SDK 已安装"
fi

echo ""

# 配置环境变量提示
echo "🔑 配置环境变量（可选）"
echo ""
read -p "是否配置 OpenAI API Key? [y/N] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "export OPENAI_API_KEY=\"your_api_key\"" >> ~/.bashrc || true
    echo "export OPENAI_API_KEY=\"your_api_key\"" >> ~/.zshrc || true
    echo "✓ OpenAI API Key 配置已添加到 shell rc 文件"
fi

echo ""

# 下载 Whisper 模型（首次运行自动下载）
echo "📥 Whisper 模型说明:"
echo ""
echo "首次运行时，Whisper 会自动下载模型文件到 ~/.cache/torch/hub/"
echo ""
echo "推荐模型大小:"
echo "  - base (142MB): 通用场景，CPU 友好"
echo "  - small (466MB): 生产环境，平衡性能"
echo "  - medium (769MB): 高精度需求，需要 GPU"
echo ""

# 测试安装
echo "🧪 运行安装测试..."
python3 << 'EOF'
import sys
try:
    from faster_whisper import WhisperModel
    print("✓ Faster Whisper 库导入成功")
    
    # 尝试加载模型（仅检查，不实际下载）
    try:
        model = WhisperModel("base", device="cpu")
        print("✓ Whisper 模型可以正常加载")
    except Exception as e:
        print(f"⚠️ 模型加载警告：{e}")
        
except ImportError as e:
    print(f"❌ 导入失败：{e}")
    sys.exit(1)

print("")
print("🎉 安装测试通过！可以开始使用 Whisper 了！")
EOF

echo ""
echo "====================================="
echo "✅ 安装完成！下一步："
echo ""
echo "1. 阅读 SKILL.md 了解使用方法"
echo "2. 配置环境变量（可选）:"
echo "   - OPENAI_API_KEY (使用 OpenAI Whisper API)"
echo "   - AZURE_SUBSCRIPTION_KEY (使用 Azure TTS)"
echo ""
echo "3. 开始处理语音消息！🎤"
echo "====================================="


path: scripts-/transcribe_quick.py
content: #!/usr/bin/env python3
"""快速语音识别 - 简单版"""

import subprocess
import sys

audio_path = "/tmp/openclaw/bot-resource-1773578262747-a7da1d11-604d-4f80-ae2a-5ff39981f1c8"

print(f"📥 开始识别：{audio_path}")
print("="*50)

try:
    # 安装依赖（如果未安装）
    subprocess.run([sys.executable, "-m", "pip", "install", "faster-whisper", "--quiet"], check=True)
    
    from faster_whisper import WhisperModel
    
    print("🔍 加载模型 base (约 140MB，首次需要下载)...")
    model = WhisperModel("base", device="cpu")
    
    print("⏳ 正在识别语音...")
    segments, info = model.transcribe(audio_path, language="zh")
    
    text = " ".join([segment.text for segment in segments])
    
    print("="*50)
    print(f"✅ 识别成功！\n\n📝 内容：{text}\n")
    print("="*50)
    
except Exception as e:
    print(f"\n❌ 错误：{e}")
    import traceback
    traceback.print_exc()


path: scripts-/transcribe_local.py
content: #!/usr/bin/env python3
"""使用本地 faster-whisper 模型进行语音识别"""

import sys
from faster_whisper import WhisperModel

def transcribe_audio(file_path: str):
    """使用本地模型路径进行识别"""
    
    # 指定本地模型路径
    model_path = "/Users/jurry/.cache/modelscope/hub/models/pengzhendong/faster-whisper-base"
    
    print(f"📥 识别文件：{file_path}")
    print("==================================================")
    
    print("\n🔍 加载 faster-whisper 模型...")
    model = WhisperModel(model_path, device="cpu", compute_type="float32")
    print("✅ 模型加载成功！\n")
    
    print("⏳ 正在识别语音...")
    
    # 执行转录
    segments, info = model.transcribe(
        file_path,
        language="zh",
        beam_size=5,
        word_timestamps=False
    )
    
    # 收集结果
    result_text = ""
    for segment in segments:
        print(f"[{segment.start:.2f}s -> {segment.end:.2f}s] {segment.text}")
        result_text += segment.text + " "
    
    return result_text.strip()

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法：python transcribe_local.py <音频文件路径>")
        sys.exit(1)
    
    file_path = sys.argv[1]
    try:
        result = transcribe_audio(file_path)
        print("\n==================================================")
        print(f"📝 识别结果:\n{result}")
        # 将结果写入文件供后续使用
        with open("/tmp/voice_result.txt", "w", encoding="utf-8") as f:
            f.write(result)
    except Exception as e:
        print(f"\n❌ 错误：{e}")
        sys.exit(1)


path: scripts-/transcribe_newest.py
content: #!/usr/bin/env python3
"""使用 faster-whisper 进行语音识别 - 最新版本"""

from faster_whisper import WhisperModel
import os
import sys

# 最新的音频文件路径
audio_path = "/tmp/openclaw/bot-resource-1773586420907-d5f2d6a8-a2c6-4b0e-b5e7-0f0e5c5e5e5e"

print(f"📥 识别文件：{audio_path}")
print("="*50)

# faster-whisper 模型路径（已缓存）
model_path = os.path.expanduser("~/.cache/modelscope/hub/models/pengzhendong/faster-whisper-base")

if not os.path.exists(model_path):
    print(f"❌ 错误：faster-whisper 模型未找到")
    sys.exit(1)

try:
    print(f"\n🔍 加载 faster-whisper 模型...")
    model = WhisperModel(model_path, device="auto")
    
    print("✅ 模型加载成功！")
    print("\n⏳ 正在识别语音...")
    
    # 识别中文语音
    segments, info = model.transcribe(audio_path, language="zh")
    
    text = ""
    for segment in segments:
        text += segment.text + " "
    
    print("="*50)
    print(f"✅ 识别成功！\n\n📝 内容：{text.strip()}\n")
    print("="*50)
    
except Exception as e:
    print(f"\n❌ 错误类型：{type(e).__name__}")
    print(f"❌ 错误信息：{e}")


path: scripts-/transcribe.py
content: #!/usr/bin/env python3
"""Whisper 语音识别脚本 - Feishu Voice Assistant"""

import sys
from pathlib import Path

def transcribe_audio(audio_path: str) -> str:
    """使用 Whisper 转文字"""
    
    try:
        from faster_whisper import WhisperModel
        
        print("🔍 正在加载 Whisper 模型...")
        
        # 尝试加载 base 模型（CPU 友好）
        model = WhisperModel("base", device="cpu")
        
        print(f"📥 识别音频文件：{audio_path}")
        
        segments, info = model.transcribe(
            audio_path,
            language="zh",  # 中文场景，或自动检测用 None
            word_timestamps=True
        )
        
        text = " ".join([segment.text for segment in segments])
        
        print(f"✅ 识别结果：{text}")
        return text
        
    except ImportError:
        print("❌ faster-whisper 未安装，正在尝试安装...")
        import subprocess
        subprocess.check_call([sys.executable, "-m", "pip", "install", "faster-whisper"])
        
        # 重试
        from faster_whisper import WhisperModel
        model = WhisperModel("base", device="cpu")
        segments, info = model.transcribe(audio_path)
        text = " ".join([segment.text for segment in segments])
        
        print(f"✅ 识别结果：{text}")
        return text
        
    except Exception as e:
        print(f"❌ 识别失败：{e}")
        return None

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法：python transcribe.py <audio_file_path>")
        sys.exit(1)
    
    audio_path = sys.argv[1]
    
    # 检查文件是否存在
    if not Path(audio_path).exists():
        print(f"❌ 文件不存在：{audio_path}")
        sys.exit(1)
    
    result = transcribe_audio(audio_path)
    
    if result:
        print("\n=== 识别结果 ===")
        print(result)
        print("===============")


path: scripts-/transcribe_faster.py
content: #!/usr/bin/env python3
"""使用 faster-whisper 进行语音识别 - 自动检测模型位置"""

from faster_whisper import WhisperModel
import os
import sys

audio_path = "/tmp/openclaw/bot-resource-1773585421031-d57701a2-6fbd-405b-915f-9d46d7ad2ee3"

print(f"📥 识别文件：{audio_path}")
print("="*50)

# 检查模型位置
model_paths = [
    os.path.expanduser("~/.cache/modelscope/hub/models/pengzhendong/faster-whisper-base"),
    os.path.expanduser("~/.cache/huggingface/hub/models--SYSTRAN-faster-whisper-base"),
]

model_path = None
for path in model_paths:
    if os.path.exists(path):
        print(f"✅ 找到模型：{path}")
        model_path = path
        break

if not model_path:
    print("❌ 错误：faster-whisper 模型未下载")
    print("\n请运行以下命令安装:")
    print("  pip install faster-whisper")
    print("  # 首次运行时会自动下载 base 模型 (~73MB)")
    sys.exit(1)

try:
    print(f"\n🔍 加载 faster-whisper 模型...")
    
    # 使用本地模型路径
    model = WhisperModel(model_path, device="auto")
    
    print("✅ 模型加载成功！")
    print("\n⏳ 正在识别语音...")
    
    # 识别中文语音
    segments, info = model.transcribe(audio_path, language="zh")
    
    text = ""
    for segment in segments:
        text += segment.text + " "
    
    print("="*50)
    print(f"✅ 识别成功！\n\n📝 内容：{text.strip()}\n")
    print("="*50)
    
except Exception as e:
    print(f"\n❌ 错误类型：{type(e).__name__}")
    print(f"❌ 错误信息：{e}")
    
    import traceback
    traceback.print_exc()


path: scripts-/transcribe_latest.py
content: #!/usr/bin/env python3
"""使用 faster-whisper 进行语音识别 - 最新版本"""

from faster_whisper import WhisperModel
import os
import sys

# 最新的音频文件路径
audio_path = "/tmp/openclaw/bot-resource-1773586420696-fbdaa3d8-bc14-4e3f-a6f0-c497f5c0a988"

print(f"📥 识别文件：{audio_path}")
print("="*50)

# faster-whisper 模型路径（已缓存）
model_path = os.path.expanduser("~/.cache/modelscope/hub/models/pengzhendong/faster-whisper-base")

if not os.path.exists(model_path):
    print(f"❌ 错误：faster-whisper 模型未找到")
    sys.exit(1)

try:
    print(f"\n🔍 加载 faster-whisper 模型...")
    model = WhisperModel(model_path, device="auto")
    
    print("✅ 模型加载成功！")
    print("\n⏳ 正在识别语音...")
    
    # 识别中文语音
    segments, info = model.transcribe(audio_path, language="zh")
    
    text = ""
    for segment in segments:
        text += segment.text + " "
    
    print("="*50)
    print(f"✅ 识别成功！\n\n📝 内容：{text.strip()}\n")
    print("="*50)
    
except Exception as e:
    print(f"\n❌ 错误类型：{type(e).__name__}")
    print(f"❌ 错误信息：{e}")


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)