webui.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # coding=utf-8
  2. import gradio as gr
  3. import numpy as np
  4. import torch
  5. import torchaudio
  6. from funasr import AutoModel
  7. model = "iic/SenseVoiceSmall"
  8. model = AutoModel(model=model,
  9. vad_model="iic/speech_fsmn_vad_zh-cn-16k-common-pytorch",
  10. vad_kwargs={"max_single_segment_time": 30000},
  11. trust_remote_code=True,
  12. )
  13. emo_dict = {
  14. "<|HAPPY|>": "😊",
  15. "<|SAD|>": "😔",
  16. "<|ANGRY|>": "😡",
  17. "<|NEUTRAL|>": "",
  18. "<|FEARFUL|>": "😰",
  19. "<|DISGUSTED|>": "🤢",
  20. "<|SURPRISED|>": "😮",
  21. }
  22. event_dict = {
  23. "<|BGM|>": "🎼",
  24. "<|Speech|>": "",
  25. "<|Applause|>": "👏",
  26. "<|Laughter|>": "😀",
  27. "<|Cry|>": "😭",
  28. "<|Sneeze|>": "🤧",
  29. "<|Breath|>": "",
  30. "<|Cough|>": "🤧",
  31. }
  32. emoji_dict = {
  33. "<|nospeech|><|Event_UNK|>": "❓",
  34. "<|zh|>": "",
  35. "<|en|>": "",
  36. "<|yue|>": "",
  37. "<|ja|>": "",
  38. "<|ko|>": "",
  39. "<|nospeech|>": "",
  40. "<|HAPPY|>": "😊",
  41. "<|SAD|>": "😔",
  42. "<|ANGRY|>": "😡",
  43. "<|NEUTRAL|>": "",
  44. "<|BGM|>": "🎼",
  45. "<|Speech|>": "",
  46. "<|Applause|>": "👏",
  47. "<|Laughter|>": "😀",
  48. "<|FEARFUL|>": "😰",
  49. "<|DISGUSTED|>": "🤢",
  50. "<|SURPRISED|>": "😮",
  51. "<|Cry|>": "😭",
  52. "<|EMO_UNKNOWN|>": "",
  53. "<|Sneeze|>": "🤧",
  54. "<|Breath|>": "",
  55. "<|Cough|>": "😷",
  56. "<|Sing|>": "",
  57. "<|Speech_Noise|>": "",
  58. "<|withitn|>": "",
  59. "<|woitn|>": "",
  60. "<|GBG|>": "",
  61. "<|Event_UNK|>": "",
  62. }
  63. lang_dict = {
  64. "<|zh|>": "<|lang|>",
  65. "<|en|>": "<|lang|>",
  66. "<|yue|>": "<|lang|>",
  67. "<|ja|>": "<|lang|>",
  68. "<|ko|>": "<|lang|>",
  69. "<|nospeech|>": "<|lang|>",
  70. }
  71. emo_set = {"😊", "😔", "😡", "😰", "🤢", "😮"}
  72. event_set = {"🎼", "👏", "😀", "😭", "🤧", "😷", }
  73. def format_str(s):
  74. for sptk in emoji_dict:
  75. s = s.replace(sptk, emoji_dict[sptk])
  76. return s
  77. def format_str_v2(s):
  78. sptk_dict = {}
  79. for sptk in emoji_dict:
  80. sptk_dict[sptk] = s.count(sptk)
  81. s = s.replace(sptk, "")
  82. emo = "<|NEUTRAL|>"
  83. for e in emo_dict:
  84. if sptk_dict[e] > sptk_dict[emo]:
  85. emo = e
  86. for e in event_dict:
  87. if sptk_dict[e] > 0:
  88. s = event_dict[e] + s
  89. s = s + emo_dict[emo]
  90. for emoji in emo_set.union(event_set):
  91. s = s.replace(" " + emoji, emoji)
  92. s = s.replace(emoji + " ", emoji)
  93. return s.strip()
  94. def format_str_v3(s):
  95. def get_emo(s):
  96. return s[-1] if s[-1] in emo_set else None
  97. def get_event(s):
  98. return s[0] if s[0] in event_set else None
  99. s = s.replace("<|nospeech|><|Event_UNK|>", "❓")
  100. for lang in lang_dict:
  101. s = s.replace(lang, "<|lang|>")
  102. s_list = [format_str_v2(s_i).strip(" ") for s_i in s.split("<|lang|>")]
  103. new_s = " " + s_list[0]
  104. cur_ent_event = get_event(new_s)
  105. for i in range(1, len(s_list)):
  106. if len(s_list[i]) == 0:
  107. continue
  108. if get_event(s_list[i]) == cur_ent_event and get_event(s_list[i]) != None:
  109. s_list[i] = s_list[i][1:]
  110. # else:
  111. cur_ent_event = get_event(s_list[i])
  112. if get_emo(s_list[i]) != None and get_emo(s_list[i]) == get_emo(new_s):
  113. new_s = new_s[:-1]
  114. new_s += s_list[i].strip().lstrip()
  115. new_s = new_s.replace("The.", " ")
  116. return new_s.strip()
  117. def model_inference(input_wav, language, fs=16000):
  118. # task_abbr = {"Speech Recognition": "ASR", "Rich Text Transcription": ("ASR", "AED", "SER")}
  119. language_abbr = {"auto": "auto", "zh": "zh", "en": "en", "yue": "yue", "ja": "ja", "ko": "ko",
  120. "nospeech": "nospeech"}
  121. # task = "Speech Recognition" if task is None else task
  122. language = "auto" if len(language) < 1 else language
  123. selected_language = language_abbr[language]
  124. # selected_task = task_abbr.get(task)
  125. # print(f"input_wav: {type(input_wav)}, {input_wav[1].shape}, {input_wav}")
  126. if isinstance(input_wav, tuple):
  127. fs, input_wav = input_wav
  128. input_wav = input_wav.astype(np.float32) / np.iinfo(np.int16).max
  129. if len(input_wav.shape) > 1:
  130. input_wav = input_wav.mean(-1)
  131. if fs != 16000:
  132. print(f"audio_fs: {fs}")
  133. resampler = torchaudio.transforms.Resample(fs, 16000)
  134. input_wav_t = torch.from_numpy(input_wav).to(torch.float32)
  135. input_wav = resampler(input_wav_t[None, :])[0, :].numpy()
  136. merge_vad = True # False if selected_task == "ASR" else True
  137. print(f"language: {language}, merge_vad: {merge_vad}")
  138. text = model.generate(input=input_wav,
  139. cache={},
  140. language=language,
  141. use_itn=True,
  142. batch_size_s=60, merge_vad=merge_vad)
  143. print(text)
  144. text = text[0]["text"]
  145. text = format_str_v3(text)
  146. print(text)
  147. return text
  148. audio_examples = [
  149. ["example/zh.mp3", "zh"],
  150. ["example/yue.mp3", "yue"],
  151. ["example/en.mp3", "en"],
  152. ["example/ja.mp3", "ja"],
  153. ["example/ko.mp3", "ko"],
  154. ["example/emo_1.wav", "auto"],
  155. ["example/emo_2.wav", "auto"],
  156. ["example/emo_3.wav", "auto"],
  157. # ["example/emo_4.wav", "auto"],
  158. # ["example/event_1.wav", "auto"],
  159. # ["example/event_2.wav", "auto"],
  160. # ["example/event_3.wav", "auto"],
  161. ["example/rich_1.wav", "auto"],
  162. ["example/rich_2.wav", "auto"],
  163. # ["example/rich_3.wav", "auto"],
  164. ["example/longwav_1.wav", "auto"],
  165. ["example/longwav_2.wav", "auto"],
  166. ["example/longwav_3.wav", "auto"],
  167. # ["example/longwav_4.wav", "auto"],
  168. ]
  169. html_content = """
  170. <div>
  171. <h2 style="font-size: 22px;margin-left: 0px;">Voice Understanding Model: SenseVoice-Small</h2>
  172. <p style="font-size: 18px;margin-left: 20px;">SenseVoice-Small is an encoder-only speech foundation model designed for rapid voice understanding. It encompasses a variety of features including automatic speech recognition (ASR), spoken language identification (LID), speech emotion recognition (SER), and acoustic event detection (AED). SenseVoice-Small supports multilingual recognition for Chinese, English, Cantonese, Japanese, and Korean. Additionally, it offers exceptionally low inference latency, performing 7 times faster than Whisper-small and 17 times faster than Whisper-large.</p>
  173. <h2 style="font-size: 22px;margin-left: 0px;">Usage</h2> <p style="font-size: 18px;margin-left: 20px;">Upload an audio file or input through a microphone, then select the task and language. the audio is transcribed into corresponding text along with associated emotions (😊 happy, 😡 angry/exicting, 😔 sad) and types of sound events (😀 laughter, 🎼 music, 👏 applause, 🤧 cough&sneeze, 😭 cry). The event labels are placed in the front of the text and the emotion are in the back of the text.</p>
  174. <p style="font-size: 18px;margin-left: 20px;">Recommended audio input duration is below 30 seconds. For audio longer than 30 seconds, local deployment is recommended.</p>
  175. <h2 style="font-size: 22px;margin-left: 0px;">Repo</h2>
  176. <p style="font-size: 18px;margin-left: 20px;"><a href="https://github.com/FunAudioLLM/SenseVoice" target="_blank">SenseVoice</a>: multilingual speech understanding model</p>
  177. <p style="font-size: 18px;margin-left: 20px;"><a href="https://github.com/modelscope/FunASR" target="_blank">FunASR</a>: fundamental speech recognition toolkit</p>
  178. <p style="font-size: 18px;margin-left: 20px;"><a href="https://github.com/FunAudioLLM/CosyVoice" target="_blank">CosyVoice</a>: high-quality multilingual TTS model</p>
  179. </div>
  180. """
  181. def launch():
  182. with gr.Blocks(theme=gr.themes.Soft()) as demo:
  183. # gr.Markdown(description)
  184. gr.HTML(html_content)
  185. with gr.Row():
  186. with gr.Column():
  187. audio_inputs = gr.Audio(label="Upload audio or use the microphone")
  188. with gr.Accordion("Configuration"):
  189. language_inputs = gr.Dropdown(choices=["auto", "zh", "en", "yue", "ja", "ko", "nospeech"],
  190. value="auto",
  191. label="Language")
  192. fn_button = gr.Button("Start", variant="primary")
  193. text_outputs = gr.Textbox(label="Results")
  194. gr.Examples(examples=audio_examples, inputs=[audio_inputs, language_inputs], examples_per_page=20)
  195. fn_button.click(model_inference, inputs=[audio_inputs, language_inputs], outputs=text_outputs)
  196. demo.launch()
  197. if __name__ == "__main__":
  198. # iface.launch()
  199. launch()