Commit b974d7fa by ‘chizw’

[+]配置优化

1 parent 7d2a5828
...@@ -2,10 +2,14 @@ class Config: ...@@ -2,10 +2,14 @@ class Config:
DEBUG = False DEBUG = False
env = 'release' env = 'release'
# 数据库连接配置 # 数据库连接配置
host='supplychain.db.glsx.com' # host='supplychain.db.glsx.com'
port = 13306 # port = 13306
user = 'biz_dj_smartcarlife' # user = 'biz_dj_smartcarlife'
password = '[已加密]204db0d16a54807b8822481c6612513a' # password = '[已加密]204db0d16a54807b8822481c6612513a'
host='192.168.5.23'
port = 3306
user = 'user_chizw'
password = 'rAzjFsfp'
database = 'dj_smartcarlife' database = 'dj_smartcarlife'
# Kafka consumer配置 # Kafka consumer配置
kafka_consumer_bootstrap_servers = 'newbiz.kafka.zk.glsx.com:9094' kafka_consumer_bootstrap_servers = 'newbiz.kafka.zk.glsx.com:9094'
......
...@@ -29,10 +29,9 @@ if config.extract_sys_param("env") is None: ...@@ -29,10 +29,9 @@ if config.extract_sys_param("env") is None:
model="D:\software\python\model\modelscope\hub\iic\paraformer-temp", model="D:\software\python\model\modelscope\hub\iic\paraformer-temp",
# model="D:\software\python\model\modelscope\hub\iic\SenseVoiceSmall", # model="D:\software\python\model\modelscope\hub\iic\SenseVoiceSmall",
# model="iic/speech_paraformer-large-vad-punc-spk_asr_nat-zh-cn", # model="iic/speech_paraformer-large-vad-punc-spk_asr_nat-zh-cn",
vad_model="fsmn-vad", # vad_model="fsmn-vad",
punc_model="ct-punc-c", # punc_model="ct-punc-c",
# spk_model="damo/speech_campplus_sv_zh-cn_16k-common", # spk_model="damo/speech_campplus_sv_zh-cn_16k-common",
spk_model="iic/speech_campplus_sv_zh-cn_16k-common",
# spk_model_revision="v2.0.2", # spk_model_revision="v2.0.2",
# spk_model="D:\software\python\model\modelscope\hub\iic\speech_campplus_speaker-diarization_common", # spk_model="D:\software\python\model\modelscope\hub\iic\speech_campplus_speaker-diarization_common",
# spk_model="D:\software\python\model\modelscope\hub\iic\speech_eres2netv2_sv_zh-cn_16k-common", # spk_model="D:\software\python\model\modelscope\hub\iic\speech_eres2netv2_sv_zh-cn_16k-common",
...@@ -53,12 +52,17 @@ if config.extract_sys_param("env") is None: ...@@ -53,12 +52,17 @@ if config.extract_sys_param("env") is None:
# model="iic/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch", # model="iic/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch",
# vad_model="iic/speech_fsmn_vad_zh-cn-16k-common-pytorch", # vad_model="iic/speech_fsmn_vad_zh-cn-16k-common-pytorch",
# punc_model="iic/punc_ct-transformer_cn-en-common-vocab471067-large", # punc_model="iic/punc_ct-transformer_cn-en-common-vocab471067-large",
vad_model="iic/speech_fsmn_vad_zh-cn-16k-common-pytorch",
vad_kwargs={"max_single_segment_time": 60000},
punc_model="iic/punc_ct-transformer_zh-cn-common-vocab272727-pytorch",
spk_model="iic/speech_campplus_sv_zh-cn_16k-common",
) )
else: else:
model = AutoModel( model = AutoModel(
model="iic/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch", # 官方 model="iic/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch", # 官方
vad_model="fsmn-vad", vad_model="iic/speech_fsmn_vad_zh-cn-16k-common-pytorch",
punc_model="ct-punc-c", vad_kwargs={"max_single_segment_time": 60000},
punc_model="iic/punc_ct-transformer_zh-cn-common-vocab272727-pytorch",
spk_model="iic/speech_campplus_sv_zh-cn_16k-common", spk_model="iic/speech_campplus_sv_zh-cn_16k-common",
model_revision='v2.0.4', model_revision='v2.0.4',
vad_model_revision='v2.0.4', vad_model_revision='v2.0.4',
......
...@@ -78,10 +78,11 @@ def test_paraformer(): ...@@ -78,10 +78,11 @@ def test_paraformer():
print(res) print(res)
run("https://smartcard-1253080096.cos.ap-guangzhou.myqcloud.com/audio/806599C6309C_1710219356_806599C6309C-1710219356.MP3", # run("https://smartcard-1253080096.cos.ap-guangzhou.myqcloud.com/audio/806599C6309C_1710219356_806599C6309C-1710219356.MP3",
"旧北京") # "旧北京")
run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17205808870541720579482995.mp3", "李丽") run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17205808870541720579482995.mp3", "李丽")
run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17205827687271720580657722.mp3", "江门嘉钡") # run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17205827687271720580657722.mp3", "江门嘉钡")
run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17212740566661721272782874.mp3", "曹俊") # run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17212740566661721272782874.mp3", "曹俊")
run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_172075478615417207538825792.mp3", "东联") # run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_172075478615417207538825792.mp3", "东联")
run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17212740566661721272782874.mp3", "李钰达") # run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_172119302897717211886442290.mp3", "李钰达")
# run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17205900068901720588971648.mp3", "张东华")
...@@ -103,3 +103,11 @@ def select_voice_data(id): ...@@ -103,3 +103,11 @@ def select_voice_data(id):
where ibr.id = %s;""" where ibr.id = %s;"""
) )
return pool.select_all(sql, (id)) return pool.select_all(sql, (id))
def select_funasr_output_data(id):
sql = (
"""select * from inspection_badge_recordings ibr
left join ali_asr_model_res aamr on ibr.process_task_id = aamr.task_id and aamr.del_flag = 0
where ibr.deleted_flag = 'N' and ibr.id = %s;"""
)
return pool.select_all(sql, (id))
\ No newline at end of file \ No newline at end of file
import argparse
import copy
import json
import os
import uuid
import librosa
import gradio as gr
import numpy as np
import soundfile
g_json_key_text = ""
g_json_key_path = ""
g_load_file = ""
g_load_format = ""
g_max_json_index = 0
g_index = 0
g_batch = 10
g_text_list = []
g_audio_list = []
g_checkbox_list = []
g_data_json = []
g_language = None
LANG_CONFIG_MAP = {
"zh": {
"Change Index" : "改变索引",
"Submit Text" : "保存文本",
"Merge Audio" : "合并音频",
"Delete Audio" : "删除音频",
"Previous Index" : "前一页",
"Next Index" : "后一页",
"Light Theme" : "亮色模式",
"Dark Theme" : "黑暗模式",
"Choose Audio" : "选择音频",
"Output Audio" : "Output Audio",
"Text" : "文本",
"Invert Selection": "反选",
"Save File" : "保存文件",
"Split Audio" : "分割音频",
"Audio Split Point(s)" : "音频分割点(单位:秒)",
"Index":"索引",
"Interval":"合并间隔(单位:秒)"
},
}
class TextLanguage():
def __init__(self, language: str = "en") -> None:
if language in LANG_CONFIG_MAP.keys():
self.language = language
else:
self.language = "en"
pass
def get_text(self, text: str) -> str:
if self.language == "en":
return text
elif text in LANG_CONFIG_MAP[self.language].keys():
return LANG_CONFIG_MAP[self.language][text]
else:
return text
def __call__(self, text: str) -> str:
return self.get_text(text)
def reload_data(index, batch):
global g_index
g_index = index
global g_batch
g_batch = batch
datas = g_data_json[index:index+batch]
output = []
for d in datas:
output.append(
{
g_json_key_text: d[g_json_key_text],
g_json_key_path: d[g_json_key_path]
}
)
return output
def b_change_index(index, batch):
global g_index, g_batch
g_index, g_batch = index, batch
datas = reload_data(index, batch)
output = []
for i , _ in enumerate(datas):
output.append(
gr.Textbox(
label=f"Text {i+index}",
value=_[g_json_key_text]
)
)
for _ in range(g_batch - len(datas)):
output.append(
gr.Textbox(
label=f"Text",
value=""
)
)
for _ in datas:
output.append(_[g_json_key_path])
for _ in range(g_batch - len(datas)):
output.append(None)
for _ in range(g_batch):
output.append(False)
return output
def b_next_index(index, batch):
if (index + batch) <= g_max_json_index:
return index + batch , *b_change_index(index + batch, batch)
else:
return index, *b_change_index(index, batch)
def b_previous_index(index, batch):
if (index - batch) >= 0:
return index - batch , *b_change_index(index - batch, batch)
else:
return 0, *b_change_index(0, batch)
def b_submit_change(*text_list):
global g_data_json
change = False
for i, new_text in enumerate(text_list):
if g_index + i <= g_max_json_index:
new_text = new_text.strip()+' '
if (g_data_json[g_index + i][g_json_key_text] != new_text):
g_data_json[g_index + i][g_json_key_text] = new_text
change = True
if change:
b_save_file()
return g_index, *b_change_index(g_index, g_batch)
def b_delete_audio(*checkbox_list):
global g_data_json, g_index, g_max_json_index
change = False
for i, checkbox in reversed(list(enumerate(checkbox_list))):
if g_index + i < len(g_data_json):
if (checkbox == True):
if g_force_delete:
print("remove",g_data_json[g_index + i][g_json_key_path])
os.remove(g_data_json[g_index + i][g_json_key_path])
g_data_json.pop(g_index + i)
change = True
g_max_json_index = len(g_data_json)-1
if g_index > g_max_json_index:
g_index = g_max_json_index
g_index = g_index if g_index >= 0 else 0
if g_force_delete and change:
b_save_file()
return gr.Slider(value=g_index, maximum=(g_max_json_index if g_max_json_index>=0 else 0)), *b_change_index(g_index, g_batch)
def b_invert_selection(*checkbox_list):
new_list = [not item if item is True else True for item in checkbox_list]
return new_list
def get_next_path(filename):
base_dir = os.path.dirname(filename)
base_name = os.path.splitext(os.path.basename(filename))[0]
for i in range(100):
new_path = os.path.join(base_dir, f"{base_name}_{str(i).zfill(2)}.wav")
if not os.path.exists(new_path) :
return new_path
return os.path.join(base_dir, f'{str(uuid.uuid4())}.wav')
def b_audio_split(audio_breakpoint, *checkbox_list):
global g_data_json , g_max_json_index
checked_index = []
for i, checkbox in enumerate(checkbox_list):
if (checkbox == True and g_index+i < len(g_data_json)):
checked_index.append(g_index + i)
if len(checked_index) == 1 :
index = checked_index[0]
audio_json = copy.deepcopy(g_data_json[index])
path = audio_json[g_json_key_path]
data, sample_rate = librosa.load(path, sr=None, mono=True)
audio_maxframe = len(data)
break_frame = int(audio_breakpoint * sample_rate)
if (break_frame >= 1 and break_frame < audio_maxframe):
audio_first = data[0:break_frame]
audio_second = data[break_frame:]
nextpath = get_next_path(path)
soundfile.write(nextpath, audio_second, sample_rate)
soundfile.write(path, audio_first, sample_rate)
g_data_json.insert(index + 1, audio_json)
g_data_json[index + 1][g_json_key_path] = nextpath
b_save_file()
g_max_json_index = len(g_data_json) - 1
return gr.Slider(value=g_index, maximum=g_max_json_index), *b_change_index(g_index, g_batch)
def b_merge_audio(interval_r, *checkbox_list):
global g_data_json , g_max_json_index
checked_index = []
audios_path = []
audios_text = []
delete_files = []
for i, checkbox in enumerate(checkbox_list):
if (checkbox == True and g_index+i < len(g_data_json)):
checked_index.append(g_index + i)
if (len(checked_index)>1):
for i in checked_index:
audios_path.append(g_data_json[i][g_json_key_path])
audios_text.append(g_data_json[i][g_json_key_text])
for i in reversed(checked_index[1:]):
delete_files.append(g_data_json[i][g_json_key_path])
g_data_json.pop(i)
base_index = checked_index[0]
base_path = audios_path[0]
g_data_json[base_index][g_json_key_text] = "".join(audios_text)
audio_list = []
l_sample_rate = None
for i, path in enumerate(audios_path):
data, sample_rate = librosa.load(path, sr=l_sample_rate, mono=True)
l_sample_rate = sample_rate
if (i > 0):
silence = np.zeros(int(l_sample_rate * interval_r))
audio_list.append(silence)
audio_list.append(data)
audio_concat = np.concatenate(audio_list)
for item_file in delete_files:
os.remove(item_file)
soundfile.write(base_path, audio_concat, l_sample_rate)
b_save_file()
g_max_json_index = len(g_data_json) - 1
return gr.Slider(value=g_index, maximum=g_max_json_index), *b_change_index(g_index, g_batch)
def b_save_json():
with open(g_load_file,'w', encoding="utf-8") as file:
for data in g_data_json:
file.write(f'{json.dumps(data, ensure_ascii = False)}\n')
def b_save_list():
with open(g_load_file,'w', encoding="utf-8") as file:
for data in g_data_json:
wav_path = data["wav_path"]
speaker_name = data["speaker_name"]
language = data["language"]
text = data["text"]
file.write(f"{wav_path}|{speaker_name}|{language}|{text}".strip()+'\n')
def b_load_json():
global g_data_json, g_max_json_index
with open(g_load_file, 'r', encoding="utf-8") as file:
g_data_json = file.readlines()
g_data_json = [json.loads(line) for line in g_data_json]
g_max_json_index = len(g_data_json) - 1
def b_load_list():
global g_data_json, g_max_json_index
with open(g_load_file, 'r', encoding="utf-8") as source:
data_list = source.readlines()
for _ in data_list:
data = _.split('|')
if (len(data) == 4):
wav_path, speaker_name, language, text = data
g_data_json.append(
{
'wav_path':wav_path,
'speaker_name':speaker_name,
'language':language,
'text':text.strip()
}
)
else:
print("error line:", data)
g_max_json_index = len(g_data_json) - 1
def b_save_file():
if g_load_format == "json":
b_save_json()
elif g_load_format == "list":
b_save_list()
def b_load_file():
if g_load_format == "json":
b_load_json()
elif g_load_format == "list":
b_load_list()
def set_global(load_json, load_list, json_key_text, json_key_path, batch, webui_language, force_delete, version):
global g_json_key_text, g_json_key_path, g_load_file, g_load_format, g_batch, g_language, g_force_delete
g_batch = int(batch)
if (version != 'None'):
g_load_format = "list"
g_load_file = f".\\dataset\\{version}\\demo.list"
else:
if (load_json != "None"):
g_load_format = "json"
g_load_file = load_json
elif (load_list != "None"):
g_load_format = "list"
g_load_file = load_list
else:
g_load_format = "list"
g_load_file = "demo.list"
g_json_key_text = json_key_text
g_json_key_path = json_key_path
g_language = TextLanguage(webui_language)
g_force_delete = force_delete
b_load_file()
def startwebui(args):
set_global(args.load_json, args.load_list, args.json_key_text, args.json_key_path, args.g_batch, args.webui_language,
args.force_delete, args.ver)
with gr.Blocks() as demo:
with gr.Row():
btn_change_index = gr.Button(g_language("Change Index"))
btn_submit_change = gr.Button(g_language("Submit Text"))
btn_merge_audio = gr.Button(g_language("Merge Audio"))
btn_delete_audio = gr.Button(g_language("Delete Audio"))
btn_previous_index = gr.Button(g_language("Previous Index"))
btn_next_index = gr.Button(g_language("Next Index"))
with gr.Row():
index_slider = gr.Slider(
minimum=0, maximum=g_max_json_index, value=g_index, step=1, label=g_language("Index"), scale=3
)
splitpoint_slider = gr.Slider(
minimum=0, maximum=120.0, value=0, step=0.1, label=g_language("Audio Split Point(s)"), scale=3
)
btn_audio_split = gr.Button(g_language("Split Audio"), scale=1)
btn_save_json = gr.Button(g_language("Save File"), visible=True, scale=1)
btn_invert_selection = gr.Button(g_language("Invert Selection"), scale=1)
with gr.Row():
with gr.Column():
for _ in range(0,g_batch):
with gr.Row():
text = gr.Textbox(
label = "Text",
visible = True,
scale=5
)
audio_output = gr.Audio(
label= g_language("Output Audio"),
visible = True,
scale=5
)
audio_check = gr.Checkbox(
label="Yes",
show_label = True,
info = g_language("Choose Audio"),
scale=1
)
g_text_list.append(text)
g_audio_list.append(audio_output)
g_checkbox_list.append(audio_check)
with gr.Row():
batchsize_slider = gr.Slider(
minimum=1, maximum=g_batch, value=g_batch, step=1, label=g_language("Batch Size"), scale=3, interactive=False
)
interval_slider = gr.Slider(
minimum=0, maximum=2, value=0, step=0.01, label=g_language("Interval"), scale=3
)
btn_theme_dark = gr.Button(g_language("Light Theme"), link="?__theme=light", scale=1)
btn_theme_light = gr.Button(g_language("Dark Theme"), link="?__theme=dark", scale=1)
btn_change_index.click(
b_change_index,
inputs=[
index_slider,
batchsize_slider,
],
outputs=[
*g_text_list,
*g_audio_list,
*g_checkbox_list
],
)
btn_submit_change.click(
b_submit_change,
inputs=[
*g_text_list,
],
outputs=[
index_slider,
*g_text_list,
*g_audio_list,
*g_checkbox_list
],
)
btn_previous_index.click(
b_previous_index,
inputs=[
index_slider,
batchsize_slider,
],
outputs=[
index_slider,
*g_text_list,
*g_audio_list,
*g_checkbox_list
],
)
btn_next_index.click(
b_next_index,
inputs=[
index_slider,
batchsize_slider,
],
outputs=[
index_slider,
*g_text_list,
*g_audio_list,
*g_checkbox_list
],
)
btn_delete_audio.click(
b_delete_audio,
inputs=[
*g_checkbox_list
],
outputs=[
index_slider,
*g_text_list,
*g_audio_list,
*g_checkbox_list
]
)
btn_merge_audio.click(
b_merge_audio,
inputs=[
interval_slider,
*g_checkbox_list
],
outputs=[
index_slider,
*g_text_list,
*g_audio_list,
*g_checkbox_list
]
)
btn_audio_split.click(
b_audio_split,
inputs=[
splitpoint_slider,
*g_checkbox_list
],
outputs=[
index_slider,
*g_text_list,
*g_audio_list,
*g_checkbox_list
]
)
btn_invert_selection.click(
b_invert_selection,
inputs=[
*g_checkbox_list
],
outputs=[
*g_checkbox_list
]
)
btn_save_json.click(
b_save_file
)
demo.load(
b_change_index,
inputs=[
index_slider,
batchsize_slider,
],
outputs=[
*g_text_list,
*g_audio_list,
*g_checkbox_list
],
)
demo.launch()
\ No newline at end of file \ No newline at end of file
...@@ -354,6 +354,8 @@ def startwebui(args): ...@@ -354,6 +354,8 @@ def startwebui(args):
) )
btn_theme_dark = gr.Button(g_language("Light Theme"), link="?__theme=light", scale=1) btn_theme_dark = gr.Button(g_language("Light Theme"), link="?__theme=light", scale=1)
btn_theme_light = gr.Button(g_language("Dark Theme"), link="?__theme=dark", scale=1) btn_theme_light = gr.Button(g_language("Dark Theme"), link="?__theme=dark", scale=1)
btn_previous_index2 = gr.Button(g_language("Previous Index"))
btn_next_index2 = gr.Button(g_language("Next Index"))
btn_change_index.click( btn_change_index.click(
b_change_index, b_change_index,
...@@ -478,4 +480,32 @@ def startwebui(args): ...@@ -478,4 +480,32 @@ def startwebui(args):
], ],
) )
btn_previous_index2.click(
b_previous_index,
inputs=[
index_slider,
batchsize_slider,
],
outputs=[
index_slider,
*g_text_list,
*g_audio_list,
*g_checkbox_list
],
)
btn_next_index2.click(
b_next_index,
inputs=[
index_slider,
batchsize_slider,
],
outputs=[
index_slider,
*g_text_list,
*g_audio_list,
*g_checkbox_list
],
)
demo.launch() demo.launch()
\ No newline at end of file \ No newline at end of file
import difflib
from bs4 import BeautifulSoup
def compare_texts(file1_path, file2_path, output_file_path):
print('================================start...===============================')
# 从文件中读取文本内容
with open(file1_path, 'r', encoding='utf-8') as file1:
text1 = file1.read()
with open(file2_path, 'r', encoding='utf-8') as file2:
text2 = file2.read()
# 计算file2的总字符数
total_chars = len(text2)
# 创建HtmlDiff对象来生成HTML格式的差异报告
d = difflib.HtmlDiff()
diff_html = d.make_file(text1.splitlines(), text2.splitlines(), fromdesc='Text 1', todesc='Text 2')
# 使用BeautifulSoup解析HTML报告
soup = BeautifulSoup(diff_html, 'html.parser')
# 提取text2列中diff_add和diff_chg标记的内容
added_chars = 0
modified_chars = 0
modified_text = []
# 找到所有<tr>标签
rows = soup.find_all('tr')
for row in rows:
# 找到每个<tr>标签中的最后一个<td>标签
cells = row.find_all('td')
if cells:
last_cell = cells[-1]
# 在最后一个<td>标签中找到所有带有diff_add和diff_chg的<span>标签
spans = last_cell.find_all('span', {'class': ['diff_add', 'diff_chg']})
for span in spans:
text = span.get_text()
if 'diff_add' in span['class']:
added_chars += len(text)
elif 'diff_chg' in span['class']:
modified_chars += len(text)
modified_text.append(text)
# print("\nModified (diff_chg) Text:")
# print("".join(modified_text))
# 生成统计信息
stats_info = f"""
<h2>Comparison Report</h2>
<p><strong>file2.txt Total Characters:</strong> {total_chars}</p>
<p><strong>Added Characters (diff_add):</strong> {added_chars}; Added Characters Rate(%):</strong> {((added_chars / total_chars) * 100):.2f}%</p>
<p><strong>Modified Characters (diff_chg):</strong> {modified_chars}; Modified Characters Rate(%):</strong> {((modified_chars / total_chars) * 100):.2f}%</p>
<hr>
"""
# 打印详细的新增和修改内容的字符数
print(f"Added Characters (diff_add): {added_chars}")
print(f"Modified Characters (diff_chg): {modified_chars}")
print(f"Compare Report: {stats_info}")
# 将统计信息添加到差异报告的开头
full_report = stats_info + str(soup)
# 将结果保存为指定路径和名称的HTML文件
with open(output_file_path, 'w', encoding='utf-8') as f:
f.write(full_report)
print(f"差异报告已生成并保存为'{output_file_path}'")
# 示例:文件路径
personfile = 'person'
filename = '82874'
# file1_path = f'voicetranseform/compareresult/asresult/{filename}/{personfile}'
# file2_path = f'voicetranseform/compareresult/asresult/{filename}/fun001'
# output_file_path = f'voicetranseform/compareresult/asresult/{filename}/diff_output_v1.0.6.html'
# compare_texts(file1_path, file2_path, output_file_path)
file1_path = f'C:/Users/chizw/Desktop/新建文本文档.txt'
file2_path = f'C:/Users/chizw/Desktop/output.txt'
output_file_path = f'C:/Users/chizw/Desktop/diff_output_v1.0.6.source.html'
compare_texts(file1_path, file2_path, output_file_path)
...@@ -6,6 +6,7 @@ import oss2 ...@@ -6,6 +6,7 @@ import oss2
import string import string
import shortuuid import shortuuid
import re import re
import json
folder = "quality/" folder = "quality/"
bucketName = 'glsk-oss' bucketName = 'glsk-oss'
...@@ -80,20 +81,30 @@ def update_dataset_paths(version): ...@@ -80,20 +81,30 @@ def update_dataset_paths(version):
output_val_text_path = f"{train_path}/val_text.txt" output_val_text_path = f"{train_path}/val_text.txt"
output_val_wav_path = f"{train_path}/val_wav.scp" 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 voice_slicing(id, generate_train=False, version=None): def voice_slicing(id, generate_train=False, version=None):
if version is not None: update_dataset_paths(version) if version is not None: update_dataset_paths(version)
from mysql_service import funasr_db voice_url, data = analysis_db_voice_data(id)
data = funasr_db.select_voice_data(id)
log.info(f"====data:{data}") log.info(f"====data:{data}")
voice_url = data[0].get("recording_url")
audio_file_name = os.path.basename(voice_url) audio_file_name = os.path.basename(voice_url)
basename, extension = os.path.splitext(audio_file_name) basename, extension = os.path.splitext(audio_file_name)
output_directory = base_output_directory + basename + "/" output_directory = base_output_directory + basename + "/"
audio_file_path = os.path.join(base_output_directory, audio_file_name) audio_file_path = os.path.join(base_output_directory, audio_file_name)
if not os.path.exists(os.path.dirname(audio_file_path)): if not os.path.exists(os.path.dirname(output_directory)):
os.makedirs(os.path.dirname(audio_file_path))
os.makedirs(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) download_audio(voice_url, audio_file_path)
if not os.path.exists(os.path.dirname(train_path)): if not os.path.exists(os.path.dirname(train_path)):
os.makedirs(os.path.dirname(train_path)) os.makedirs(os.path.dirname(train_path))
...@@ -106,9 +117,9 @@ def voice_slicing(id, generate_train=False, version=None): ...@@ -106,9 +117,9 @@ def voice_slicing(id, generate_train=False, version=None):
output_path = f"{output_directory}{key}.wav" output_path = f"{output_directory}{key}.wav"
cmd = [ cmd = [
'ffmpeg', 'ffmpeg',
'-ss', str(item.get("offset") / 1000), '-ss', str((item.get("offset") / 1000) - 0.3),
'-i', audio_file_path, '-i', audio_file_path,
'-t', str(item.get("duration") / 1000), '-t', str((item.get("duration") / 1000) + 0.3),
'-c', 'copy', '-c', 'copy',
output_path output_path
] ]
...@@ -158,9 +169,10 @@ def analysis_demo_list(version=None): ...@@ -158,9 +169,10 @@ def analysis_demo_list(version=None):
log.info("analysis_demo_list success") log.info("analysis_demo_list success")
list = [-430, 866, 867, 870, 871, 872, 873] list = [866,-430,867,870,871,872,873]
for id in list: for id in list:
# voice_slicing(id) # voice_slicing(id)
pass pass
print(str(2270 / 1000))
\ No newline at end of file \ No newline at end of file
import Levenshtein as lev
import jieba
def cer(reference, hypothesis):
"""
Calculate the Character Error Rate (CER) for Chinese
:param reference: The reference string
:param hypothesis: The hypothesis string
:return: CER as a float
"""
# Levenshtein distance at the character level
distance = lev.distance(reference, hypothesis)
cer_value = distance / len(reference)
return cer_value
def wer(reference, hypothesis):
"""
Calculate the Word Error Rate (WER) for Chinese
:param reference: The reference string
:param hypothesis: The hypothesis string
:return: WER as a float
"""
# Perform Chinese word segmentation
reference_words = list(jieba.cut(reference))
hypothesis_words = list(jieba.cut(hypothesis))
# Levenshtein distance at the word level
distance = lev.distance(' '.join(reference_words), ' '.join(hypothesis_words))
wer_value = distance / len(reference_words)
return wer_value
def ser(reference, hypothesis):
"""
Calculate the Sentence Error Rate (SER) for Chinese
:param reference: The reference string
:param hypothesis: The hypothesis string
:return: SER as a float
"""
# Split sentences using common Chinese punctuation
reference_sentences = reference.split('\n')
hypothesis_sentences = hypothesis.split('\n')
num_sentences = len(reference_sentences)
num_errors = sum(1 for r, h in zip(reference_sentences, hypothesis_sentences) if r != h)
ser_value = num_errors / num_sentences
return ser_value
def dealcompare(file1_path, file2_path):
print('================================start...===============================')
# 从文件中读取文本内容
with open(file1_path, 'r', encoding='utf-8') as file1:
reference_text = file1.read()
with open(file2_path, 'r', encoding='utf-8') as file2:
hypothesis_text = file2.read()
cer_value = cer(reference_text, hypothesis_text)
wer_value = wer(reference_text, hypothesis_text)
ser_value = ser(reference_text, hypothesis_text)
print(f"CER(字错率): {cer_value:.4f}")
print(f"WER(词错率): {wer_value:.4f}")
print(f"SER(句错率): {ser_value:.4f}")
filename = '82874'
# 人工标注文件:
personfile = f'C:/Users/chizw/Desktop/新建文本文档.txt'
# 训练后文件:
trainfile = f'C:/Users/chizw/Desktop/output.txt'
dealcompare(personfile, trainfile)
print('================================end===============================')
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!