trans remove file way, test=doc

pull/1882/head
lym0302 3 years ago
parent b1f9b8016d
commit be21aed09b

@ -92,7 +92,7 @@ class TTSClientExecutor(BaseExecutor):
temp_wav = str(random.getrandbits(128)) + ".wav" temp_wav = str(random.getrandbits(128)) + ".wav"
soundfile.write(temp_wav, samples, sample_rate) soundfile.write(temp_wav, samples, sample_rate)
wav2pcm(temp_wav, outfile, data_type=np.int16) wav2pcm(temp_wav, outfile, data_type=np.int16)
os.system("rm %s" % (temp_wav)) os.remove(temp_wav)
else: else:
logger.error("The format for saving audio only supports wav or pcm") logger.error("The format for saving audio only supports wav or pcm")

@ -61,7 +61,7 @@ def tts_client(args):
temp_wav = str(random.getrandbits(128)) + ".wav" temp_wav = str(random.getrandbits(128)) + ".wav"
soundfile.write(temp_wav, samples, sample_rate) soundfile.write(temp_wav, samples, sample_rate)
wav2pcm(temp_wav, outfile, data_type=np.int16) wav2pcm(temp_wav, outfile, data_type=np.int16)
os.system("rm %s" % (temp_wav)) os.remove(temp_wav)
else: else:
print("The format for saving audio only supports wav or pcm") print("The format for saving audio only supports wav or pcm")

@ -321,50 +321,63 @@ class TTSWsHandler:
await ws.send(request) await ws.send(request)
logging.info("send a message to the server") logging.info("send a message to the server")
# Process the received response # 4. Process the received response
message = await ws.recv() message = await ws.recv()
first_response = time.time() - st first_response = time.time() - st
message = json.loads(message) message = json.loads(message)
status = message["status"] status = message["status"]
while True:
# When throw an exception
if status == -1:
# send end request
end_request = json.dumps({
"task": "tts",
"signal": "end",
"session": session
})
await ws.send(end_request)
break
while (status == 1): # Rerutn last packet normally, no audio information
receive_time_list.append(time.time()) elif status == 2:
audio = message["audio"] final_response = time.time() - st
audio = base64.b64decode(audio) # bytes duration = len(all_bytes) / 2.0 / 24000
chunk_duration_list.append(len(audio) / 2.0 / 24000)
all_bytes += audio if output is not None:
if self.play: save_audio_success = save_audio(all_bytes, output)
self.mutex.acquire() else:
self.buffer += audio save_audio_success = False
self.mutex.release()
if self.start_play: # send end request
self.t.start() end_request = json.dumps({
self.start_play = False "task": "tts",
"signal": "end",
message = await ws.recv() "session": session
message = json.loads(message) })
status = message["status"] await ws.send(end_request)
break
# 4. Last packet, no audio information
if status == 2:
final_response = time.time() - st
duration = len(all_bytes) / 2.0 / 24000
if output is not None:
save_audio_success = save_audio(all_bytes, output)
else:
save_audio_success = False
# 5. send end request # Return the audio stream normally
end_request = json.dumps({ elif status == 1:
"task": "tts", receive_time_list.append(time.time())
"signal": "end", audio = message["audio"]
"session": session audio = base64.b64decode(audio) # bytes
}) chunk_duration_list.append(len(audio) / 2.0 / 24000)
await ws.send(end_request) all_bytes += audio
if self.play:
self.mutex.acquire()
self.buffer += audio
self.mutex.release()
if self.start_play:
self.t.start()
self.start_play = False
message = await ws.recv()
message = json.loads(message)
status = message["status"]
else: else:
logger.error("infer error") logger.error("infer error, return status is invalid.")
if self.play: if self.play:
self.t.join() self.t.join()

@ -167,7 +167,7 @@ def save_audio(bytes_data, audio_path, sample_rate: int=24000) -> bool:
channels=1, channels=1,
bits=16, bits=16,
sample_rate=sample_rate) sample_rate=sample_rate)
os.system("rm ./tmp.pcm") os.remove("./tmp.pcm")
else: else:
print("Only supports saved audio format is pcm or wav") print("Only supports saved audio format is pcm or wav")
return False return False

@ -16,7 +16,6 @@ import uuid
from fastapi import APIRouter from fastapi import APIRouter
from fastapi import WebSocket from fastapi import WebSocket
from fastapi import WebSocketDisconnect
from starlette.websockets import WebSocketState as WebSocketState from starlette.websockets import WebSocketState as WebSocketState
from paddlespeech.cli.log import logger from paddlespeech.cli.log import logger
@ -87,17 +86,19 @@ async def websocket_endpoint(websocket: WebSocket):
resp = {"status": 1, "audio": tts_results} resp = {"status": 1, "audio": tts_results}
await websocket.send_json(resp) await websocket.send_json(resp)
except StopIteration as e: except StopIteration as e:
import pdb
pdb.set_trace()
resp = {"status": 2, "audio": ''} resp = {"status": 2, "audio": ''}
await websocket.send_json(resp) await websocket.send_json(resp)
logger.info( logger.info(
"Complete the synthesis of the audio streams") "Complete the synthesis of the audio streams")
break break
except Exception as e:
resp = {"status": -1, "audio": ''}
await websocket.send_json(resp)
break
else: else:
logger.error( logger.error(
"Invalid request, please check if the request is correct.") "Invalid request, please check if the request is correct.")
except WebSocketDisconnect: except Exception as e:
pass logger.error(e)

