e2e_webui.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import re
  2. import gradio as gr
  3. import numpy as np
  4. from .fish_e2e import FishE2EAgent, FishE2EEventType
  5. from .schema import ServeMessage, ServeTextPart, ServeVQPart
  6. class ChatState:
  7. def __init__(self):
  8. self.conversation = []
  9. self.added_systext = False
  10. self.added_sysaudio = False
  11. def get_history(self):
  12. results = []
  13. for msg in self.conversation:
  14. results.append({"role": msg.role, "content": self.repr_message(msg)})
  15. # Process assistant messages to extract questions and update user messages
  16. for i, msg in enumerate(results):
  17. if msg["role"] == "assistant":
  18. match = re.search(r"Question: (.*?)\n\nResponse:", msg["content"])
  19. if match and i > 0 and results[i - 1]["role"] == "user":
  20. # Update previous user message with extracted question
  21. results[i - 1]["content"] += "\n" + match.group(1)
  22. # Remove the Question/Answer format from assistant message
  23. msg["content"] = msg["content"].split("\n\nResponse: ", 1)[1]
  24. return results
  25. def repr_message(self, msg: ServeMessage):
  26. response = ""
  27. for part in msg.parts:
  28. if isinstance(part, ServeTextPart):
  29. response += part.text
  30. elif isinstance(part, ServeVQPart):
  31. response += f"<audio {len(part.codes[0]) / 21:.2f}s>"
  32. return response
  33. def clear_fn():
  34. return [], ChatState(), None, None, None
  35. async def process_audio_input(
  36. sys_audio_input, sys_text_input, audio_input, state: ChatState, text_input: str
  37. ):
  38. if audio_input is None and not text_input:
  39. raise gr.Error("No input provided")
  40. agent = FishE2EAgent() # Create new agent instance for each request
  41. # Convert audio input to numpy array
  42. if isinstance(audio_input, tuple):
  43. sr, audio_data = audio_input
  44. elif text_input:
  45. sr = 44100
  46. audio_data = None
  47. else:
  48. raise gr.Error("Invalid audio format")
  49. if isinstance(sys_audio_input, tuple):
  50. sr, sys_audio_data = sys_audio_input
  51. elif text_input:
  52. sr = 44100
  53. sys_audio_data = None
  54. def append_to_chat_ctx(
  55. part: ServeTextPart | ServeVQPart, role: str = "assistant"
  56. ) -> None:
  57. if not state.conversation or state.conversation[-1].role != role:
  58. state.conversation.append(ServeMessage(role=role, parts=[part]))
  59. else:
  60. state.conversation[-1].parts.append(part)
  61. if state.added_systext is False and sys_text_input:
  62. state.added_systext = True
  63. append_to_chat_ctx(ServeTextPart(text=sys_text_input), role="system")
  64. if text_input:
  65. append_to_chat_ctx(ServeTextPart(text=text_input), role="user")
  66. audio_data = None
  67. result_audio = b""
  68. async for event in agent.stream(
  69. sys_audio_data,
  70. audio_data,
  71. sr,
  72. 1,
  73. chat_ctx={
  74. "messages": state.conversation,
  75. "added_sysaudio": state.added_sysaudio,
  76. },
  77. ):
  78. if event.type == FishE2EEventType.USER_CODES:
  79. append_to_chat_ctx(ServeVQPart(codes=event.vq_codes), role="user")
  80. elif event.type == FishE2EEventType.SPEECH_SEGMENT:
  81. result_audio += event.frame.data
  82. np_audio = np.frombuffer(result_audio, dtype=np.int16)
  83. append_to_chat_ctx(ServeVQPart(codes=event.vq_codes))
  84. yield state.get_history(), (44100, np_audio), None, None
  85. elif event.type == FishE2EEventType.TEXT_SEGMENT:
  86. append_to_chat_ctx(ServeTextPart(text=event.text))
  87. if result_audio:
  88. np_audio = np.frombuffer(result_audio, dtype=np.int16)
  89. yield state.get_history(), (44100, np_audio), None, None
  90. else:
  91. yield state.get_history(), None, None, None
  92. np_audio = np.frombuffer(result_audio, dtype=np.int16)
  93. yield state.get_history(), (44100, np_audio), None, None
  94. async def process_text_input(
  95. sys_audio_input, sys_text_input, state: ChatState, text_input: str
  96. ):
  97. async for event in process_audio_input(
  98. sys_audio_input, sys_text_input, None, state, text_input
  99. ):
  100. yield event
  101. def create_demo():
  102. with gr.Blocks() as demo:
  103. state = gr.State(ChatState())
  104. with gr.Row():
  105. # Left column (70%) for chatbot and notes
  106. with gr.Column(scale=7):
  107. chatbot = gr.Chatbot(
  108. [],
  109. elem_id="chatbot",
  110. bubble_full_width=False,
  111. height=600,
  112. type="messages",
  113. )
  114. # notes = gr.Markdown(
  115. # """
  116. # # Fish Agent
  117. # 1. 此Demo为Fish Audio自研端到端语言模型Fish Agent 3B版本.
  118. # 2. 你可以在我们的官方仓库找到代码以及权重,但是相关内容全部基于 CC BY-NC-SA 4.0 许可证发布.
  119. # 3. Demo为早期灰度测试版本,推理速度尚待优化.
  120. # # 特色
  121. # 1. 该模型自动集成ASR与TTS部分,不需要外挂其它模型,即真正的端到端,而非三段式(ASR+LLM+TTS).
  122. # 2. 模型可以使用reference audio控制说话音色.
  123. # 3. 可以生成具有较强情感与韵律的音频.
  124. # """
  125. # )
  126. notes = gr.Markdown(
  127. """
  128. # Fish Agent
  129. 1. This demo is Fish Audio's self-researh end-to-end language model, Fish Agent version 3B.
  130. 2. You can find the code and weights in our official repo in [gitub](https://github.com/fishaudio/fish-speech) and [hugging face](https://huggingface.co/fishaudio/fish-agent-v0.1-3b), but the content is released under a CC BY-NC-SA 4.0 licence.
  131. 3. The demo is an early alpha test version, the inference speed needs to be optimised.
  132. # Features
  133. 1. The model automatically integrates ASR and TTS parts, no need to plug-in other models, i.e., true end-to-end, not three-stage (ASR+LLM+TTS).
  134. 2. The model can use reference audio to control the speech timbre.
  135. 3. The model can generate speech with strong emotion.
  136. """
  137. )
  138. # Right column (30%) for controls
  139. with gr.Column(scale=3):
  140. sys_audio_input = gr.Audio(
  141. sources=["upload"],
  142. type="numpy",
  143. label="Give a timbre for your assistant",
  144. )
  145. sys_text_input = gr.Textbox(
  146. label="What is your assistant's role?",
  147. value="You are a voice assistant created by Fish Audio, offering end-to-end voice interaction for a seamless user experience. You are required to first transcribe the user's speech, then answer it in the following format: 'Question: [USER_SPEECH]\n\nAnswer: [YOUR_RESPONSE]\n'. You are required to use the following voice in this conversation.",
  148. type="text",
  149. )
  150. audio_input = gr.Audio(
  151. sources=["microphone"], type="numpy", label="Speak your message"
  152. )
  153. text_input = gr.Textbox(label="Or type your message", type="text")
  154. output_audio = gr.Audio(label="Assistant's Voice", type="numpy")
  155. send_button = gr.Button("Send", variant="primary")
  156. clear_button = gr.Button("Clear")
  157. # Event handlers
  158. audio_input.stop_recording(
  159. process_audio_input,
  160. inputs=[sys_audio_input, sys_text_input, audio_input, state, text_input],
  161. outputs=[chatbot, output_audio, audio_input, text_input],
  162. show_progress=True,
  163. )
  164. send_button.click(
  165. process_text_input,
  166. inputs=[sys_audio_input, sys_text_input, state, text_input],
  167. outputs=[chatbot, output_audio, audio_input, text_input],
  168. show_progress=True,
  169. )
  170. text_input.submit(
  171. process_text_input,
  172. inputs=[sys_audio_input, sys_text_input, state, text_input],
  173. outputs=[chatbot, output_audio, audio_input, text_input],
  174. show_progress=True,
  175. )
  176. clear_button.click(
  177. clear_fn,
  178. inputs=[],
  179. outputs=[chatbot, state, audio_input, output_audio, text_input],
  180. )
  181. return demo
  182. if __name__ == "__main__":
  183. demo = create_demo()
  184. demo.launch(server_name="127.0.0.1", server_port=7860, share=True)