test05.py 3.68 KB
import json
from funasr import AutoModel


def generate_asr_result(wav_file):
    # Initialize the ASR model
    model = AutoModel(model="paraformer-zh",
                      vad_model="fsmn-vad",
                      vad_kwargs={"max_single_segment_time": 60000},
                      punc_model="ct-punc",
                      device="cuda")

    # Generate the ASR result
    res = model.generate(input=wav_file, batch_size_s=300, batch_size_threshold_s=60, hotword='魔搭')
    return res


def write_output_file(data, file_path):
    try:
        with open(file_path, 'w', encoding='utf-8') as file:
            json.dump(data, file, ensure_ascii=False, indent=4)
    except Exception as e:
        print(f"Error: {e}")


def process_text_segments(data):
    processed_data = []
    for item in data:
        key = item['key']
        text = item['text']
        timestamps = item['timestamp']

        # Ensure timestamps match the length of text
        if len(timestamps) < len(text):
            print(
                f"Warning: Timestamp count ({len(timestamps)}) less than text length ({len(text)}). Padding timestamps.")
            # Pad timestamps with last valid timestamp
            last_timestamp = timestamps[-1]
            timestamps += [last_timestamp] * (len(text) - len(timestamps))

        sentences = split_text_into_sentences(text, timestamps)
        for sentence in sentences:
            processed_data.append({
                'key': key,
                'text': sentence['text'],
                'start': sentence['start'],
                'end': sentence['end']
            })
    return processed_data


def split_text_into_sentences(text, timestamps):
    sentences = []
    sentence_start = timestamps[0][0]
    current_sentence = ''
    current_sentence_timestamps = []

    for i, char in enumerate(text):
        current_sentence += char
        current_sentence_timestamps.append(timestamps[i])

        if char in '。!?':
            sentence_end = timestamps[i][1]
            sentences.append({
                'text': current_sentence,
                'start': sentence_start,
                'end': sentence_end
            })
            current_sentence = ''
            current_sentence_timestamps = []
            if i + 1 < len(timestamps):
                sentence_start = timestamps[i + 1][0]
        elif (i + 1 < len(timestamps) and timestamps[i + 1][0] is not None and
              timestamps[i][1] is not None and timestamps[i + 1][0] - timestamps[i][1] > 1000):  # 长间隙时长(>1秒)
            sentence_end = timestamps[i][1]
            sentences.append({
                'text': current_sentence,
                'start': sentence_start,
                'end': sentence_end
            })
            current_sentence = ''
            current_sentence_timestamps = []
            if i + 1 < len(timestamps):
                sentence_start = timestamps[i + 1][0]

    if current_sentence:  # 如果最后一句没有以标点结束
        sentence_end = timestamps[-1][1]
        sentences.append({
            'text': current_sentence,
            'start': sentence_start,
            'end': sentence_end
        })

    return sentences


def main():
    wav_file_path = '/home/yanjian/work/SenseVoice/f30/000-1400539915-12367-4ff74c1b80494533af7034cf91bed014-000-1720231298_left.wav'
    output_file_path = 'output.json'  # 修改为你的输出文件路径

    # Generate ASR result from wav file
    asr_result = generate_asr_result(wav_file_path)

    # Process the ASR result
    processed_data = process_text_segments(asr_result)

    # Write the processed data to an output file
    write_output_file(processed_data, output_file_path)


if __name__ == "__main__":
    main()