@ -1,6 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
import argparse import argparse
import os import os
import shutil
import yaml import yaml
@ -14,7 +15,7 @@ def change_device(yamlfile: str, engine: str, device: str):
model_type (dict): change model type model_type (dict): change model type
""" """
tmp_yamlfile = yamlfile.split(".yaml")[0] + "_tmp.yaml" tmp_yamlfile = yamlfile.split(".yaml")[0] + "_tmp.yaml"
os.system("cp %s %s" % (yamlfile, tmp_yamlfile)) shutil.copyfile(yamlfile, tmp_yamlfile)
if device == 'cpu': if device == 'cpu':
set_device = 'cpu' set_device = 'cpu'
@ -41,7 +42,7 @@ def change_device(yamlfile: str, engine: str, device: str):
print(yaml.dump(y, default_flow_style=False, sort_keys=False)) print(yaml.dump(y, default_flow_style=False, sort_keys=False))
yaml.dump(y, fw, allow_unicode=True) yaml.dump(y, fw, allow_unicode=True)
os.system("rm %s" % (tmp_yamlfile)) os.remove(tmp_yamlfile)
print("Change %s successfully." % (yamlfile)) print("Change %s successfully." % (yamlfile))
@ -52,7 +53,7 @@ def change_engine_type(yamlfile: str, engine_type):
task (str): asr or tts task (str): asr or tts
""" """
tmp_yamlfile = yamlfile.split(".yaml")[0] + "_tmp.yaml" tmp_yamlfile = yamlfile.split(".yaml")[0] + "_tmp.yaml"
os.system("cp %s %s" % (yamlfile, tmp_yamlfile)) shutil.copyfile(yamlfile, tmp_yamlfile)
speech_task = engine_type.split("_")[0] speech_task = engine_type.split("_")[0]
with open(tmp_yamlfile) as f, open(yamlfile, "w+", encoding="utf-8") as fw: with open(tmp_yamlfile) as f, open(yamlfile, "w+", encoding="utf-8") as fw:
@ -65,7 +66,7 @@ def change_engine_type(yamlfile: str, engine_type):
y['engine_list'] = engine_list y['engine_list'] = engine_list
print(yaml.dump(y, default_flow_style=False, sort_keys=False)) print(yaml.dump(y, default_flow_style=False, sort_keys=False))
yaml.dump(y, fw, allow_unicode=True) yaml.dump(y, fw, allow_unicode=True)
os.system("rm %s" % (tmp_yamlfile)) os.remove(tmp_yamlfile)
print("Change %s successfully." % (yamlfile)) print("Change %s successfully." % (yamlfile))

@ -1,6 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
import argparse import argparse
import os import os
import shutil
import yaml import yaml
@ -13,7 +14,7 @@ def change_value(args):
target_value = args.target_value target_value = args.target_value
tmp_yamlfile = yamlfile.split(".yaml")[0] + "_tmp.yaml" tmp_yamlfile = yamlfile.split(".yaml")[0] + "_tmp.yaml"
os.system("cp %s %s" % (yamlfile, tmp_yamlfile)) shutil.copyfile(yamlfile, tmp_yamlfile)
with open(tmp_yamlfile) as f, open(yamlfile, "w+", encoding="utf-8") as fw: with open(tmp_yamlfile) as f, open(yamlfile, "w+", encoding="utf-8") as fw:
y = yaml.safe_load(f) y = yaml.safe_load(f)
@ -51,7 +52,7 @@ def change_value(args):
print(yaml.dump(y, default_flow_style=False, sort_keys=False)) print(yaml.dump(y, default_flow_style=False, sort_keys=False))
yaml.dump(y, fw, allow_unicode=True) yaml.dump(y, fw, allow_unicode=True)
os.system("rm %s" % (tmp_yamlfile)) os.remove(tmp_yamlfile)
print(f"Change key: {target_key} to value: {target_value} successfully.") print(f"Change key: {target_key} to value: {target_value} successfully.")

@ -75,8 +75,8 @@ if __name__ == "__main__":
args = parser.parse_args() args = parser.parse_args()
os.system("rm -rf %s" % (args.output_dir)) if not os.path.exists(args.output_dir):
os.mkdir(args.output_dir) os.makedirs(args.output_dir)
first_response_list = [] first_response_list = []
final_response_list = [] final_response_list = []

Loading…
Cancel
Save