Download app.py from peter288/mido: direct link, hf CLI and curl.
- Browser
- Download file 2.72 kB
-
https://huggingface.co/spaces/peter288/mido/resolve/main/app.py
- Command line
-
hf download hf://spaces/peter288/mido/app.py
-
curl -L -o app.py https://huggingface.co/spaces/peter288/mido/resolve/main/app.py
2.72 kB
| import gradio as gr | |
| import os | |
| import tempfile | |
| from midi_utils import process_midi # 我们重用之前的核心处理逻辑 | |
| def process_midi_and_provide_download(input_midi_file): | |
| """ | |
| 这个函数会被Gradio调用。 | |
| 它接收一个上传的文件,调用处理函数,然后返回一个可供下载的新文件路径。 | |
| """ | |
| # 1. 检查用户是否上传了文件 | |
| if input_midi_file is None: | |
| raise gr.Error("错误:请先上传一个MIDI文件!") | |
| print(f"收到的临时文件路径: {input_midi_file.name}") | |
| # 2. 从Gradio提供的临时文件中读取二进制数据 | |
| with open(input_midi_file.name, 'rb') as f: | |
| midi_bytes = f.read() | |
| # 3. 使用我们之前写好的核心MIDI处理函数 | |
| # 这个函数会返回一个包含已处理MIDI数据的内存缓冲区 (BytesIO) | |
| processed_midi_buffer = process_midi(midi_bytes) | |
| # 4. 将处理后的数据保存到一个新的临时文件中 | |
| # 这是必要的,因为Gradio需要一个文件路径来创建下载链接 | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=".mid", prefix="processed-") as temp_output_file: | |
| temp_output_file.write(processed_midi_buffer.getvalue()) | |
| output_file_path = temp_output_file.name | |
| print(f"已处理的文件已保存到: {output_file_path}") | |
| # 5. 返回这个新文件的路径,Gradio会自动生成一个下载链接 | |
| return output_file_path | |
| # --- 使用Gradio Blocks创建用户界面 --- | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| # 标题和描述 | |
| gr.Markdown( | |
| """ | |
| # 🎵 MIDI 处理器 (Gradio版) | |
| 这是一个可以直接在Hugging Face Space中交互的版本。 | |
| """ | |
| ) | |
| gr.Markdown("---") | |
| gr.Markdown("### 步骤 1: 上传你的MIDI文件") | |
| # 文件上传组件 | |
| midi_input = gr.File(label="点击或拖拽MIDI文件到这里", file_types=[".mid", ".midi"]) | |
| gr.Markdown("### 步骤 2: 点击按钮进行处理") | |
| # 处理按钮 | |
| process_button = gr.Button("处理MIDI文件 (所有音符升一个半音)", variant="primary") | |
| gr.Markdown("### 步骤 3: 下载处理后的文件") | |
| # 文件输出/下载组件 | |
| midi_output = gr.File(label="处理结果将出现在这里,点击即可下载") | |
| # 将按钮的点击事件连接到我们的处理函数 | |
| process_button.click( | |
| fn=process_midi_and_provide_download, # 要调用的函数 | |
| inputs=midi_input, # 函数的输入来自哪里 | |
| outputs=midi_output # 函数的输出更新哪个组件 | |
| ) | |
| # 启动Gradio应用 | |
| demo.launch() |