finetune.py
6.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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