Download app.py from Vampont/NVH: direct link, hf CLI and curl.
- Browser
- Download file 5.93 kB
-
https://huggingface.co/spaces/Vampont/NVH/resolve/main/app.py
- Command line
-
hf download hf://spaces/Vampont/NVH/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Vampont/NVH/resolve/main/app.py
5.93 kB
| """NVH Spectrum — HuggingFace Spaces 部署入口。 | |
| 与本地 web_app.py 的差异: | |
| * 监听 0.0.0.0:7860(HF Spaces 默认暴露端口) | |
| * 上传/结果文件放在 /tmp 下,HF 容器中可写且无持久化负担 | |
| * 关闭 debug,避免 reloader 在容器中启动两次 | |
| """ | |
| import os | |
| import uuid | |
| import threading | |
| import math | |
| from pathlib import Path | |
| from flask import Flask, render_template, request, jsonify, send_file | |
| from werkzeug.utils import secure_filename | |
| from nvh_spectrum import analyze_audio | |
| WORK_ROOT = Path(os.environ.get("NVH_WORK_DIR", "/tmp/nvh")) | |
| UPLOAD_DIR = WORK_ROOT / "uploads" | |
| RESULT_DIR = WORK_ROOT / "results" | |
| UPLOAD_DIR.mkdir(parents=True, exist_ok=True) | |
| RESULT_DIR.mkdir(parents=True, exist_ok=True) | |
| ALLOWED_EXTENSIONS = {"mp4", "mov", "avi", "mkv", "mp3", "m4a", "wav", "flac", "ogg", "wmv"} | |
| DEFAULT_PLOT_FREQ_RANGE = (0.0, 1000.0) | |
| DEFAULT_PLOT_TIME_RANGE = (-10.0, 65.0) | |
| DEFAULT_PLOT_DB_RANGE = (0.0, None) | |
| app = Flask(__name__) | |
| app.config["MAX_CONTENT_LENGTH"] = 200 * 1024 * 1024 # HF 免费实例内存有限,调小到 200MB | |
| def allowed_file(filename: str) -> bool: | |
| return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS | |
| def _parse_axis_value(value: str | None, default: float | None, label: str) -> float | None: | |
| if value is None or value == "": | |
| return default | |
| try: | |
| parsed = float(value) | |
| except ValueError as exc: | |
| raise ValueError(f"{label}必须是数字") from exc | |
| if not math.isfinite(parsed): | |
| raise ValueError(f"{label}必须是有效数字") | |
| return parsed | |
| def _parse_axis_range(prefix: str, default: tuple[float, float], label: str) -> tuple[float, float]: | |
| axis_min = _parse_axis_value(request.form.get(f"{prefix}_min"), default[0], f"{label}下限") | |
| axis_max = _parse_axis_value(request.form.get(f"{prefix}_max"), default[1], f"{label}上限") | |
| if axis_min >= axis_max: | |
| raise ValueError(f"{label}下限必须小于上限") | |
| return axis_min, axis_max | |
| def _parse_color_range(default: tuple[float, float | None]) -> tuple[float, float | None]: | |
| color_min = _parse_axis_value(request.form.get("color_min"), default[0], "色标下限") | |
| color_max = _parse_axis_value(request.form.get("color_max"), default[1], "色标上限") | |
| if color_max is not None and color_min >= color_max: | |
| raise ValueError("色标下限必须小于上限") | |
| return color_min, color_max | |
| def index(): | |
| return render_template("index.html") | |
| def analyze(): | |
| if "file" not in request.files: | |
| return jsonify({"error": "没有上传文件"}), 400 | |
| file = request.files["file"] | |
| if file.filename == "": | |
| return jsonify({"error": "没有选择文件"}), 400 | |
| if not allowed_file(file.filename): | |
| return jsonify({"error": "不支持的文件格式"}), 400 | |
| try: | |
| plot_time_range = _parse_axis_range("time", DEFAULT_PLOT_TIME_RANGE, "时间轴") | |
| plot_freq_range = _parse_axis_range("freq", DEFAULT_PLOT_FREQ_RANGE, "频率轴") | |
| plot_db_range = _parse_color_range(DEFAULT_PLOT_DB_RANGE) | |
| except ValueError as exc: | |
| return jsonify({"error": str(exc)}), 400 | |
| if plot_freq_range[0] < 0: | |
| return jsonify({"error": "频率轴下限不能小于 0"}), 400 | |
| if plot_db_range[0] < 0: | |
| return jsonify({"error": "色标下限不能小于 0"}), 400 | |
| job_id = uuid.uuid4().hex[:8] | |
| filename = secure_filename(file.filename) | |
| ext = filename.rsplit(".", 1)[1].lower() | |
| input_path = UPLOAD_DIR / f"{job_id}_input.{ext}" | |
| output_path = RESULT_DIR / f"{job_id}_result.png" | |
| file.save(str(input_path)) | |
| def run_analysis(): | |
| try: | |
| analyze_audio( | |
| str(input_path), | |
| fft_size=32768, | |
| a_weighting=True, | |
| db_scale=True, | |
| freq_min=0.0, | |
| freq_max=None, | |
| plot_freq_range=plot_freq_range, | |
| plot_time_range=plot_time_range, | |
| plot_db_range=plot_db_range, | |
| save_fig=str(output_path), | |
| ) | |
| (RESULT_DIR / f"{job_id}_done").touch() | |
| except Exception as e: | |
| (RESULT_DIR / f"{job_id}_error").write_text(str(e), encoding="utf-8") | |
| finally: | |
| try: | |
| input_path.unlink() | |
| except Exception: | |
| pass | |
| threading.Thread(target=run_analysis, daemon=True).start() | |
| return jsonify({"job_id": job_id, "status": "processing"}) | |
| def result(job_id): | |
| done_file = RESULT_DIR / f"{job_id}_done" | |
| error_file = RESULT_DIR / f"{job_id}_error" | |
| if error_file.exists(): | |
| return jsonify({"status": "error", "message": error_file.read_text(encoding="utf-8")}), 400 | |
| if not done_file.exists(): | |
| return jsonify({"status": "processing"}) | |
| output_path = RESULT_DIR / f"{job_id}_result.png" | |
| if not output_path.exists(): | |
| return jsonify({"status": "error", "message": "结果文件丢失"}), 400 | |
| return jsonify({"status": "done", "job_id": job_id}) | |
| def get_image(job_id): | |
| output_path = RESULT_DIR / f"{job_id}_result.png" | |
| if not output_path.exists(): | |
| return jsonify({"error": "文件不存在"}), 404 | |
| return send_file(str(output_path), mimetype="image/png") | |
| def cleanup(job_id): | |
| for folder in [UPLOAD_DIR, RESULT_DIR]: | |
| for f in folder.glob(f"{job_id}_*"): | |
| try: | |
| f.unlink() | |
| except Exception: | |
| pass | |
| return jsonify({"status": "cleaned"}) | |
| def healthz(): | |
| return "ok", 200 | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", 7860)) | |
| app.run(host="0.0.0.0", port=port, debug=False) | |