Download app.py from UliC/Beat: direct link, hf CLI and curl.
- Browser
- Download file 8.07 kB
-
https://huggingface.co/spaces/UliC/Beat/resolve/main/app.py
- Command line
-
hf download hf://spaces/UliC/Beat/app.py
-
curl -L -o app.py https://huggingface.co/spaces/UliC/Beat/resolve/main/app.py
8.07 kB
| 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""" | |
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> | |
| <style> | |
| body {{ background-color: #121212; color: white; padding: 0; margin: 0; font-family: -apple-system, sans-serif; }} | |
| #player-wrapper {{ position: relative; width: 100%; max-width: 800px; margin: 0 auto; overflow: hidden; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.5);}} | |
| video {{ width: 100%; display: block; }} | |
| #beat-subtitle {{ | |
| position: absolute; | |
| top: 20px; | |
| left: 20px; | |
| font-size: 80px; | |
| font-weight: 900; | |
| color: #ff3b30; | |
| text-shadow: 3px 3px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000; | |
| z-index: 10; | |
| opacity: 0; | |
| transition: opacity 0.1s; | |
| pointer-events: none; | |
| }} | |
| .btn {{ background: #ff5722; color: white; border: none; padding: 18px 0; width: 100%; max-width: 800px; display: block; margin: 15px auto 0; font-size: 20px; font-weight: bold; border-radius: 8px; cursor: pointer; }} | |
| </style> | |
| </head> | |
| <body> | |
| <div id="player-wrapper"> | |
| <video id="dance-video" src="data:{mime_type};base64,{video_b64}" playsinline></video> | |
| <div id="beat-subtitle"></div> | |
| </div> | |
| <button class="btn" id="play-btn">▶ 开始带练 (需取消静音)</button> | |
| <script> | |
| const videoEl = document.getElementById('dance-video'); | |
| const playBtn = document.getElementById('play-btn'); | |
| const subtitleEl = document.getElementById('beat-subtitle'); | |
| const synth = window.speechSynthesis; | |
| const bpm = Number({bpm_value}); | |
| const beatInterval = {beat_interval}; | |
| const autoAnchor = {auto_anchor}; | |
| const offsetBeats = {offset_beats}; | |
| const finalAnchor = autoAnchor + (offsetBeats * beatInterval); | |
| let lastBeatIndex = -1; | |
| let isPlaying = false; | |
| let syncRequestId; | |
| function syncLoop() {{ | |
| if (!isPlaying) return; | |
| const currentTime = videoEl.currentTime; | |
| if (currentTime >= finalAnchor) {{ | |
| const timeSinceAnchor = currentTime - finalAnchor; | |
| const beatIndex = Math.floor(timeSinceAnchor / beatInterval); | |
| if (beatIndex !== lastBeatIndex && beatIndex >= 0) {{ | |
| lastBeatIndex = beatIndex; | |
| const beatNumInEight = (beatIndex % 8) + 1; | |
| subtitleEl.innerText = beatNumInEight; | |
| subtitleEl.style.opacity = 1; | |
| setTimeout(() => {{ subtitleEl.style.opacity = 0; }}, (beatInterval * 1000) * 0.4); | |
| if (synth) {{ | |
| const words = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"]; | |
| const utterance = new SpeechSynthesisUtterance(words[beatNumInEight - 1]); | |
| utterance.lang = 'en-US'; | |
| utterance.rate = 1.8; | |
| utterance.pitch = beatNumInEight === 1 ? 1.5 : 1.0; | |
| synth.speak(utterance); | |
| }} | |
| }} | |
| }} else {{ | |
| subtitleEl.style.opacity = 0; | |
| lastBeatIndex = -1; | |
| }} | |
| syncRequestId = requestAnimationFrame(syncLoop); | |
| }} | |
| playBtn.addEventListener('click', () => {{ | |
| if (videoEl.paused) {{ | |
| videoEl.play(); | |
| isPlaying = true; | |
| playBtn.innerText = '⏸ 暂停'; | |
| if (synth && synth.getVoices().length === 0) synth.speak(new SpeechSynthesisUtterance('')); | |
| syncRequestId = requestAnimationFrame(syncLoop); | |
| }} else {{ | |
| videoEl.pause(); | |
| isPlaying = false; | |
| playBtn.innerText = '▶ 开始带练'; | |
| if (synth) synth.cancel(); | |
| cancelAnimationFrame(syncRequestId); | |
| }} | |
| }}); | |
| videoEl.addEventListener('ended', () => {{ | |
| isPlaying = false; | |
| playBtn.innerText = '▶ 重新带练'; | |
| subtitleEl.style.opacity = 0; | |
| cancelAnimationFrame(syncRequestId); | |
| }}); | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| st.components.v1.html(html_code, height=700, scrolling=True) |