fish_e2e.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import base64
  2. import ctypes
  3. import io
  4. import json
  5. import os
  6. import struct
  7. from dataclasses import dataclass
  8. from enum import Enum
  9. from typing import AsyncGenerator, Union
  10. import httpx
  11. import numpy as np
  12. import ormsgpack
  13. import soundfile as sf
  14. from .schema import (
  15. ServeMessage,
  16. ServeRequest,
  17. ServeTextPart,
  18. ServeVQGANDecodeRequest,
  19. ServeVQGANEncodeRequest,
  20. ServeVQPart,
  21. )
  22. class CustomAudioFrame:
  23. def __init__(self, data, sample_rate, num_channels, samples_per_channel):
  24. if len(data) < num_channels * samples_per_channel * ctypes.sizeof(
  25. ctypes.c_int16
  26. ):
  27. raise ValueError(
  28. "data length must be >= num_channels * samples_per_channel * sizeof(int16)"
  29. )
  30. self._data = bytearray(data)
  31. self._sample_rate = sample_rate
  32. self._num_channels = num_channels
  33. self._samples_per_channel = samples_per_channel
  34. @property
  35. def data(self):
  36. return memoryview(self._data).cast("h")
  37. @property
  38. def sample_rate(self):
  39. return self._sample_rate
  40. @property
  41. def num_channels(self):
  42. return self._num_channels
  43. @property
  44. def samples_per_channel(self):
  45. return self._samples_per_channel
  46. @property
  47. def duration(self):
  48. return self.samples_per_channel / self.sample_rate
  49. def __repr__(self):
  50. return (
  51. f"CustomAudioFrame(sample_rate={self.sample_rate}, "
  52. f"num_channels={self.num_channels}, "
  53. f"samples_per_channel={self.samples_per_channel}, "
  54. f"duration={self.duration:.3f})"
  55. )
  56. class FishE2EEventType(Enum):
  57. SPEECH_SEGMENT = 1
  58. TEXT_SEGMENT = 2
  59. END_OF_TEXT = 3
  60. END_OF_SPEECH = 4
  61. ASR_RESULT = 5
  62. USER_CODES = 6
  63. @dataclass
  64. class FishE2EEvent:
  65. type: FishE2EEventType
  66. frame: np.ndarray = None
  67. text: str = None
  68. vq_codes: list[list[int]] = None
  69. client = httpx.AsyncClient(
  70. timeout=None,
  71. limits=httpx.Limits(
  72. max_connections=None,
  73. max_keepalive_connections=None,
  74. keepalive_expiry=None,
  75. ),
  76. )
  77. class FishE2EAgent:
  78. def __init__(self):
  79. self.llm_url = "http://localhost:8080/v1/chat"
  80. self.vqgan_url = "http://localhost:8080"
  81. self.client = httpx.AsyncClient(timeout=None)
  82. async def get_codes(self, audio_data, sample_rate):
  83. audio_buffer = io.BytesIO()
  84. sf.write(audio_buffer, audio_data, sample_rate, format="WAV")
  85. audio_buffer.seek(0)
  86. # Step 1: Encode audio using VQGAN
  87. encode_request = ServeVQGANEncodeRequest(audios=[audio_buffer.read()])
  88. encode_request_bytes = ormsgpack.packb(
  89. encode_request, option=ormsgpack.OPT_SERIALIZE_PYDANTIC
  90. )
  91. encode_response = await self.client.post(
  92. f"{self.vqgan_url}/v1/vqgan/encode",
  93. data=encode_request_bytes,
  94. headers={"Content-Type": "application/msgpack"},
  95. )
  96. encode_response_data = ormsgpack.unpackb(encode_response.content)
  97. codes = encode_response_data["tokens"][0]
  98. return codes
  99. async def stream(
  100. self,
  101. system_audio_data: np.ndarray | None,
  102. user_audio_data: np.ndarray | None,
  103. sample_rate: int,
  104. num_channels: int,
  105. chat_ctx: dict | None = None,
  106. ) -> AsyncGenerator[bytes, None]:
  107. if system_audio_data is not None:
  108. sys_codes = await self.get_codes(system_audio_data, sample_rate)
  109. else:
  110. sys_codes = None
  111. if user_audio_data is not None:
  112. user_codes = await self.get_codes(user_audio_data, sample_rate)
  113. # Step 2: Prepare LLM request
  114. if chat_ctx is None:
  115. sys_parts = [
  116. ServeTextPart(
  117. text='您是由 Fish Audio 设计的语音助手,提供端到端的语音交互,实现无缝用户体验。首先转录用户的语音,然后使用以下格式回答:"Question: [用户语音]\n\nAnswer: [你的回答]\n"。'
  118. ),
  119. ]
  120. if system_audio_data is not None:
  121. sys_parts.append(ServeVQPart(codes=sys_codes))
  122. chat_ctx = {
  123. "messages": [
  124. ServeMessage(
  125. role="system",
  126. parts=sys_parts,
  127. ),
  128. ],
  129. }
  130. else:
  131. if chat_ctx["added_sysaudio"] is False and sys_codes:
  132. chat_ctx["added_sysaudio"] = True
  133. chat_ctx["messages"][0].parts.append(ServeVQPart(codes=sys_codes))
  134. prev_messages = chat_ctx["messages"].copy()
  135. if user_audio_data is not None:
  136. yield FishE2EEvent(
  137. type=FishE2EEventType.USER_CODES,
  138. vq_codes=user_codes,
  139. )
  140. else:
  141. user_codes = None
  142. request = ServeRequest(
  143. messages=prev_messages
  144. + (
  145. [
  146. ServeMessage(
  147. role="user",
  148. parts=[ServeVQPart(codes=user_codes)],
  149. )
  150. ]
  151. if user_codes
  152. else []
  153. ),
  154. streaming=True,
  155. num_samples=1,
  156. )
  157. # Step 3: Stream LLM response and decode audio
  158. buffer = b""
  159. vq_codes = []
  160. current_vq = False
  161. async def decode_send():
  162. nonlocal current_vq
  163. nonlocal vq_codes
  164. data = np.concatenate(vq_codes, axis=1).tolist()
  165. # Decode VQ codes to audio
  166. decode_request = ServeVQGANDecodeRequest(tokens=[data])
  167. decode_response = await self.client.post(
  168. f"{self.vqgan_url}/v1/vqgan/decode",
  169. data=ormsgpack.packb(
  170. decode_request,
  171. option=ormsgpack.OPT_SERIALIZE_PYDANTIC,
  172. ),
  173. headers={"Content-Type": "application/msgpack"},
  174. )
  175. decode_data = ormsgpack.unpackb(decode_response.content)
  176. # Convert float16 audio data to int16
  177. audio_data = np.frombuffer(decode_data["audios"][0], dtype=np.float16)
  178. audio_data = (audio_data * 32768).astype(np.int16).tobytes()
  179. audio_frame = CustomAudioFrame(
  180. data=audio_data,
  181. samples_per_channel=len(audio_data) // 2,
  182. sample_rate=44100,
  183. num_channels=1,
  184. )
  185. yield FishE2EEvent(
  186. type=FishE2EEventType.SPEECH_SEGMENT,
  187. frame=audio_frame,
  188. vq_codes=data,
  189. )
  190. current_vq = False
  191. vq_codes = []
  192. async with self.client.stream(
  193. "POST",
  194. self.llm_url,
  195. data=ormsgpack.packb(request, option=ormsgpack.OPT_SERIALIZE_PYDANTIC),
  196. headers={"Content-Type": "application/msgpack"},
  197. ) as response:
  198. async for chunk in response.aiter_bytes():
  199. buffer += chunk
  200. while len(buffer) >= 4:
  201. read_length = struct.unpack("I", buffer[:4])[0]
  202. if len(buffer) < 4 + read_length:
  203. break
  204. body = buffer[4 : 4 + read_length]
  205. buffer = buffer[4 + read_length :]
  206. data = ormsgpack.unpackb(body)
  207. if data["delta"] and data["delta"]["part"]:
  208. if current_vq and data["delta"]["part"]["type"] == "text":
  209. async for event in decode_send():
  210. yield event
  211. if data["delta"]["part"]["type"] == "text":
  212. yield FishE2EEvent(
  213. type=FishE2EEventType.TEXT_SEGMENT,
  214. text=data["delta"]["part"]["text"],
  215. )
  216. elif data["delta"]["part"]["type"] == "vq":
  217. vq_codes.append(np.array(data["delta"]["part"]["codes"]))
  218. current_vq = True
  219. if current_vq and vq_codes:
  220. async for event in decode_send():
  221. yield event
  222. yield FishE2EEvent(type=FishE2EEventType.END_OF_TEXT)
  223. yield FishE2EEvent(type=FishE2EEventType.END_OF_SPEECH)
  224. # Example usage:
  225. async def main():
  226. import torchaudio
  227. agent = FishE2EAgent()
  228. # Replace this with actual audio data loading
  229. with open("uz_story_en.m4a", "rb") as f:
  230. audio_data = f.read()
  231. audio_data, sample_rate = torchaudio.load("uz_story_en.m4a")
  232. audio_data = (audio_data.numpy() * 32768).astype(np.int16)
  233. stream = agent.stream(audio_data, sample_rate, 1)
  234. if os.path.exists("audio_segment.wav"):
  235. os.remove("audio_segment.wav")
  236. async for event in stream:
  237. if event.type == FishE2EEventType.SPEECH_SEGMENT:
  238. # Handle speech segment (e.g., play audio or save to file)
  239. with open("audio_segment.wav", "ab+") as f:
  240. f.write(event.frame.data)
  241. elif event.type == FishE2EEventType.ASR_RESULT:
  242. print(event.text, flush=True)
  243. elif event.type == FishE2EEventType.TEXT_SEGMENT:
  244. print(event.text, flush=True, end="")
  245. elif event.type == FishE2EEventType.END_OF_TEXT:
  246. print("\nEnd of text reached.")
  247. elif event.type == FishE2EEventType.END_OF_SPEECH:
  248. print("End of speech reached.")
  249. if __name__ == "__main__":
  250. import asyncio
  251. asyncio.run(main())