MOSS-Transcribe-Diarize API使用教程:Python与命令行两种方式详解

【免费下载链接】MOSS-Transcribe-Diarize MOSS-Transcribe-Diarize 是 OpenMOSS 团队推出的开源语音转写与说话人分离模型。它对长音频、多说话人音频进行统一建模,支持自动语音识别、带说话人标识的转写、说话人分离、时间戳预测以及简洁转录文本生成。 【免费下载链接】MOSS-Transcribe-Diarize 项目地址: https://ai.gitcode.com/OpenMOSS/MOSS-Transcribe-Diarize

MOSS-Transcribe-Diarize是OpenMOSS团队推出的终极开源语音转写与说话人分离模型,它能够对长音频、多说话人音频进行统一建模,支持自动语音识别、带说话人标识的转写、说话人分离、时间戳预测以及简洁转录文本生成。这款强大的AI工具让语音转写变得简单快速,无论是会议录音、播客内容还是视频采访,都能一键生成带时间戳和说话人标签的专业转录文本。

🎯 为什么选择MOSS-Transcribe-Diarize?

在众多语音转写工具中,MOSS-Transcribe-Diarize凭借其独特优势脱颖而出:

  • 一体化解决方案:将语音识别、说话人分离、时间戳预测整合在一个模型中
  • 长音频支持:专门优化处理长格式音频内容
  • 多说话人识别:自动区分不同说话者,标记为[S01]、[S02]等
  • 高精度时间戳:精确到秒级的开始和结束时间标记
  • 开源免费:Apache 2.0许可证,完全免费使用

MOSS-Transcribe-Diarize模型架构

📦 环境准备与安装

系统要求与依赖安装

开始使用MOSS-Transcribe-Diarize之前,需要准备以下环境:

  1. Python版本:推荐Python 3.12
  2. CUDA支持:如需GPU加速,需要CUDA 12.8及以上版本
  3. FFmpeg:用于音频/视频文件处理

完整的安装步骤如下:

# 克隆仓库
git clone https://gitcode.com/OpenMOSS/MOSS-Transcribe-Diarize
cd MOSS-Transcribe-Diarize

# 创建虚拟环境
conda create -n moss-transcribe-diarize python=3.12 -y
conda activate moss-transcribe-diarize

# 安装FFmpeg
conda install -c conda-forge "ffmpeg=7" -y

# 安装PyTorch及相关依赖
pip install --extra-index-url https://download.pytorch.org/whl/cu128 -e ".[torch-runtime]"

如需FlashAttention 2加速(仅限支持GPU):

pip install --extra-index-url https://download.pytorch.org/whl/cu128 -e ".[torch-runtime,flash-attn]"

🖥️ 命令行使用方式

基本转录命令

MOSS-Transcribe-Diarize提供了简单易用的命令行接口,只需一行命令即可完成音频转录:

python infer.py \
  --model OpenMOSS-Team/MOSS-Transcribe-Diarize \
  --audio /path/to/your_audio.mp3 \
  --decoding greedy \
  --max-new-tokens 2048

支持多种解码策略

根据不同的需求,可以选择不同的解码策略:

贪心解码(推荐用于准确性)

python infer.py \
  --model OpenMOSS-Team/MOSS-Transcribe-Diarize \
  --audio meeting_recording.mp4 \
  --decoding greedy \
  --max-new-tokens 2048

采样解码(适合创意性内容)

python infer.py \
  --model OpenMOSS-Team/MOSS-Transcribe-Diarize \
  --audio podcast_episode.m4a \
  --decoding sample \
  --temperature 0.7 \
  --max-new-tokens 2048

JSON格式输出

如需结构化数据,可以使用JSON输出格式:

python infer.py \
  --model OpenMOSS-Team/MOSS-Transcribe-Diarize \
  --audio interview.wav \
  --json

自定义提示词

您还可以自定义转录提示词,让模型按照特定要求生成转录文本:

