Commit be842ea8 by ‘chizw’

[+]配置优化

1 parent b974d7fa
......@@ -102,7 +102,7 @@ class FunasrService(object):
"\n打死 100\n油车 100\n电车 100\n备忘录 100\n自费 100\n胶套求成密封圈 100\n安信无忧 100"
"\n全车易损耗件 100\n厂家 100\n喷漆 100\n封釉 100\n雾化 100\n里程 100\n延保 100\n外地牌 100"
"\n轮胎 100\n胶条 100\n漆面 100\n充电接口 100\n车衣 100\n传动车身 100\n喜提新车 100"
"\n估计 100")
"\n估计 100\n安心包 100\n定损金额 100")
# print(res)
return res
......
#!/usr/bin/env python
# coding=utf-8
import os
import json
import datetime
import requests
import time
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from aliyunsdkcore.auth.credentials import AccessKeyCredential
def create_common_request(domain, version, protocolType, method, uri):
request = CommonRequest()
request.set_accept_format('json')
request.set_domain(domain)
request.set_version(version)
request.set_protocol_type(protocolType)
request.set_method(method)
request.set_uri_pattern(uri)
request.add_header('Content-Type', 'application/json')
return request
def init_parameters(fileUrl):
root = dict()
root['AppKey'] = os.environ['APPKEY']
# 基本请求参数
input = dict()
input['SourceLanguage'] = 'cn'
input['TaskKey'] = 'task' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')
input['FileUrl'] = fileUrl
root['Input'] = input
# AI相关参数,按需设置即可
parameters = dict()
# 语音识别控制相关
transcription = dict()
# 角色分离
transcription['DiarizationEnabled'] = True
# 热词ID
# transcription['PhraseId'] = '5437a8c0fda746d687fd54558d8922f6'
diarization = dict()
diarization['SpeakerCount'] = 2
transcription['Diarization'] = diarization
# 使用汽车领域模型
transcription['Model'] = 'domain-automotive'
# 增加敏感词过滤提示
customPrompt = dict()
customPromptEnabled = dict()
customPromptEnabled['Enabled'] = True
contents = dict()
contents['Name'] = 'minganci'
contents['Prompt'] = '请帮我将以下对话内容中的敏感词进行过滤处理,处理方式为替换成*,内容为:\n {Transcription}'
customPrompt['Contents'] = contents
parameters['Transcription'] = transcription
# parameters['CustomPromptEnabled']=True
# parameters['CustomPrompt']=customPrompt
root['Parameters'] = parameters
return root
def create_file_if_not_exist(file_path):
if not os.path.exists(file_path):
with open(file_path, 'w') as file:
pass # 创建空文件
def write_file(text_list, path):
# txtName = f'voicetranseform/aliyun/exportresult/{formatted_time}_{TaskId}'
txtName = path
create_file_if_not_exist(txtName)
# 逐行读取文本文件,并将每一行添加到 list 中
with open(txtName, "w", encoding='utf-8') as file:
# 将列表数据逐行写入文件
for item in text_list:
file.write(item + "\n")
def dealResultJson(contentUrl, TaskId):
contentResponse = requests.get(contentUrl)
contentResponseJson = contentResponse.json()
paragraphsArray = contentResponseJson['Transcription']['Paragraphs']
# 定义一个空的 list
text_list = []
for paraItem in paragraphsArray:
SpeakerId = paraItem.get('SpeakerId')
wordsArray = paraItem['Words']
curSentenceId = 1
index = 0
wordLine = ''
for wordItem in wordsArray:
sentenceId = wordItem['SentenceId']
if curSentenceId != sentenceId or index == 0:
if wordLine != '':
# print(wordLine)
text_list.append(wordLine)
curSentenceId = sentenceId
seconds = wordItem['Start'] // 1000
lineTime = str(datetime.timedelta(seconds=seconds))
if len(lineTime) < 8:
lineTime = '0' + lineTime
# wordLine = f'[{lineTime}] {SpeakerId}:'
wordLine = f'{SpeakerId}:'
wordLine = wordLine + wordItem['Text']
index += 1
# print(wordLine)
text_list.append(wordLine)
# 将文件写入txt
current_time = datetime.datetime.now()
formatted_time = current_time.strftime('%Y-%m-%d_%H%M%S')
# write_file(text_list,f'voicetranseform/aliyun/exportresult/{formatted_time}_{TaskId}')
return text_list
def submitTask(fileUrl):
request = create_common_request('tingwu.cn-beijing.aliyuncs.com', '2023-09-30', 'https', 'PUT',
'/openapi/tingwu/v2/tasks')
request.add_query_param('type', 'offline')
# 1、第一个测试的李总音频
# fileUrl = 'https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/7e9e313d-05ec-4d25-8165-eba0dfff28be.mp3'
# fileUrl = 'https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17198144604911719813133275.mp3'
body = init_parameters(fileUrl)
print(body)
request.set_content(json.dumps(body).encode('utf-8'))
response = client.do_action_with_exception(request)
print("response: \n" + json.dumps(json.loads(response), indent=4, ensure_ascii=False))
return json.loads(response)['Data']['TaskId']
def dealTaskResult(TaskId):
request = CommonRequest()
request.set_accept_format('json')
request.set_method('GET')
request.set_protocol_type('https') # https | http
request.set_domain('tingwu.cn-beijing.aliyuncs.com')
request.set_version('2023-09-30')
# TaskId = '1e2bfdae92e44702bfc47a50b68bb830'
request.add_header('Content-Type', 'application/json')
request.set_uri_pattern(f'/openapi/tingwu/v2/tasks/{TaskId}')
while True:
response = client.do_action_with_exception(request)
# python2: print(response)
print(str(response, encoding='utf-8'))
responseJson = json.loads(response)
taskStatus = responseJson['Data']['TaskStatus']
if taskStatus == 'COMPLETED':
resultUrl = responseJson['Data']['Result']['Transcription']
text_list = dealResultJson(resultUrl, TaskId)
return text_list
time.sleep(10)
# print("dealTaskResult success")
### 自己的key
# os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] = 'LTAI5tPGhjdotp2BrzqhpLt1'
# os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] = 'iCueQVuqRevHEJyWAijycIzVkh5Tvb'
# os.environ['APPKEY'] = 'yKnghX1dx3xO9X1g'
### 测试的key
os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] = 'LTAI5tKZK5NnKTitXn2SvvtB'
os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] = 'tdxf7ui1t3CyXTBUQWKxRIIKw01mkI'
os.environ['APPKEY'] = 'wEAW8axiurVHvM'
# TODO 请通过环境变量设置您的 AccessKeyId 和 AccessKeySecret
credentials = AccessKeyCredential(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
client = AcsClient(region_id='cn-beijing', credential=credentials)
# fileUrl = 'https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/d15515d1-6ccb-4e58-9ebf-47d45677b298.mp3'
base_path = "D:/software/python/project/funasr_web/audios/temp/"
txt_path = "/audios/11111.txt"
with open(txt_path, 'r', encoding='utf-8') as file:
for index, line in enumerate(file, 1):
print(f"line==={line}")
parts = line.strip().split(',')
name = parts[0]
fileUrl = parts[1]
taskId = submitTask(fileUrl)
# taskId = 'd80649120bc04d10892f99d70082c194'
print('taskId:' + taskId)
text_list = dealTaskResult(taskId)
write_file(text_list, f"{base_path}{name}.txt")
......@@ -111,15 +111,15 @@ def voice_slicing(id, generate_train=False, version=None):
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}"
# 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) - 0.3),
'-ss', str((item.get("offset") / 1000) - 0),
'-i', audio_file_path,
'-t', str((item.get("duration") / 1000) + 0.3),
'-t', str((item.get("duration") / 1000) + 0),
'-c', 'copy',
output_path
]
......@@ -157,8 +157,8 @@ def analysis_demo_list(version=None):
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)
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}")
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!