import streamlit as st import librosa import base64 import os import tempfile import numpy as np from moviepy.editor import VideoFileClip st.set_page_config(page_title="舞蹈卡点教练", layout="wide") st.title("🕺 虚拟领舞教练系统") uploaded_file = st.file_uploader("上传视频 (MP4/MOV)", type=["mp4", "mov", "MOV"]) st.markdown("### 🎛️ 第一拍校准器") offset_beats = st.slider("如果机器找的第一拍偏了,请左右滑动微调 (单位: 拍)", min_value=-4.0, max_value=4.0, value=0.0, step=1.0) if uploaded_file is not None: with st.spinner("⏳ 正在分析鼓点与节拍结构..."): with tempfile.TemporaryDirectory() as temp_dir: file_ext = os.path.splitext(uploaded_file.name)[1].lower() video_path = os.path.join(temp_dir, f"temp_video{file_ext}") audio_path = os.path.join(temp_dir, "temp_audio.wav") with open(video_path, "wb") as f: f.write(uploaded_file.getbuffer()) clip = VideoFileClip(video_path) clip.audio.write_audiofile(audio_path, logger=None) y, sr = librosa.load(audio_path) _, y_percussive = librosa.effects.hpss(y) tempo, drum_frames = librosa.beat.beat_track(y=y_percussive, sr=sr) drum_times = [round(float(t), 3) for t in librosa.frames_to_time(drum_frames, sr=sr)] onset_env_bass = librosa.onset.onset_strength(y=y, sr=sr, fmax=250, n_mels=16) search_window_frames = librosa.time_to_frames(10.0, sr=sr) if len(onset_env_bass) > 0: max_energy_frame = np.argmax(onset_env_bass[:search_window_frames]) guessed_time = librosa.frames_to_time(max_energy_frame, sr=sr) if drum_times: nearest_idx = np.argmin(np.abs(np.array(drum_times) - guessed_time)) auto_anchor = drum_times[nearest_idx] else: auto_anchor = guessed_time else: auto_anchor = 0.0 bpm_value = float(tempo[0]) beat_interval = 60.0 / bpm_value with open(video_path, "rb") as f: video_b64 = base64.b64encode(f.read()).decode('ascii') mime_type = "video/quicktime" if file_ext == ".mov" else "video/mp4" st.success(f"✅ 节拍分析完毕!当前 BPM: {bpm_value:.1f}") html_code = f"""
""" st.components.v1.html(html_code, height=700, scrolling=True)