oddsilk
Update web UI components and logic for improved user interaction.
9c7ff98
Raw History Blame Contribute Delete
16.3 kB
import gradio as gr
import os
import tempfile
import subprocess
import sys
import shutil
import numpy as np
import librosa
import soundfile as sf
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import traceback
from auto_mapper import run_pipeline
LIBRARY_DIR = os.path.join(os.getcwd(), "library")
os.makedirs(LIBRARY_DIR, exist_ok=True)
def get_cached_songs():
songs = []
if os.path.exists(LIBRARY_DIR):
for f in os.listdir(LIBRARY_DIR):
if f.lower().endswith(('.wav', '.mp3')):
songs.append(f)
return sorted(songs)
def generate_validation_data(audio_path, onsets, out_dir, bpm, offset=0.0):
"""
λΆ„μ„λœ Onset 데이터λ₯Ό λ°”νƒ•μœΌλ‘œ ν‹±(Click) μ‚¬μš΄λ“œλ₯Ό μΆ”κ°€ν•œ κ²€μ¦μš© μ˜€λ””μ˜€ 파일과,
Waveform & Piano Roll 동기화 μ‹œκ°ν™” Plotly Figureλ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
"""
times = [float(t) for t, p in onsets]
# 1. 원본 μ˜€λ””μ˜€ λ‘œλ“œ 및 ν‹± νŠΈλž™ 생성
y, sr = librosa.load(audio_path, sr=22050)
click_track = librosa.clicks(times=times, sr=sr, length=len(y))
# 원본(μ•½κ°„ μ€„μž„) + ν‹±(κ°•ν•˜κ²Œ) 믹슀
y_mixed = (y * 0.7) + (click_track * 1.5)
# μ •κ·œν™”ν•˜μ—¬ 클리핑 λ°©μ§€
max_val = np.max(np.abs(y_mixed))
if max_val > 0:
y_mixed = y_mixed / max_val
mixed_path = os.path.join(out_dir, "validation_mixed.wav")
sf.write(mixed_path, y_mixed, sr)
# 2. Plotly νŒŒν˜• 생성
# λΈŒλΌμš°μ € λ©”λͺ¨λ¦¬μ™€ λ Œλ”λ§ μ„±λŠ₯을 μœ„ν•΄ λ‹€μš΄μƒ˜ν”Œλ§ (1μ΄ˆμ— 100개 포인트 정도)
down_factor = max(1, sr // 100)
y_down = y[::down_factor]
time_axis = np.linspace(0, len(y)/sr, len(y_down))
# Ableton Live μŠ€νƒ€μΌλ‘œ 상단: μ˜€λ””μ˜€, ν•˜λ‹¨: λ―Έλ””μ˜ λ…λ¦½λœ νŠΈλž™ 생성
fig = make_subplots(
rows=2, cols=1,
shared_xaxes=True,
vertical_spacing=0.03,
row_heights=[0.5, 0.5]
)
# [Track 1] μ˜€λ””μ˜€ νŒŒν˜• (에이블톀 λŠλ‚Œμ˜ 밝은 μ΄ˆλ‘μƒ‰)
fig.add_trace(go.Scatter(
x=time_axis,
y=y_down,
mode='lines',
name="μ˜€λ””μ˜€ 원본",
line=dict(color='#00ff88', width=1),
hoverinfo='none'
), row=1, col=1)
# [Track 2] MIDI ν”Όμ•„λ…Έ λ‘€ (에이블톀 λŠλ‚Œμ˜ νŒŒλž€μƒ‰ 블둝 ν˜•νƒœ)
x_midi = []
y_midi = []
# Plotlyμ—μ„œ λŠμ–΄μ§€λŠ” μ„ (블둝)을 그리기 μœ„ν•΄ None을 쀑간에 μ‚½μž…
for t, p in onsets:
x_midi.extend([t, t + 0.08, None]) # 각 λ…ΈνŠΈμ˜ μ‹œκ°μ  길이λ₯Ό 0.08초둜 ν‘œν˜„
y_midi.extend([p, p, None])
fig.add_trace(go.Scatter(
x=x_midi,
y=y_midi,
mode='lines',
name="MIDI 타격 지점",
line=dict(color='#3399ff', width=16),
hovertemplate='μ‹œκ°„: %{x:.3f}초<br>ν”ΌμΉ˜: %{y}<extra></extra>'
), row=2, col=1)
# λ ˆμ΄μ•„μ›ƒ μ΄ˆκΈ°ν™” 및 λ””μžμΈ
min_pitch = min([p for _, p in onsets]) if onsets else 60
max_pitch = max([p for _, p in onsets]) if onsets else 64
total_time = len(y) / sr
beat_duration = 60.0 / bpm
measure_duration = beat_duration * 4.0 # 4/4 λ°•μž κΈ°μ€€
fig.update_layout(
title=dict(text=f"<b>Ableton Live μŠ€νƒ€μΌ 닀쀑 νŠΈλž™ 동기화 λ·° (BPM: {bpm})</b>", font=dict(color="#e9ecef")),
template='plotly_dark',
height=450,
margin=dict(l=40, r=20, t=50, b=40),
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(255,255,255,0.03)',
showlegend=False
)
# X/YμΆ• λ””μžμΈ μ‘°μ •: λ°•μž(Beat) λ‹¨μœ„λ‘œ 일반 κ·Έλ¦¬λ“œ ν‘œμ‹œ
fig.update_xaxes(
showgrid=True, gridcolor='rgba(255,255,255,0.1)', gridwidth=1,
tickmode='linear', tick0=offset, dtick=beat_duration,
title="μ‹œκ°„ (초)", row=2, col=1
)
fig.update_xaxes(
showgrid=True, gridcolor='rgba(255,255,255,0.1)', gridwidth=1,
tickmode='linear', tick0=offset, dtick=beat_duration,
row=1, col=1
)
# λ§ˆλ””(Measure) μ‹œμž‘μ λ§ˆλ‹€ ꡡ은 μ„Έλ‘œμ„  μΆ”κ°€ (μœ„μ•„λž˜ νŠΈλž™ 전체 관톡)
measure_time = offset
while measure_time <= total_time:
fig.add_vline(x=measure_time, line_width=2, line_color='rgba(255, 255, 255, 0.5)')
measure_time += measure_duration
# μ˜€λ””μ˜€ νŠΈλž™ YμΆ• λ””μžμΈ
fig.update_yaxes(showgrid=False, showticklabels=False, range=[-1.1, 1.1], row=1, col=1)
# MIDI νŠΈλž™ YμΆ• λ””μžμΈ (ν•΄λ‹Ήν•˜λŠ” ν”ΌμΉ˜λ§Œ 보이도둝)
fig.update_yaxes(showgrid=True, gridcolor='rgba(255,255,255,0.1)', title="ν”ΌμΉ˜", range=[min_pitch - 2, max_pitch + 2], row=2, col=1)
return mixed_path, fig
def process_audio(input_mode, audio_upload, audio_cached, bpm, target_stem, mode, quantize_strength, offset, shift, threshold_multiplier, min_votes, tolerance_ms, sr):
try:
if input_mode == "μƒˆ μ˜€λ””μ˜€ μ—…λ‘œλ“œ":
if not audio_upload:
return None, None, None, "⚠️ 였λ₯˜: μ˜€λ””μ˜€ νŒŒμΌμ„ λ¨Όμ € μ—…λ‘œλ“œν•΄μ£Όμ„Έμš”."
audio_path = audio_upload
safe_name = os.path.basename(audio_path)
library_audio_path = os.path.join(LIBRARY_DIR, safe_name)
if audio_path != library_audio_path:
shutil.copy(audio_path, library_audio_path)
audio_path_to_use = library_audio_path
base_name = os.path.splitext(safe_name)[0]
else:
if not audio_cached:
return None, None, None, "⚠️ 였λ₯˜: μΊμ‹œλœ 곑을 μ„ νƒν•΄μ£Όμ„Έμš”."
audio_path_to_use = os.path.join(LIBRARY_DIR, audio_cached)
base_name = os.path.splitext(audio_cached)[0]
if not bpm or bpm <= 0:
return None, None, None, "⚠️ 였λ₯˜: μ˜¬λ°”λ₯Έ BPM(예: 120, 150)을 μž…λ ₯ν•΄μ£Όμ„Έμš”."
out_dir = tempfile.mkdtemp()
out_path = os.path.join(LIBRARY_DIR, f"{base_name}.mid")
onsets = run_pipeline(
audio_path=audio_path_to_use,
output_path=out_path,
bpm=float(bpm),
threshold_multiplier=float(threshold_multiplier),
quantize_strength=quantize_strength,
sr=int(sr),
target_stem=target_stem,
mode=mode,
min_votes=int(min_votes),
tolerance_ms=float(tolerance_ms),
offset=float(offset),
shift=float(shift)
)
if os.path.exists(out_path):
mixed_path, fig = generate_validation_data(audio_path_to_use, onsets, out_dir, float(bpm), float(offset))
return out_path, mixed_path, fig, "βœ… μž‘μ—…μ΄ μ„±κ³΅μ μœΌλ‘œ μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€."
else:
return None, None, None, "⚠️ 였λ₯˜: MIDI 파일 생성에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. (좜λ ₯ 파일 μ—†μŒ)"
except Exception as e:
error_log = traceback.format_exc()
print(error_log)
return None, None, None, f"❌ μ‹œμŠ€ν…œ 였λ₯˜ λ°œμƒ! μ•„λž˜ ν…μŠ€νŠΈλ₯Ό λ³΅μ‚¬ν•˜μ—¬ κ°œλ°œμžμ—κ²Œ μ „λ‹¬ν•΄μ£Όμ„Έμš”:\n\n{error_log}"
# ─────────────────────────────────────────────
# κ³ κΈ‰μŠ€λŸ¬μš΄ λ””μžμΈμ„ μœ„ν•œ Custom CSS (닀크 μŠ€ν‚¨ κ°•μ œ κ³ μ •)
# ─────────────────────────────────────────────
custom_css = """
.gradio-container {
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%) !important;
font-family: 'Inter', 'Apple SD Gothic Neo', sans-serif !important;
color: #e9ecef !important;
}
/* μ‹œμŠ€ν…œ 라이트λͺ¨λ“œμ—μ„œλ„ μž…λ ₯μ°½ 및 νŒ¨λ„μ΄ μ–΄λ‘‘κ²Œ λ Œλ”λ§λ˜κ²Œ κ°•μ œ μ§€μ • */
.gradio-container input,
.gradio-container textarea,
.gradio-container select,
.gradio-container .gr-box,
.gradio-container .gr-input,
.gradio-container .gr-dropdown,
.gradio-container .gr-form,
.gradio-container .gr-panel,
.gradio-container [data-testid="textbox"] {
background-color: rgba(255, 255, 255, 0.08) !important;
color: #e9ecef !important;
border-color: rgba(255, 255, 255, 0.1) !important;
}
/* ν…μŠ€νŠΈ μš”μ†Œλ“€ 가독성을 μœ„ν•΄ μ™„μ „ 흰색 κ³„μ—΄λ‘œ λ³€ν™˜ */
.gradio-container label,
.gradio-container span,
.gradio-container p {
color: #e9ecef !important;
}
/* λ“œλ‘­λ‹€μš΄ 리슀트 ν•­λͺ© 가독성 보정 */
ul.options > li {
background-color: #1a1a2e !important;
color: #e9ecef !important;
}
ul.options > li:hover, ul.options > li.selected {
background-color: #4361ee !important;
}
.glass-panel {
background: rgba(255, 255, 255, 0.05) !important;
backdrop-filter: blur(10px) !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
border-radius: 20px !important;
padding: 2rem !important;
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37) !important;
}
h1 {
background: linear-gradient(90deg, #4cc9f0, #4361ee) !important;
-webkit-background-clip: text !important;
-webkit-text-fill-color: transparent !important;
font-weight: 800 !important;
letter-spacing: -0.05em !important;
}
.gr-button-primary {
background: linear-gradient(90deg, #4361ee, #4cc9f0) !important;
border: none !important;
color: white !important;
transition: transform 0.2s ease !important;
}
.gr-button-primary:hover {
transform: translateY(-2px) !important;
box-shadow: 0 10px 20px rgba(67, 97, 238, 0.3) !important;
}
/* λΆˆν•„μš”ν•œ ν…Œλ‘λ¦¬ 제거 */
.gr-box, .gr-block, .gr-form, .gr-panel, fieldset, .block, .group {
border-color: transparent !important;
border: none !important;
box-shadow: none !important;
}
footer {visibility: hidden}
"""
custom_theme = gr.themes.Soft(
primary_hue="blue",
secondary_hue="slate"
).set(
block_border_width="0px",
block_border_width_dark="0px",
panel_border_width="0px",
panel_border_width_dark="0px",
block_border_color="transparent",
block_border_color_dark="transparent",
border_color_primary="transparent",
border_color_primary_dark="transparent"
)
# μžλ°”μŠ€ν¬λ¦½νŠΈλ₯Ό μ΄μš©ν•΄ 무쑰건 닀크λͺ¨λ“œλ‘œ λ Œλ”λ§λ˜κ²Œ body 클래슀 κ°•μ œ μ§€μ •
js_func = """
function() {
document.body.classList.remove('light');
document.body.classList.add('dark');
}
"""
with gr.Blocks(theme=custom_theme, css=custom_css, js=js_func) as app:
with gr.Column(elem_classes="glass-panel"):
gr.Markdown("# 🎡 UV MIDI Maker - Pro")
gr.Markdown(
"### μ˜€λ””μ˜€λ₯Ό λΆ„μ„ν•˜μ—¬ μ •λ°€ν•œ 리듬 κ²Œμž„ MIDIλ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.\n"
"이 λ„κ΅¬λŠ” Meta의 Demucs AIλ₯Ό 톡해 μ•…κΈ°λ₯Ό 고음질둜 λΆ„λ¦¬ν•˜κ³ , Librosaλ₯Ό 톡해 타격점을 μ •λ°€ν•˜κ²Œ μΆ”μΆœν•©λ‹ˆλ‹€."
)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### πŸ“‚ 1. μ˜€λ””μ˜€ μ†ŒμŠ€ μž…λ ₯")
input_mode = gr.Radio(choices=["μƒˆ μ˜€λ””μ˜€ μ—…λ‘œλ“œ", "μΊμ‹œλœ 곑 선택"], value="μƒˆ μ˜€λ””μ˜€ μ—…λ‘œλ“œ", label="μž…λ ₯ 방식")
with gr.Group(visible=True) as upload_group:
audio_upload = gr.Audio(type="filepath", label="μ˜€λ””μ˜€ 파일 μ—…λ‘œλ“œ (.wav, .mp3)")
with gr.Group(visible=False) as cached_group:
def update_cache():
return gr.Dropdown(choices=get_cached_songs())
audio_cached = gr.Dropdown(choices=get_cached_songs(), label="라이브러리 μΊμ‹œ 곑 선택")
refresh_btn = gr.Button("πŸ”„ λͺ©λ£ μƒˆλ‘œκ³ μΉ¨", size="sm")
refresh_btn.click(fn=update_cache, outputs=audio_cached)
def change_input_mode(mode):
if mode == "μƒˆ μ˜€λ””μ˜€ μ—…λ‘œλ“œ":
return gr.update(visible=True), gr.update(visible=False)
else:
return gr.update(visible=False), gr.update(visible=True)
input_mode.change(fn=change_input_mode, inputs=input_mode, outputs=[upload_group, cached_group])
bpm_input = gr.Number(label="λͺ©ν‘œ 곑 BPM", value=120, precision=2, info="리듬 λ°•μžλ₯Ό λ§žμΆ”κΈ° μœ„ν•œ ν•„μˆ˜ κ°’μž…λ‹ˆλ‹€.")
with gr.Accordion("βš™οΈ κΈ°λ³Έ μ„€μ • νŒ¨λ„", open=True):
target_stem_input = gr.Dropdown(
choices=["drums", "vocals", "bass", "other"],
value="drums",
label="뢄석 λŒ€μƒ μ•…κΈ°"
)
quantize_input = gr.Dropdown(
choices=["1/4", "1/8", "1/16", "1/32"],
value="1/16",
label="ν€€νƒ€μ΄μ¦ˆ (κ·Έλ¦¬λ“œ)"
)
offset_input = gr.Number(label="첫 λ°•μž μ˜€ν”„μ…‹ (초 λ”œλ ˆμ΄)", value=0.0)
shift_input = gr.Number(label="전체 λ…ΈνŠΈ κ°•μ œ 이동 (초)", value=0.0)
with gr.Accordion("πŸ› οΈ κ³ κΈ‰ μ „λ¬Έκ°€ μ„€μ •", open=False):
mode_input = gr.Radio(choices=["single", "vote"], value="single", label="μž‘λ™ λͺ¨λ“œ")
threshold_input = gr.Slider(minimum=0.1, maximum=2.0, value=0.5, step=0.1, label="μ—λ„ˆμ§€ μž„κ³„μΉ˜ (민감도)")
min_votes_input = gr.Slider(minimum=1, maximum=4, value=2, step=1, label="μ΅œμ†Œ ν•©μ˜ 수 (Vote λͺ¨λ“œ)")
tolerance_input = gr.Number(label="ν•©μ˜ ν—ˆμš© 였차 (ms)", value=50.0)
sr_input = gr.Number(label="뢄석 μƒ˜ν”Œλ ˆμ΄νŠΈ (Hz)", value=22050)
submit_btn = gr.Button("πŸš€ MIDI νŒŒμ΄ν”„λΌμΈ μ—”μ§„ 가동", variant="primary")
with gr.Column(scale=1):
gr.Markdown("### πŸ“₯ 2. μƒμ„±λœ κ²°κ³Όλ¬Ό 및 검증")
with gr.Group():
gr.Markdown("#### 🎧 κ²€μ¦μš© νƒ€μž„λΌμΈ 및 μ˜€λ””μ˜€")
plot_output = gr.Plot(label="μ˜€λ””μ˜€ & λ―Έλ”” λ§€ν•‘ 동기화 λ·°")
mixed_audio_output = gr.Audio(label="ν‹± μ†Œλ¦¬κ°€ ν•©μ„±λœ λ…Έλž˜ (미리듣기)")
midi_output = gr.File(label="MIDI 파일 λ‹€μš΄λ‘œλ“œ")
with gr.Group():
gr.Markdown("#### πŸ’‘ TIP")
gr.Markdown("- λ“œλŸΌ λΉ„νŠΈκ°€ κ°•ν•œ 곑은 `drums` μŠ€ν…œμ΄ κ°€μž₯ μ •ν™•ν•©λ‹ˆλ‹€.\n"
"- λΉ λ₯Έ λž©μ΄λ‚˜ 보컬이 μ£Όκ°€ λ˜λŠ” ꡬ간은 `vocals` μŠ€ν…œμ„ μ‚¬μš©ν•΄ λ³΄μ„Έμš”.")
log_output = gr.Textbox(label="πŸ“ μ‹œμŠ€ν…œ 둜그 및 였λ₯˜ 리포트", lines=8, interactive=True, info="였λ₯˜κ°€ λ°œμƒν•˜λ©΄ 이 곳의 ν…μŠ€νŠΈλ₯Ό λ³΅μ‚¬ν•΄μ„œ μ „λ‹¬ν•΄μ£Όμ„Έμš”.")
submit_btn.click(
fn=process_audio,
inputs=[
input_mode, audio_upload, audio_cached, bpm_input, target_stem_input, mode_input,
quantize_input, offset_input, shift_input, threshold_input,
min_votes_input, tolerance_input, sr_input
],
outputs=[midi_output, mixed_audio_output, plot_output, log_output]
)
if __name__ == "__main__":
# 둜컬 μ„œλ²„ μ‹€ν–‰ μ„€μ •
# share=Trueλ₯Ό μ„€μ •ν•˜λ©΄ μ™ΈλΆ€μ—μ„œλ„ 접속 κ°€λŠ₯ν•œ μž„μ‹œ URL이 μƒμ„±λ©λ‹ˆλ‹€.
port = int(os.environ.get("PORT", 7860))
print(f"μ›Ή μ„œλ²„λ₯Ό μ‹œμž‘ν•©λ‹ˆλ‹€. 포트: {port}")
result = app.launch(
server_name="0.0.0.0",
server_port=port,
share=True # 이 μ˜΅μ…˜μœΌλ‘œ μ™ΈλΆ€ 곡유 κ°€λŠ₯
)
# URL μΆ”μΆœ (버전별 차이 λ°©μ–΄)
share_url = getattr(app, "share_url", "URL 생성 쀑...")
if not share_url and isinstance(result, tuple) and len(result) >= 3:
share_url = result[2]
# URL을 파일둜 μ €μž₯ν•˜μ—¬ 확인 κ°€λŠ₯ν•˜κ²Œ 함
with open("last_url.txt", "w") as f:
f.write(str(share_url))
print(f"곡유 URL: {share_url}")