python infer.py \
  --model OpenMOSS-Team/MOSS-Transcribe-Diarize \
  --audio lecture.mp4 \
  --prompt "请将这段音频转录成中文,包含时间戳和说话人标签。"

🐍 Python API使用方式

基础Python脚本

对于开发者,Python API提供了更灵活的控制方式。以下是一个完整的Python使用示例:

import torch
from transformers import AutoModelForCausalLM, AutoProcessor
from moss_transcribe_diarize.inference_utils import (
    build_transcription_messages,
    generate_transcription,
    resolve_device,
)

# 设置模型和音频路径
model_id = "OpenMOSS-Team/MOSS-Transcribe-Diarize"
audio_path = "/path/to/your_audio_or_video.mp4"

# 自动检测设备(CPU/GPU)
device = resolve_device("auto")
dtype = torch.bfloat16 if device.type == "cuda" else torch.float32

# 加载模型(注意必须设置trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    trust_remote_code=True,
    dtype="auto",
).to(dtype=dtype).to(device).eval()

# 加载处理器
processor = AutoProcessor.from_pretrained(
    model_id,
    trust_remote_code=True,
    fix_mistral_regex=True,
)

# 构建转录消息
messages = build_transcription_messages(audio_path)

# 生成转录结果
result = generate_transcription(
    model,
    processor,
    messages,
    max_new_tokens=2048,
    do_sample=False,  # 使用贪心解码
    device=device,
    dtype=dtype,
)

# 输出结果
print("转录文本:")
print(result["text"])

高级配置选项

Python API支持更多高级配置,满足复杂场景需求:

# 自定义提示词
messages = build_transcription_messages(
    audio_path,
    prompt="请为这段会议录音生成详细的转录文本,包含精确的时间戳和说话人标签。",
)

# 使用采样解码
result = generate_transcription(
    model,
    processor,
    messages,
    max_new_tokens=4096,  # 支持更长文本
    do_sample=True,       # 启用采样
    temperature=0.7,      # 控制随机性
    top_p=0.9,           # 核采样参数
    device=device,
    dtype=dtype,
)

# 获取完整输出信息
print(f"生成token数量:{len(result['generated_ids'])}")
print(f"推理时间:{result['inference_time']:.2f}秒")

批量处理音频文件

对于需要处理多个音频文件的场景,可以编写批量处理脚本:

import os
from pathlib import Path

def batch_transcribe(audio_folder, output_folder):
    audio_files = list(Path(audio_folder).glob("*.mp3")) + \
                  list(Path(audio_folder).glob("*.wav")) + \
                  list(Path(audio_folder).glob("*.mp4"))
    
    for audio_file in audio_files:
        print(f"处理文件:{audio_file.name}")
        
        messages = build_transcription_messages(str(audio_file))
        result = generate_transcription(
            model, processor, messages,
            max_new_tokens=2048,
            do_sample=False,
            device=device,
            dtype=dtype,
        )
        
        # 保存结果
        output_path = Path(output_folder) / f"{audio_file.stem}_transcript.txt"
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(result["text"])
        
        print(f"已保存:{output_path}")

# 使用示例
batch_transcribe("audio_inputs/", "transcripts/")

📊 输出格式详解

标准输出格式

MOSS-Transcribe-Diarize生成的标准转录格式如下:

[开始时间][说话人标签]转录文本[结束时间]

实际示例

[0.48][S01]欢迎大家参加今天的会议[2.15][3.22][S02]我们首先回顾一下上周的进展[5.78][6.45][S01]好的,我准备了相关的数据报告[9.12]

格式说明

  • 时间戳:精确到秒的小数,如[0.48]表示0.48秒
  • 说话人标签:匿名标签[S01][S02]等,仅在同一音频内区分不同说话者
  • 转录文本:识别出的语音内容
  • 时间顺序:每个说话片段按时间顺序排列

🔧 配置文件解析

