finetune.py
8.58 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
from log.logger import log
import os
import subprocess
import requests
import oss2
import string
import shortuuid
import re
import json
import traceback
from mysql_service import funasr_db
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):
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):
translator = str.maketrans('', '', string.punctuation)
no_punct = input_string.translate(translator)
return no_punct
def remove_punctuation_re(input_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
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 analysis_db_voice_data(id):
from mysql_service import funasr_db
data = funasr_db.select_voice_data(id)
return data[0].get("recording_url"), data
def analysis_db_funasr_output(id):
from mysql_service import funasr_db
data = funasr_db.select_funasr_output_data(id)
return data[0].get("recording_url"), json.loads(data[0].get("output_data"))
def crop_audio(offset, duration, audio_file_path, output_path, expand=0):
cmd = [
'ffmpeg',
'-ss', str((offset / 1000) - expand),
'-i', audio_file_path,
'-t', str((duration / 1000) + expand),
'-c', 'copy',
output_path
]
subprocess.run(cmd, check=True)
def voice_slicing(id, generate_train=False, version=None):
if version is not None: update_dataset_paths(version)
voice_url, data = analysis_db_voice_data(id)
log.info(f"====data:{data}")
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(output_directory)):
os.makedirs(os.path.dirname(output_directory))
else:
log.info(f"{output_directory} is exists, skip it")
return
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"
crop_audio(item.get("offset"), item.get("duration"), audio_file_path, output_path)
# 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")
def crop_audio_by_rule(output_duration: int):
pattern = r"([一二三四五六七八九0-9]){6,}"
output_path = 'D:/software/python/project/funasr_web/audios/train_audio/'
total_duration = 0
data = funasr_db.select_funasr_audio('2024-08-01')
for item in data:
try:
duration = item["recording_duration"]
id = item["id"]
recording_url = item["recording_url"]
file_path = f"{output_path}{id}"
download_audio(recording_url, file_path)
output_data = item["output_data"]
jsonobj = json.loads(output_data)
for obj in jsonobj:
content = obj.get("content", "")
match = re.search(pattern, content)
if bool(match):
crop_audio(obj.get("offset"), obj.get("duration"), file_path, file_path, 10)
duration -= obj.get("duration") + (10 * 2)
total_duration += duration
if total_duration > output_duration:
log.info(f"执行完成,文件总时长:{total_duration} ms")
return
except Exception as e:
print(f"crop_audio_by_rule error:{traceback.format_exc()}")
continue
pass
list = [866, -430, 867, 870, 871, 872, 873]
for id in list:
# voice_slicing(id)
pass
def upload_files(name, file_path):
with open("D:/software/python/project/funasr_web/dataset/temp/train/train_text.txt", 'r', encoding='gbk') as file:
for index, line in enumerate(file, 1):
parts = line.split(' ')
name = parts[0]
upload_file(f"{index}.wav", f"D:/software/python/project/funasr_web/dataset/temp/0830_{name}.wav")