finetune.py
15.7 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import datetime
import uuid
from log.logger import log
import os
import subprocess
import requests
import oss2
import string
import shortuuid
import re
import json
import traceback
import sys
import shutil
from pydub import AudioSegment
from pydub.exceptions import CouldntDecodeError
def append_sys_param(param_name, default_value=None):
sys.argv.append(f"--{param_name}")
sys.argv.append(f"{default_value}")
log.info(f"append_sys_param success sys.argv:{sys.argv}")
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,
'-y', # 强制覆盖现有文件
]
subprocess.run(cmd, check=True)
def cut_audio(input_file, output_remaining_file, start_time_ms, duration_ms):
try:
# 加载音频文件
audio = AudioSegment.from_file(input_file)
end_time_ms = int((start_time_ms + duration_ms))
# 剪切指定部分
cut_part = audio[start_time_ms:end_time_ms]
directory = os.path.dirname(output_remaining_file)
basename = "cut_" + os.path.basename(output_remaining_file)
cut_part.export(f"{directory}/{basename}", format="mp3")
upload_file(basename, f"{directory}/{basename}")
# 提取剩余部分
if start_time_ms == 0:
remaining_part = audio[end_time_ms:]
else:
remaining_part = audio[:start_time_ms] + audio[end_time_ms:]
remaining_part.export(output_remaining_file, format="mp3")
print("cut success!")
except CouldntDecodeError:
print(f"无法解析文件:{input_file}")
except Exception as e:
print(f"发生错误:{e}")
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 copy_and_overwrite(source_file_path, target_file_path):
try:
# 如果目标文件已存在,删除它
if os.path.exists(target_file_path):
os.remove(target_file_path)
# 复制文件
shutil.copy2(source_file_path, target_file_path)
print(f"文件 {source_file_path} 已覆盖到 {target_file_path}")
except FileNotFoundError:
print(f"源文件 {source_file_path} 不存在")
except IOError as e:
print(f"文件操作错误: {e}")
except Exception as e:
print(f"未知错误: {e}")
def crop_audio_by_rule(output_duration: int):
append_sys_param("env", "release")
pattern = r"(?:[零幺一二三四五六七八九0-9].*){6,}"
base_path = "D:/software/python/project/funasr_web/audios/train_audio/"
output_path = f'{base_path}final_audio/'
down_path = f'{base_path}down_audio/'
total_duration = 0
from mysql_service import funasr_db
data = funasr_db.select_funasr_audio('2024-08-01')
# data = funasr_db.select_ali_asr_model_res('1acddf88-69c8-11ef-b08a-00163e14f7ff')
with open(f"{base_path}filter.txt", 'w', encoding='utf-8') as file:
for item in data:
try:
duration = item["recording_duration"] * 1000
task_id = item["task_id"]
recording_url = item["recording_url"]
down_file = f"{down_path}{task_id}.mp3"
output_file = f"{output_path}{task_id}.mp3"
download_audio(recording_url, down_file)
output_data = item["output_data"]
if output_data is None:
continue
jsonobj = json.loads(output_data)
cut_duration = 0
for obj in jsonobj:
content = obj.get("content", "")
match = re.search(pattern, content)
if bool(match):
cut_audio(down_file, output_file, obj.get("offset") - cut_duration, obj.get("duration"), )
cut_duration += obj.get("duration")
copy_and_overwrite(output_file, down_file)
duration -= obj.get("duration")
file.write(f"{task_id}:{content}\n")
total_duration += duration
log.info(f"当前累计时长为:{total_duration} ms")
if total_duration > output_duration:
break
except Exception as e:
print(f"crop_audio_by_rule item:{item}")
print(f"crop_audio_by_rule error:{traceback.format_exc()}")
continue
log_text = f"执行完成,文件总时长:{total_duration / 1000 / 3600} hour"
log.info(log_text)
file.write(log_text)
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")
# crop_audio_by_rule(500 * 1000 * 3600)
def format_audio_and_text():
append_sys_param("env", "dev")
import funasr_service
from mysql_service import funasr_db
audio_path = f'D:/software/python/project/funasr_web/audios/train_audio/down_audio/'
text_path = f'D:/software/python/project/funasr_web/audios/train_audio/upload_text.txt'
output_path = f'D:/software/python/project/funasr_web/audios/train_audio/result.txt'
filter_path = f'D:/software/python/project/funasr_web/audios/train_audio/filter.txt'
task_set = set()
index = 0
with open(filter_path, 'r', encoding='utf-8') as file:
for line in file:
index += 1
if index % 6 != 0:
continue
# 去除行尾的换行符
line = line.strip()
# 使用逗号分隔键和值
parts = line.split(':', 1)
task_set.add(parts[0])
if len(task_set) == 100:
break
# list = list(task_set)[:100]
with open(f"{output_path}", 'w', encoding='utf-8') as file:
for task_id in task_set:
file_path = f"{audio_path}{task_id}.mp3"
data = funasr_db.select_ali_asr_model_res(task_id)
output_data = data[0].get("output_data", "")
with open(text_path, 'w', encoding='gbk') as text_file:
text_file.write(funasr_service.careful_transform_output(output_data))
text_file.close()
audio_url = upload_file(f"{task_id}.mp3", file_path)
text_url = upload_file(f"{task_id}.txt", text_path)
result = f"{task_id}:{audio_url}:{text_url}\n"
file.write(result)
# with open("D:/software/python/project/funasr_web/audios/train_audio/upload_text.txt", 'w', encoding='utf-8') as f:
# for root, dirs, files in os.walk("D:/software/python/project/funasr_web/log/111"):
# for file in files:
# file_path = os.path.join(root, file)
# url = upload_file(file,file_path)
# f.write(f"{url}\n")
def down_to_cut_to_upload(url, offset):
basename, extension = os.path.splitext(os.path.basename(url))
base_path = f"D:/software/python/project/funasr_web/audios/qwen/"
file_path = f"{base_path}{basename}"
download_audio(f"https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/{basename}.mp3",
file_path)
cut_audio(file_path,
f"D:/software/python/project/funasr_web/audios/qwen/{basename}_{offset}.mp3",
offset,
30 * 1000)
def down_file_upload_release(table_name):
down_path = "D:/software/python/project/funasr_web/audios/pic_temp/"
append_sys_param("env", "release")
from mysql_service import funasr_db
data = funasr_db.select_reception_material_data(table_name,1)
list = []
for item in data:
uuid_id = uuid.uuid4().hex
id = item['id']
if table_name == "reception_material_case_info":
thumbnail_path = f"{down_path}thumbnail_{uuid_id}"
download_audio(item['thumbnail_url'], thumbnail_path)
thumbnail_url = upload_file(f"thumbnail_{uuid_id}.png", thumbnail_path)
material_path = f"{down_path}material_{uuid_id}"
download_audio(item['material_url'], material_path)
material_url = upload_file(f"material_{uuid_id}.mp4", material_path)
update_sql = f"""UPDATE {table_name} SET thumbnail_url = '{thumbnail_url}', material_url = '{material_url}' WHERE id = {id};"""
else:
model_path = f"{down_path}model_{uuid_id}"
download_audio(item['model_display_picurl'], model_path)
model_url = upload_file(f"model_{uuid_id}.png", model_path)
detail_path = f"{down_path}detail_{uuid_id}"
download_audio(item['detail_picurl'], detail_path)
detail_url = upload_file(f"detail_{uuid_id}.png", detail_path)
update_sql = f"""UPDATE {table_name} SET model_display_picurl='{model_url}', detail_picurl='{detail_url}' WHERE id={id};"""
list.append(update_sql)
for sql in list:
print(sql)
upload_file("1_1120_赛力斯、平安智驾项目对接会议.m4a","D:\\software\\python\\project\\funasr_web\\dataset\\20241205152115-车辆知识_保险基础知识培训-视频-1 - 副本.mp3")