@app.post("/inference") async def inferenceendpoint( audiofile: UploadFile = File(...),…
- User
@app.post("/inference") async def inference_endpoint( audio_file: UploadFile = File(...), video_file: UploadFile = File(...), bbox_shift: float = Form(0), batch_size_args: int = Form(8), use_saved_coord_args: bool = Form(False), trim_video: bool = Form(False), ): # 保存上传的文件到临时目录 with tempfile.TemporaryDirectory() as tmp_dir: audio_temp_path = os.path.join( tmp_dir, f"audio{os.path.splitext(audio_file.filename)[1]}") with open(audio_temp_path, 'wb') as f: content = await audio_file.read() f.write(content)
video_temp_path = os.path.join( tmp_dir, f"video{os.path.splitext(video_file.filename)[1]}") with open(video_temp_path, 'wb') as f: content = await video_file.read() f.write(content) # 调用推理函数 output_video_path, bbox_shift_text = inference( audio_path=audio_temp_path, video_path=video_temp_path, bbox_shift=bbox_shift, batch_size_args=batch_size_args, use_saved_coord_args=use_saved_coord_args, trim_video=trim_video, result_dir=tmp_dir ) # 将生成的视频作为响应返回 return FileResponse( output_video_path, media_type='video/mp4', filename=os.path.basename(output_video_path) ) 针对上面代码写一个js调用示例代码 - Assistant
下面是一个使用 JavaScript 调用上述 FastAPI
/inference接口的示例代码。这个示例使用了现代浏览器支持的fetchAPI,并使用FormData对象来构建包含文件和表单数据的请求。// 选择需要上传的音频和视频文件 const audioInput = document.querySelector('#audioInput'); const videoInput = document.querySelector('#videoInput'); // 设置表单中的其他参数 const bbox_shift = 0; // Adjust as needed const batch_size_args = 8; // Adjust as needed const use_saved_coord_args = false; // Adjust as needed const trim_video = false; // Adjust as needed // 当用户点击提交按钮时触发请求 document.querySelector('#submitButton').addEventListener('click', async () => { // 确保已经选择了文件 if (audioInput.files.length === 0 || videoInput.files.length === 0) { alert('请先选择音频和视频文件!'); return; } // 创建一个 FormData 对象 const formData = new FormData(); // 添加文件到 FormData formData.append('audio_file', audioInput.files[0]); formData.append('video_file', videoInput.files[0]); // 添加其他表单数据 formData.append('bbox_shift', bbox_shift); formData.append('batch_size_args', batch_size_args); formData.append('use_saved_coord_args', use_saved_coord_args); formData.append('trim_video', trim_video); try { // 发送 POST 请求到 /inference 接口 const response = await fetch('https://yourserver.com/inference', { method: 'POST', body: formData }); // 检查响应是否成功 if (!response.ok) { throw new Error(`服务器返回错误状态: ${response.status}`); } // 获取响应的Blob数据(视频文件) const blob = await response.blob(); // 创建一个下载链接 const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; // 从响应头或其他方式获取文件名 const filename = 'output_video.mp4'; a.download = filename; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); alert('视频已下载!'); } catch (error) { console.error('请求出错:', error); alert('请求出错,请检查控制台日志。'); } });HTML 部分示例:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>调用推理接口示例</title> </head> <body> <h1>调用推理接口示例</h1> <label for="audioInput">选择音频文件:</label> <input type="file" id="audioInput" accept="audio/*"><br><br> <label for="videoInput">选择视频文件:</label> <input type="file" id="videoInput" accept="video/*"><br><br> <!-- 可以添加更多的输入来调整参数 --> <button id="submitButton">提交</button> <script src="your_script.js"></script> </body> </html>说明:
- 文件选择: 用户通过
<input type="file">元素选择要上传的音频和视频文件。 - FormData 对象: 用于构造包含文件和其他表单数据的请求数据。
- fetch API: 使用
fetch发送 POST 请求到服务器的/inference端点。 - 响应处理: 接口返回一个视频文件,使用
response.blob()获取二进制数据,然后创建一个临时下载链接,模拟点击来下载文件。 - 错误处理: 捕获并处理请求中的错误,向用户提示。
注意事项:
- 将
'https://yourserver.com/inference'替换为实际服务器的 URL。 - 确保服务器支持跨域请求(CORS),如果前端和后端不在同一域名下,需要在后端设置适当的 CORS 头。
- 根据需要调整表单参数的值,或者将其替换为用户可输入的表单元素。
后端 CORS 设置(如有需要):
如果前端页面和后端接口不在同一个域名,需要在 FastAPI 应用中添加 CORS 中间件:
from fastapi.middleware.cors import CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # 或者指定允许的域名列表,如 ["https://your-frontend.com"] allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )这样设置后,前端才能成功调用后端接口。
升级 fetch 到 axios(可选):
如果您更喜欢使用
axios库,可以用以下方式替换 fetch 请求:// 首先引入 axios <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> // 使用 axios 发送请求 axios.post('https://yourserver.com/inference', formData, { headers: { 'Content-Type': 'multipart/form-data' }, responseType: 'blob' // 确保响应类型为 blob }) .then(response => { const url = window.URL.createObjectURL(new Blob([response.data])); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; const filename = 'output_video.mp4'; // 可从响应头获取 a.download = filename; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); alert('视频已下载!'); }) .catch(error => { console.error('请求出错:', error); alert('请求出错,请检查控制台日志。'); });总结:
以上示例展示了如何在前端使用 JavaScript 调用 FastAPI 后端的文件上传和下载接口。通过使用
FormData和fetch/axios,可以方便地在浏览器中与后端进行交互,上传文件并接收处理后的结果。 - 文件选择: 用户通过