You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现React前端传音频及参数至Flask后端,执行Jupyter Notebook返回结果?

实现React→Flask→Jupyter的音频处理流程(无需额外技术)

完全可以不借助额外技术实现你要的流程,核心靠React的表单上传、Flask的请求处理与命令行调用、Jupyter Notebook的参数化执行串联。以下是具体实现步骤和代码示例:

1. React前端:上传音频与参数

用FormData封装音频文件和自定义参数,通过POST请求发送给Flask后端:

import { useState } from 'react';

function AudioProcessor() {
  const [audioFile, setAudioFile] = useState(null);
  const [customParam, setCustomParam] = useState('');
  const [processingResult, setProcessingResult] = useState('');

  const handleFileSelect = (e) => {
    setAudioFile(e.target.files[0]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!audioFile) return;

    const formData = new FormData();
    formData.append('audio', audioFile);
    formData.append('custom_param', customParam);

    try {
      const res = await fetch('http://localhost:5000/process-audio', {
        method: 'POST',
        body: formData,
      });
      const data = await res.json();
      setProcessingResult(data.result);
    } catch (err) {
      console.error('处理请求失败:', err);
    }
  };

  return (
    <div className="audio-uploader">
      <form onSubmit={handleSubmit}>
        <input type="file" accept="audio/*" onChange={handleFileSelect} />
        <input
          type="text"
          value={customParam}
          onChange={(e) => setCustomParam(e.target.value)}
          placeholder="输入处理参数(如MFCC维度)"
          required
        />
        <button type="submit">提交处理</button>
      </form>
      {processingResult && (
        <div className="result">
          <h3>处理结果:</h3>
          <p>{processingResult}</p>
        </div>
      )}
    </div>
  );
}

export default AudioProcessor;

2. Flask后端:接收请求并调用Jupyter

Flask负责接收前端的文件和参数,临时保存音频,通过命令行调用Jupyter Notebook执行处理,最后返回结果:

from flask import Flask, request, jsonify
import subprocess
import os
import tempfile

app = Flask(__name__)

# 开发环境允许跨域,生产环境可通过Nginx配置或flask-cors扩展处理
@app.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    return response

@app.route('/process-audio', methods=['POST'])
def process_audio():
    # 获取前端传来的文件和参数
    audio_file = request.files.get('audio')
    custom_param = request.form.get('custom_param')

    if not audio_file or not custom_param:
        return jsonify({'error': '请提供音频文件和处理参数'}), 400

    # 临时保存音频文件
    with tempfile.NamedTemporaryFile(delete=False, suffix='.' + audio_file.filename.split('.')[-1]) as temp_audio:
        audio_file.save(temp_audio.name)
        temp_audio_path = temp_audio.name

    try:
        # 创建临时文件存储Notebook执行结果和输出Notebook
        output_notebook = tempfile.mktemp(suffix='.ipynb')
        result_txt = tempfile.mktemp(suffix='.txt')

        # 构造Jupyter执行命令,传递音频路径、参数、结果输出路径
        cmd = [
            'jupyter', 'nbconvert', '--to', 'notebook', '--execute',
            '--ExecutePreprocessor.timeout=120',
            '--ExecutePreprocessor.kernel_name=python3',
            '--output', output_notebook,
            f'--ExecutePreprocessor.extra_arguments=["{temp_audio_path}", "{custom_param}", "{result_txt}"]',
            'audio_processing.ipynb'
        ]

        # 执行命令,若失败抛出异常
        subprocess.run(cmd, check=True, capture_output=True, text=True)

        # 读取处理结果
        with open(result_txt, 'r', encoding='utf-8') as f:
            result = f.read().strip()

        return jsonify({'result': result})

    except subprocess.CalledProcessError as e:
        return jsonify({'error': f'Notebook执行出错: {e.stderr}'}), 500
    finally:
        # 清理临时文件,避免磁盘占用
        for file_path in [temp_audio_path, output_notebook, result_txt]:
            if os.path.exists(file_path):
                os.unlink(file_path)

if __name__ == '__main__':
    app.run(debug=True)

3. Jupyter Notebook:音频处理逻辑

编写可接收命令行参数的Notebook,处理音频后将结果写入文本文件,供Flask读取:

import sys
import librosa
import numpy as np

# 从命令行获取传入的参数:音频路径、自定义参数、结果输出路径
audio_path = sys.argv[1]
custom_param = sys.argv[2]
output_path = sys.argv[3]

# 示例处理逻辑:提取音频MFCC特征(可替换为你的实际处理代码)
y, sr = librosa.load(audio_path, sr=None)
mfcc_dim = int(custom_param)
mfcc_features = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=mfcc_dim)

# 构造返回文本
result_text = f"""音频处理完成:
- 采样率: {sr} Hz
- 音频时长: {len(y)/sr:.2f} 秒
- MFCC特征维度: {mfcc_features.shape}
- 特征均值: {np.mean(mfcc_features):.4f}"""

# 将结果写入文件
with open(output_path, 'w', encoding='utf-8') as f:
    f.write(result_text)

关键说明

  • 无需额外中间件:整个流程仅依赖React、Flask、Jupyter的原生功能,没有引入额外的第三方服务或工具。
  • 优化建议:如果追求更高的执行效率,可以直接将Notebook中的处理逻辑提取为Python函数,在Flask中直接调用,省去启动Jupyter内核的开销。
  • 环境依赖:确保Flask环境安装了jupyter、librosa(或你用的音频处理库)等依赖包。

内容的提问来源于stack exchange,提问作者whyamihere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 15:01:20