Upload 3 files
Browse filesFiles changed (3)
- app.pyAdded+109
- packages.txtAdded+2
- requirements.txtAdded+4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import 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)", type=["mp4"])
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:
video_path = os.path.join(temp_dir, "temp_video.mp4")
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)
# 强制转换类型,防止 JavaScript 崩溃
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)
bass_frames = librosa.onset.onset_detect(onset_envelope=onset_env_bass, sr=sr)
bass_times = [round(float(t), 3) for t in librosa.frames_to_time(bass_frames, sr=sr)]
bpm_value = float(tempo[0])
beat_interval = 60.0 / bpm_value
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
with open(video_path, "rb") as f:
video_b64 = base64.b64encode(f.read()).decode('ascii')
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">
<script src="https://unpkg.com/wavesurfer.js@7"></script>
<script src="https://unpkg.com/wavesurfer.js@7/dist/plugins/regions.min.js"></script>
<style>
body {{ background-color: #121212; color: white; padding: 5px; margin: 0; font-family: sans-serif; }}
#video-container {{ width: 100%; margin-bottom: 10px; }}
video {{ width: 100%; border-radius: 8px; }}
#waveform {{ width: 100vw; margin-left: -5px; background: #1e1e1e; padding: 10px 0; overflow-x: hidden; }}
.btn {{ background: #ff5722; color: white; border: none; padding: 15px 0; width: 100%; font-size: 18px; font-weight: bold; border-radius: 8px; cursor: pointer; margin-top: 10px; }}
.region-beat {{ color: rgba(255,255,255,0.7); font-size: 12px; padding: 2px; }}
.region-one {{ color: #ffffff; font-size: 16px; font-weight: bold; padding: 2px 6px; background: rgba(255,87,34,0.9); border-radius: 4px; }}
</style>
</head>
<body>
<div id="video-container"><video id="dance-video" src="data:video/mp4;base64,{video_b64}" playsinline></video></div>
<div id="waveform"></div>
<button class="btn" id="play-btn">▶ 播放 / 暂停</button>
<script>
const videoEl = document.getElementById('dance-video');
const playBtn = document.getElementById('play-btn');
const bpm = {bpm_value};
const secondsFor8Beats = (60 / bpm) * 8;
const pxPerSec = window.innerWidth / (secondsFor8Beats * 1.5);
const wavesurfer = WaveSurfer.create({{
container: '#waveform', waveColor: '#4a90e2', progressColor: '#ff5722',
cursorColor: '#fff', barWidth: 2, media: videoEl, minPxPerSec: pxPerSec, autoScroll: true
}});
const wsRegions = wavesurfer.registerPlugin(WaveSurfer.Regions.create());
const drumTimes = {drum_times};
const bassTimes = {bass_times};
const baseAnchor = {auto_anchor};
const beatInterval = {beat_interval};
const userOffset = {offset_beats};
const finalAnchor = baseAnchor + (userOffset * beatInterval);
wavesurfer.on('decode', () => {{
drumTimes.forEach(time => {{ wsRegions.addRegion({{ start: time, end: time + 0.05, color: 'rgba(255, 215, 0, 0.2)', drag: false, resize: false }}); }});
bassTimes.forEach(time => {{ wsRegions.addRegion({{ start: time, end: time + 0.15, color: 'rgba(0, 191, 255, 0.15)', drag: false, resize: false }}); }});
for (let i = 0; i < 40; i++) {{
for (let beat = 1; beat <= 8; beat++) {{
let time = finalAnchor + (i * 8 + (beat - 1)) * beatInterval;
if (time >= 0) {{
const isOne = (beat === 1);
wsRegions.addRegion({{
start: time, end: time + 0.02,
color: isOne ? 'transparent' : 'rgba(255, 255, 255, 0.2)',
content: isOne ? '<div class="region-one">🚩 1</div>' : '<div class="region-beat">' + beat + '</div>',
drag: false, resize: false
}});
}}
}}
}}
}});
playBtn.addEventListener('click', () => {{ wavesurfer.playPause(); }});
</script>
</body>
</html>
"""
st.components.v1.html(html_code, height=750, scrolling=True)12ffmpeg
libsndfile11234streamlit
librosa
moviepy==1.0.3
numpyapp.pyAdded+109
packages.txtAdded+2
requirements.txtAdded+4