finetune.py 6.76 KB
from log.logger import log
import os
import subprocess
import requests
import oss2
import string
import shortuuid
import re

folder = "quality/"
bucketName = 'glsk-oss'
endpoint = 'oss-cn-shenzhen.aliyuncs.com'  # 假设你的Bucket处于杭州区域
auth = oss2.Auth('LTAI5tCRcCUgd7bt1J7JY596', 'kJos9mqyIkR5ztosnDt8Asrc3ulgqy')
bucket = oss2.Bucket(auth, 'http://' + endpoint, bucketName)


def read_file_as_bytes(file_path):
    with open(file_path, 'rb') as file:
        data = file.read()
    return data


def upload_file(fileName, filePath):
    # Bucket中的文件名(key)为story.txt
    key = folder + fileName
    # 上传
    file_content = read_file_as_bytes(filePath)
    bucket.put_object(key, file_content)
    # oss2.resumable_upload(bucket, 'remote-normal.txt', filename)
    fileUrl = "https://" + bucketName + "." + endpoint + "/" + folder + fileName
    log.info(f"upload_file success fileUrl:{fileUrl}")
    return fileUrl


def download_audio(url, output_path):
    """Download audio file from URL."""
    response = requests.get(url)
    with open(output_path, 'wb') as f:
        f.write(response.content)


def append_to_file(filePath, content, encoding_format='gbk'):
    if not os.path.exists(os.path.dirname(filePath)):
        os.makedirs(os.path.dirname(filePath))
    with open(filePath, 'a', encoding=encoding_format) as file:
        print(content, file=file)


def remove_punctuation(input_string):
    # Make a translator object to remove all punctuation
    translator = str.maketrans('', '', string.punctuation)

    # Use the translator object to remove punctuation from the input string
    no_punct = input_string.translate(translator)
    return no_punct


def remove_punctuation_re(input_string):
    # Use regular expression to replace all punctuation with an empty string
    no_punct = re.sub(r'[^\w\s]', '', input_string)
    return no_punct


dataset_version = '1.0'
base_subfix_path = f"dataset/{dataset_version}"
# base_output_directory = 'D:/software/python/project/funasr_web/results/1best_recog/dataset/'
base_output_directory = f'D:/software/python/project/funasr_web/dataset/{dataset_version}/'
train_path = f'D:/software/python/project/funasr_web/dataset/{dataset_version}/train'
local_train_path = f"D:/dev/python/project/FunASR/data/dataset/{dataset_version}/"
output_train_text_path = f"{train_path}/train_text.txt"
output_train_wav_path = f"{train_path}/train_wav.scp"
output_val_text_path = f"{train_path}/val_text.txt"
output_val_wav_path = f"{train_path}/val_wav.scp"


def update_dataset_paths(version):
    global base_subfix_path, base_output_directory, train_path, local_train_path, output_train_text_path, \
        output_train_wav_path, output_val_text_path, output_val_wav_path
    # 更新所有与 dataset_version 相关的路径
    base_subfix_path = f"dataset/{version}"
    base_output_directory = f'D:/software/python/project/funasr_web/dataset/{version}/'
    train_path = f'D:/software/python/project/funasr_web/dataset/{version}/train'
    local_train_path = f"D:/dev/python/project/FunASR/data/dataset/{version}/"
    output_train_text_path = f"{train_path}/train_text.txt"
    output_train_wav_path = f"{train_path}/train_wav.scp"
    output_val_text_path = f"{train_path}/val_text.txt"
    output_val_wav_path = f"{train_path}/val_wav.scp"


def voice_slicing(id, generate_train=False, version=None):
    if version is not None: update_dataset_paths(version)
    from mysql_service import funasr_db
    data = funasr_db.select_voice_data(id)
    log.info(f"====data:{data}")
    voice_url = data[0].get("recording_url")
    audio_file_name = os.path.basename(voice_url)
    basename, extension = os.path.splitext(audio_file_name)
    output_directory = base_output_directory + basename + "/"
    audio_file_path = os.path.join(base_output_directory, audio_file_name)
    if not os.path.exists(os.path.dirname(audio_file_path)):
        os.makedirs(os.path.dirname(audio_file_path))
    os.makedirs(os.path.dirname(output_directory))
    download_audio(voice_url, audio_file_path)
    if not os.path.exists(os.path.dirname(train_path)):
        os.makedirs(os.path.dirname(train_path))
    output_subfix_path = f"{base_output_directory}demo.list"
    for index, item in enumerate(data, 1):
        key = shortuuid.ShortUUID().random(length=22)
        key = f"clip_{index}"
        # split
        # output_path = f"{audio_file_path}clip_{index}.wav"  # mp3
        output_path = f"{output_directory}{key}.wav"
        cmd = [
            'ffmpeg',
            '-ss', str(item.get("offset") / 1000),
            '-i', audio_file_path,
            '-t', str(item.get("duration") / 1000),
            '-c', 'copy',
            output_path
        ]
        subprocess.run(cmd, check=True)
        # upload
        # file_url = upload_file(str(key) + '.wav', output_path)
        # save train wav and text
        text = remove_punctuation_re(item.get("content"))
        subfix_path = f"{base_subfix_path}\\{basename}\\{key}.wav"
        role = item.get("role")
        append_to_file(output_subfix_path, f"{subfix_path}|{role}|ZH|{text}", encoding_format="utf-8")
        # if generate_train:
        #     file_url = f"{local_train_path}{basename}/{key}.wav"
        #     append_to_file(output_train_text_path, f"{key} {text}")
        #     append_to_file(output_train_wav_path, f"{key} {file_url}")
        #     if index % 3 == 0:
        #         append_to_file(output_val_text_path, f"{key} {text}")
        #         append_to_file(output_val_wav_path, f"{key} {file_url}")
        #         pass
    if generate_train:
        analysis_demo_list()
    log.info("voice_slicing success")


def analysis_demo_list(version=None):
    if version is not None: update_dataset_paths(version)
    demo_list_path = base_output_directory + "demo.list"
    if not os.path.exists(os.path.dirname(train_path)):
        os.makedirs(os.path.dirname(train_path))
    with open(demo_list_path, 'r', encoding='utf-8') as file:
        for index, line in enumerate(file, 1):
            line = line.strip()
            parts = line.split('|')
            wav = parts[0]
            text = remove_punctuation_re(parts[-1])
            wav_parts = wav.split('\\')
            basename = wav_parts[-2]
            # key = wav_parts[-1].split('.')[0]
            key = shortuuid.ShortUUID().random(length=22)
            file_url = f"{local_train_path}{basename}/{key}.wav"
            if index % 3 == 0:
                append_to_file(output_val_text_path, f"{key} {text}")
                append_to_file(output_val_wav_path, f"{key} {file_url}")
            else:
                append_to_file(output_train_text_path, f"{key} {text}")
                append_to_file(output_train_wav_path, f"{key} {file_url}")
    log.info("analysis_demo_list success")


list = [-430, 866, 867, 870, 871, 872, 873]

for id in list:
    # voice_slicing(id)
    pass