|
| 1 | +#!/usr/bin/python |
| 2 | +# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# calc avg RTF(NOT Accurate): grep -rn RTF log.txt | awk '{print $NF}' | awk -F "=" '{sum += $NF} END {print "all time",sum, "audio num", NR, "RTF", sum/NR}' |
| 16 | +# python3 websocket_client.py --server_ip 127.0.0.1 --port 8290 --punc.server_ip 127.0.0.1 --punc.port 8190 --wavfile ./zh.wav |
| 17 | +# python3 websocket_client.py --server_ip 127.0.0.1 --port 8290 --wavfile ./zh.wav |
| 18 | +import argparse |
| 19 | +import asyncio |
| 20 | +import codecs |
| 21 | +import os |
| 22 | +from pydub import AudioSegment |
| 23 | +import re |
| 24 | + |
| 25 | +from paddlespeech.cli.log import logger |
| 26 | +from paddlespeech.server.utils.audio_handler import ASRWsAudioHandler |
| 27 | + |
| 28 | +def convert_to_wav(input_file): |
| 29 | + # Load audio file |
| 30 | + audio = AudioSegment.from_file(input_file) |
| 31 | + |
| 32 | + # Set parameters for audio file |
| 33 | + audio = audio.set_channels(1) |
| 34 | + audio = audio.set_frame_rate(16000) |
| 35 | + |
| 36 | + # Create output filename |
| 37 | + output_file = os.path.splitext(input_file)[0] + ".wav" |
| 38 | + |
| 39 | + # Export audio file as WAV |
| 40 | + audio.export(output_file, format="wav") |
| 41 | + |
| 42 | + logger.info(f"{input_file} converted to {output_file}") |
| 43 | + |
| 44 | +def format_time(sec): |
| 45 | + # Convert seconds to SRT format (HH:MM:SS,ms) |
| 46 | + hours = int(sec/3600) |
| 47 | + minutes = int((sec%3600)/60) |
| 48 | + seconds = int(sec%60) |
| 49 | + milliseconds = int((sec%1)*1000) |
| 50 | + return f'{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}' |
| 51 | + |
| 52 | +def results2srt(results, srt_file): |
| 53 | + """convert results from paddlespeech to srt format for subtitle |
| 54 | + Args: |
| 55 | + results (dict): results from paddlespeech |
| 56 | + """ |
| 57 | + # times contains start and end time of each word |
| 58 | + times = results['times'] |
| 59 | + # result contains the whole sentence including punctuation |
| 60 | + result = results['result'] |
| 61 | + # split result into several sencences by ',' and '。' |
| 62 | + sentences = re.split(',|。', result)[:-1] |
| 63 | + # print("sentences: ", sentences) |
| 64 | + # generate relative time for each sentence in sentences |
| 65 | + relative_times = [] |
| 66 | + word_i = 0 |
| 67 | + for sentence in sentences: |
| 68 | + relative_times.append([]) |
| 69 | + for word in sentence: |
| 70 | + if relative_times[-1] == []: |
| 71 | + relative_times[-1].append(times[word_i]['bg']) |
| 72 | + if len(relative_times[-1]) == 1: |
| 73 | + relative_times[-1].append(times[word_i]['ed']) |
| 74 | + else: |
| 75 | + relative_times[-1][1] = times[word_i]['ed'] |
| 76 | + word_i += 1 |
| 77 | + # print("relative_times: ", relative_times) |
| 78 | + # generate srt file acoording to relative_times and sentences |
| 79 | + with open(srt_file, 'w') as f: |
| 80 | + for i in range(len(sentences)): |
| 81 | + # Write index number |
| 82 | + f.write(str(i+1)+'\n') |
| 83 | + |
| 84 | + # Write start and end times |
| 85 | + start = format_time(relative_times[i][0]) |
| 86 | + end = format_time(relative_times[i][1]) |
| 87 | + f.write(start + ' --> ' + end + '\n') |
| 88 | + |
| 89 | + # Write text |
| 90 | + f.write(sentences[i]+'\n\n') |
| 91 | + logger.info(f"results saved to {srt_file}") |
| 92 | + |
| 93 | +def main(args): |
| 94 | + logger.info("asr websocket client start") |
| 95 | + handler = ASRWsAudioHandler( |
| 96 | + args.server_ip, |
| 97 | + args.port, |
| 98 | + endpoint=args.endpoint, |
| 99 | + punc_server_ip=args.punc_server_ip, |
| 100 | + punc_server_port=args.punc_server_port) |
| 101 | + loop = asyncio.get_event_loop() |
| 102 | + |
| 103 | + # check if the wav file is mp3 format |
| 104 | + # if so, convert it to wav format using convert_to_wav function |
| 105 | + if args.wavfile and os.path.exists(args.wavfile): |
| 106 | + if args.wavfile.endswith(".mp3"): |
| 107 | + convert_to_wav(args.wavfile) |
| 108 | + args.wavfile = args.wavfile.replace(".mp3", ".wav") |
| 109 | + |
| 110 | + # support to process single audio file |
| 111 | + if args.wavfile and os.path.exists(args.wavfile): |
| 112 | + logger.info(f"start to process the wavscp: {args.wavfile}") |
| 113 | + result = loop.run_until_complete(handler.run(args.wavfile)) |
| 114 | + # result = result["result"] |
| 115 | + # logger.info(f"asr websocket client finished : {result}") |
| 116 | + results2srt(result, args.wavfile.replace(".wav", ".srt")) |
| 117 | + |
| 118 | + # support to process batch audios from wav.scp |
| 119 | + if args.wavscp and os.path.exists(args.wavscp): |
| 120 | + logger.info(f"start to process the wavscp: {args.wavscp}") |
| 121 | + with codecs.open(args.wavscp, 'r', encoding='utf-8') as f,\ |
| 122 | + codecs.open("result.txt", 'w', encoding='utf-8') as w: |
| 123 | + for line in f: |
| 124 | + utt_name, utt_path = line.strip().split() |
| 125 | + result = loop.run_until_complete(handler.run(utt_path)) |
| 126 | + result = result["result"] |
| 127 | + w.write(f"{utt_name} {result}\n") |
| 128 | + |
| 129 | + |
| 130 | +if __name__ == "__main__": |
| 131 | + logger.info("Start to do streaming asr client") |
| 132 | + parser = argparse.ArgumentParser() |
| 133 | + parser.add_argument( |
| 134 | + '--server_ip', type=str, default='127.0.0.1', help='server ip') |
| 135 | + parser.add_argument('--port', type=int, default=8090, help='server port') |
| 136 | + parser.add_argument( |
| 137 | + '--punc.server_ip', |
| 138 | + type=str, |
| 139 | + default=None, |
| 140 | + dest="punc_server_ip", |
| 141 | + help='Punctuation server ip') |
| 142 | + parser.add_argument( |
| 143 | + '--punc.port', |
| 144 | + type=int, |
| 145 | + default=8091, |
| 146 | + dest="punc_server_port", |
| 147 | + help='Punctuation server port') |
| 148 | + parser.add_argument( |
| 149 | + "--endpoint", |
| 150 | + type=str, |
| 151 | + default="/paddlespeech/asr/streaming", |
| 152 | + help="ASR websocket endpoint") |
| 153 | + parser.add_argument( |
| 154 | + "--wavfile", |
| 155 | + action="store", |
| 156 | + help="wav file path ", |
| 157 | + default="./16_audio.wav") |
| 158 | + parser.add_argument( |
| 159 | + "--wavscp", type=str, default=None, help="The batch audios dict text") |
| 160 | + args = parser.parse_args() |
| 161 | + |
| 162 | + main(args) |
0 commit comments