I created a router using FastAPI python, which returns the StreamingResponse. But, I don't know how to receive and process the StreamingResponse in Unity C# scripts. the router is defined as follows.
@asr_router.post("/recognition_stream")
async def api_recognition_stream(to_simple: int = Body(1, description="是否繁体转简体", embed=True),
remove_pun: int = Body(0, description="是否删除标点符号", embed=True),
language: str = Body("zh", description="设置语言,简写,如果不指定则自动检测语言", embed=True),
task: str = Body("transcribe", description="识别任务类型,支持transcribe和translate", embed=True),
audio: UploadFile = File(..., description="音频文件")):
global model_semaphore
print("接收到数据!开始处理...")
if language == "None": language = None
if model_semaphore is None:
model_semaphore = asyncio.Semaphore(5)
await model_semaphore.acquire()
contents = await audio.read()
data = BytesIO(contents)
generator = recognition(file=data, to_simple=to_simple, remove_pun=remove_pun, language=language, task=task)
background_tasks = BackgroundTasks()
background_tasks.add_task(release_model_semaphore)
print("完成数据处理!开始进行数据推送...")
return StreamingResponse(generator, background=background_tasks)
I've tried to receive the data chunk using UnityWebRequest.downloadHandler.data, but every time I can only get the first chunk.
WWWForm form = new WWWForm();
form.AddBinaryData("audio", audioBytes, "test.mp3", "audio/mpeg");
UnityWebRequest www = UnityWebRequest.Post(m_SpeechRecognizeURL, form);
Debug.Log("PostURL:" + m_SpeechRecognizeURL);
www.SetRequestHeader("accept", "application/json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error sending audio file: " + www.error);
}
else
{
byte[] _responseByte = www.downloadHandler.data;
string responseText = Encoding.Default.GetString(_responseBytes);
// process json received then.
Debug.Log(responseText);
// _callback(_response.text);
}
I am wondering how to get the other chunks in Stream response. Besides, to confirm correctness of the router, I've tested it in python using Request. It can return an iterator so I can iterate it to get data.