| 91 | |
| 92 | @app.post("/recognition") |
| 93 | async def api_recognition(audio: UploadFile = File(..., description="audio file")): |
| 94 | suffix = audio.filename.split(".")[-1] |
| 95 | audio_path = f"{args.temp_dir}/{str(uuid.uuid1())}.{suffix}" |
| 96 | async with aiofiles.open(audio_path, "wb") as out_file: |
| 97 | content = await audio.read() |
| 98 | await out_file.write(content) |
| 99 | try: |
| 100 | audio_bytes, _ = ( |
| 101 | ffmpeg.input(audio_path, threads=0) |
| 102 | .output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=16000) |
| 103 | .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True) |
| 104 | ) |
| 105 | except Exception as e: |
| 106 | logger.error(f"读取音频文件发生错误,错误信息:{e}") |
| 107 | return {"msg": "读取音频文件发生错误", "code": 1} |
| 108 | rec_results = model.generate(input=audio_bytes, is_final=True, **param_dict) |
| 109 | # 结果为空 |
| 110 | if len(rec_results[0]["text"] ) == 0: |
| 111 | return {"text": "", "sentences": [], "code": 0} |
| 112 | elif len(rec_results[0]["text"] ) > 0: |
| 113 | # 解析识别结果 |
| 114 | rec_result = rec_results[0] |
| 115 | text = rec_result["text"] |
| 116 | sentences = [] |
| 117 | for sentence in rec_result["sentence_info"]: |
| 118 | # 每句话的时间戳 |
| 119 | sentences.append( |
| 120 | {"text": sentence["text"], "start": sentence["start"], "end": sentence["end"]} |
| 121 | ) |
| 122 | ret = {"text": text, "sentences": sentences, "code": 0} |
| 123 | logger.info(f"识别结果:{ret}") |
| 124 | return ret |
| 125 | else: |
| 126 | logger.info(f"识别结果:{rec_results}") |
| 127 | return {"msg": "未知错误", "code": -1} |
| 128 | |
| 129 | |
| 130 | if __name__ == "__main__": |