了解项目配置文件有助于更好地使用API:

🚀 性能优化技巧

内存优化

处理长音频时,可以调整以下参数优化内存使用:

# 减少最大新token数量
result = generate_transcription(
    model, processor, messages,
    max_new_tokens=1024,  # 减少内存占用
    device=device,
    dtype=torch.float16,  # 使用半精度浮点数
)

# 启用CPU模式(无GPU时)
device = resolve_device("cpu")
dtype = torch.float32

速度优化

# 启用FlashAttention(如已安装)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    trust_remote_code=True,
    dtype="auto",
    attn_implementation="flash_attention_2",  # 启用FlashAttention
).to(device).eval()

🛠️ 常见问题解决

1. 音频格式支持问题

MOSS-Transcribe-Diarize支持多种音频和视频格式:

  • 音频格式:MP3、WAV、FLAC、M4A等
  • 视频格式:MP4、MOV、MKV、AVI等
  • 采样率:自动重采样到16kHz

2. 内存不足处理

如果遇到内存不足错误,可以尝试:

  • 使用CPU模式:device = resolve_device("cpu")
  • 减少max_new_tokens参数值
  • 分割长音频为多个片段处理

3. 模型加载失败

确保正确设置trust_remote_code=True

model = AutoModelForCausalLM.from_pretrained(
    model_id,
    trust_remote_code=True,  # 必须设置为True
    dtype="auto",
)

📈 实际应用场景

会议记录自动化

def transcribe_meeting(audio_path):
    """自动化会议记录生成"""
    messages = build_transcription_messages(
        audio_path,
        prompt="请转录这次会议讨论,清晰标注每个发言人的内容和时间。"
    )
    result = generate_transcription(model, processor, messages)
    return format_meeting_minutes(result["text"])

def format_meeting_minutes(transcript):
    """格式化会议纪要"""
    lines = transcript.strip().split('\n')
    formatted = []
    for line in lines:
        if line.startswith('['):
            # 解析时间戳和说话人
            parts = line.split(']')
            time = parts[0][1:]  # 去掉开头的[
            speaker = parts[1][1:] if len(parts) > 1 else ""
            text = parts[2] if len(parts) > 2 else ""
            formatted.append(f"{time}秒 - {speaker}: {text}")
    return '\n'.join(formatted)

播客内容索引

def create_podcast_index(audio_path):
    """创建播客时间索引"""
    result = generate_transcription(model, processor, messages)
    transcript = result["text"]
    
    # 提取时间戳和主题
    timestamps = extract_timestamps(transcript)
    topics = extract_topics(transcript)
    
    return {
        "transcript": transcript,
        "timestamps": timestamps,
        "topics": topics,
        "duration": get_audio_duration(audio_path)
    }

🎉 总结

MOSS-Transcribe-Diarize提供了Python和命令行两种简单易用的API接口,无论是技术开发者还是普通用户都能快速上手。通过本教程,您已经掌握了:

  1. 环境配置:快速搭建运行环境
  2. 命令行使用:一键式音频转录
  3. Python API:灵活编程接口
  4. 高级功能:自定义提示、批量处理
  5. 性能优化:内存和速度调优技巧

这款强大的开源语音转写工具将极大提升您的音频处理效率,无论是会议记录、播客制作还是视频字幕生成,都能提供专业级的转录服务。立即开始使用MOSS-Transcribe-Diarize,体验高效精准的语音转写体验吧!✨

【免费下载链接】MOSS-Transcribe-Diarize MOSS-Transcribe-Diarize 是 OpenMOSS 团队推出的开源语音转写与说话人分离模型。它对长音频、多说话人音频进行统一建模,支持自动语音识别、带说话人标识的转写、说话人分离、时间戳预测以及简洁转录文本生成。 【免费下载链接】MOSS-Transcribe-Diarize 项目地址: https://ai.gitcode.com/OpenMOSS/MOSS-Transcribe-Diarize

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