""" 리듬 게임 오토매핑 스크립트 ========================= .wav 오디오 파일을 분석하여 정확한 타이밍에 MIDI 노트를 자동 생성한다. 파이프라인: 1. Demucs → 4stems 분리 (드럼, 베이스, 보컬, 기타) 2. librosa → 드럼 / 멜로디(보컬+기타 병합) 각각 Onset 감지 3. RMS 에너지 기반으로 드럼 활성/비활성 구간을 판별하여 Onset을 스마트 결합 4. 50ms 이내 중복 Onset 병합 5. mido → 단일 트랙 .mid 파일로 저장 """ import argparse import os import sys import time import warnings from typing import Dict, List, Tuple import librosa import mido import numpy as np import soundfile as sf from scipy.signal import butter, find_peaks, lfilter, sosfilt import shutil from pathlib import Path # Demucs 연산 최적화 (TF 경고 억제는 유지) os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # ───────────────────────────────────────────── # 1. Demucs 스템 분리 및 캐시 관리 # ───────────────────────────────────────────── def get_dir_size(path: str) -> int: """디렉토리의 전체 용량을 바이트 단위로 반환한다.""" total = 0 for p in Path(path).rglob('*'): if p.is_file(): total += p.stat().st_size return total def manage_cache(cache_dir: str, max_size_gb: float = 5.0): """ 캐시 디렉토리 용량을 확인하고 설정을 초과하면 오래된 폴더부터 삭제한다. """ if not os.path.exists(cache_dir): return current_size = get_dir_size(cache_dir) max_size_bytes = max_size_gb * 1024 * 1024 * 1024 if current_size > max_size_bytes: print(f" ⚠ 캐시 용량 초과 ({current_size/1024/1024/1024:.2f}GB > {max_size_gb}GB). 오래된 파일 정리 중...") # 각 곡별 폴더의 수정 시간을 기준으로 정렬 subdirs = [os.path.join(cache_dir, d) for d in os.listdir(cache_dir)] subdirs = [d for d in subdirs if os.path.isdir(d)] subdirs.sort(key=lambda x: os.path.getmtime(x)) for d in subdirs: if current_size <= max_size_bytes: break dir_size = get_dir_size(d) shutil.rmtree(d) current_size -= dir_size print(f" - 삭제됨: {os.path.basename(d)} ({dir_size/1024/1024:.1f}MB)") def separate_stems(audio_path: str, output_dir: str) -> str: """ Demucs를 사용해 오디오를 4개의 스템으로 분리한다. 이미 분리된 파일이 있다면 분리 과정을 건너뛴다. 반환: 스템 파일들이 저장된 디렉토리 경로 """ basename = os.path.splitext(os.path.basename(audio_path))[0] # 캐시 디렉토리 설정 (프로젝트 루트의 stems 폴더) stem_parent_dir = os.path.join(os.getcwd(), "stems") stem_dir = os.path.join(stem_parent_dir, basename) # 캐시 관리 (5GB 제한) manage_cache(stem_parent_dir, max_size_gb=5.0) expected_files = ["drums.wav", "bass.wav", "vocals.wav", "other.wav"] # 이미 모든 스템 파일이 존재하는지 확인 (캐싱) all_exist = True if os.path.exists(stem_dir): for f in expected_files: if not os.path.exists(os.path.join(stem_dir, f)): all_exist = False break else: all_exist = False if all_exist: print(f"[1/5] Demucs 스템 파일이 이미 캐시에 존재합니다: {stem_dir}") return stem_dir print("[1/5] Demucs로 스템 분리 중 (이 작업은 다소 시간이 걸릴 수 있습니다)...") # Demucs 실행 (subprocess 사용 - 환경 의존성 최소화) try: import subprocess # htdemucs 모델 사용 (기본 4스탬) # 중요: --path 인자는 존재하지 않으므로 제거하고 positional argument로 전달 cmd = [ sys.executable, "-m", "demucs.separate", "-n", "htdemucs", audio_path, "-o", stem_parent_dir ] print(f" → 실행 명령: {' '.join(cmd)}") result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: raise RuntimeError(f"Demucs 실행 실패 (Exit Code {result.returncode}):\n{result.stderr}") # Demucs의 기본 출력 경로 구조: {output_dir}/htdemucs/{filename}/{stem}.wav # 이를 우리가 원하는 {output_dir}/{filename}/{stem}.wav 로 이동/정리 demucs_out_path = os.path.join(stem_parent_dir, "htdemucs", basename) if not os.path.exists(demucs_out_path): # 파일명이 다를 수 있으므로 htdemucs 내부 폴더 확인 htdemucs_dir = os.path.join(stem_parent_dir, "htdemucs") if os.path.exists(htdemucs_dir): subdirs = [d for d in os.listdir(htdemucs_dir) if os.path.isdir(os.path.join(htdemucs_dir, d))] if subdirs: demucs_out_path = os.path.join(htdemucs_dir, subdirs[0]) print(f" ⚠ basename 불일치 감지. 폴더명을 {subdirs[0]}로 대체합니다.") if not os.path.exists(stem_dir): os.makedirs(stem_dir, exist_ok=True) for f in expected_files: src = os.path.join(demucs_out_path, f) dst = os.path.join(stem_dir, f) if os.path.exists(src): shutil.move(src, dst) else: print(f" ⚠ 경고: 예상된 스템 파일을 찾을 수 없음: {src}") # 사용 후 남은 htdemucs 빈 폴더 삭제 htdemucs_base = os.path.join(stem_parent_dir, "htdemucs") if os.path.exists(htdemucs_base): shutil.rmtree(htdemucs_base) except Exception as e: print(f" ❌ Demucs 분리 실패: {str(e)}") # 에러를 다시 던져서 상위(Gradio UI)에서 인지할 수 있게 함 raise RuntimeError(f"Demucs 분리 과정에서 오류가 발생했습니다: {str(e)}") print(f" ✓ 스템 분리 및 캐싱 완료 → {stem_dir}") return stem_dir # ───────────────────────────────────────────── def load_audio(path: str, sr: int = 22050) -> tuple: """오디오 파일을 모노로 로드한다.""" y, sr_out = librosa.load(path, sr=sr, mono=True) return y, sr_out def apply_bandpass_filter(y: np.ndarray, lowcut: float, highcut: float, sr: int, order: int = 4) -> np.ndarray: """주어진 주파수 대역만 남기는 버터워스 필터를 적용한다.""" nyq = 0.5 * sr low = lowcut / nyq high = highcut / nyq # 낮은 주파수에서 수치 폭주(Instability)를 막기 위해 SOS(Second-Order Sections) 사용 sos = butter(order, [low, high], btype='band', output='sos') y_filt = sosfilt(sos, y) # NaN 또는 Inf 방어 if not np.isfinite(y_filt).all(): y_filt = np.nan_to_num(y_filt, nan=0.0, posinf=0.0, neginf=0.0) return y_filt # ───────────────────────────────────────────── # 3. 전체 드럼 Onset 정밀 감지 (광대역용) # ───────────────────────────────────────────── def detect_all_drum_onsets(y: np.ndarray, sr: int, delta_threshold: float = 0.07) -> np.ndarray: """광대역 드럼 사운드에서 타격음을 감지한다.""" print(f" → 드럼 스템의 광대역 전체 Onset 감지 중 (민감도: {delta_threshold})...") onset_frames = librosa.onset.onset_detect( y=y, sr=sr, units="frames", hop_length=512, backtrack=True, pre_max=1, post_max=1, pre_avg=3, post_avg=5, delta=delta_threshold, wait=5 ) onset_times = librosa.frames_to_time(onset_frames, sr=sr, hop_length=512) return onset_times # ───────────────────────────────────────────── # 3.5. Kick 저음역대 전용 피크 감지 # ───────────────────────────────────────────── def detect_kick_energy_peaks(y_kick: np.ndarray, sr: int, height_thresh: float = 0.15) -> np.ndarray: """ 저주파 필터링된 신호는 librosa.onset_detect로 잡기 어려우므로, RMS 에너지를 계산하여 그 파형의 최고점(Peak)을 Onset으로 정밀하게 추출한다. """ print(f" → Kick 파형 에너지 피크(RMS) 감지 중 (임계점: {height_thresh})...") # 에너지 계산 hop_length = 512 rms = librosa.feature.rms(y=y_kick, frame_length=1024, hop_length=hop_length)[0] rms_times = librosa.frames_to_time(np.arange(len(rms)), sr=sr, hop_length=hop_length) # 정규화 rms_norm = rms / (np.max(rms) + 1e-8) # 피크 검출 (height_thresh 이상, 최소 간격 50ms) peaks, _ = find_peaks( rms_norm, height=height_thresh, distance=4, # 약 92ms 간격 유지 prominence=0.05 ) onset_times = rms_times[peaks] print(f" 감지된 Kick Onset: {len(onset_times)}개") return onset_times # ───────────────────────────────────────────── # 3.6. 보컬(랩) Onset 감지 # ───────────────────────────────────────────── def detect_vocal_onsets(y: np.ndarray, sr: int, delta_threshold: float = 0.05) -> np.ndarray: """ 빠른 랩이나 보컬의 트랜지언트를 감지한다. 보컬은 타격감이 덜하므로 민감도(delta)를 낮추고 어택 타임을 유연하게 잡는다. """ print(f" → 보컬 스템 Onset 감지 중 (민감도: {delta_threshold})...") # 랩의 특성상 피크가 일정하지 않아 정규화(Normalization)하여 일관된 감지 시도 if np.max(np.abs(y)) > 0: y = y / np.max(np.abs(y)) onset_frames = librosa.onset.onset_detect( y=y, sr=sr, units="frames", hop_length=512, backtrack=True, pre_max=1, post_max=1, pre_avg=3, post_avg=3, delta=delta_threshold, wait=3 ) onset_times = librosa.frames_to_time(onset_frames, sr=sr, hop_length=512) print(f" 감지된 보컬 Onset: {len(onset_times)}개") return onset_times # ───────────────────────────────────────────── # 3.8. Kick/Snare 주파수 에너지 교차 검증 (Cross-Validation) # ───────────────────────────────────────────── def detect_kick_snare_cross_validation(y_drums: np.ndarray, sr: int) -> List[Tuple[float, int]]: """ Kick 대역(20-100Hz)과 Snare 대역(1000-4000Hz) 필터링 후 에너지(RMS)를 비교하여 킥/스네어를 판별한다. """ print(f" → 주파수 대역별 에너지 비교 기반 드럼 분리 분석 시작...") hop_length = 128 # 1. Onset 후보 감지 (민감도 완화: 0.1) # [수정] backtrack=False 로 변경하여 타격음의 맨 앞이 아닌 '가장 에너지가 강한 피크(정점)'를 기준으로 삼아 퀀타이즈 지터(Jitter)를 방지합니다. # delta=0.1 로 조절하여 후보 노트를 더 많이 찾아내되, 아래의 Peak 필터로 정리합니다. onset_frames = librosa.onset.onset_detect( y=y_drums, sr=sr, units="frames", hop_length=hop_length, backtrack=False, delta=0.1, wait=5, pre_max=3, post_max=3 ) onset_times = librosa.frames_to_time(onset_frames, sr=sr, hop_length=hop_length) # 2. 대역별 필터링 (사용자 요청: 100Hz 이하 vs 1~4kHz) y_kick = apply_bandpass_filter(y_drums, 20.0, 100.0, sr) y_snare = apply_bandpass_filter(y_drums, 1000.0, 4000.0, sr) # 3. RMS 에너지 추출 rms_kick = librosa.feature.rms(y=y_kick, frame_length=512, hop_length=hop_length)[0] rms_snare = librosa.feature.rms(y=y_snare, frame_length=512, hop_length=hop_length)[0] rms_times = librosa.frames_to_time(np.arange(len(rms_kick)), sr=sr, hop_length=hop_length) final_notes: List[Tuple[float, int]] = [] # 4. 각 Onset 시점의 에너지 및 절대 피크 비교 for t in onset_times: # [NEW] 타격 순간의 실제 오디오 샘플 절대값(피크) 확인 (Transient Peak 필터링) # 타격 지점 주변 약 10ms 내에서 가장 큰 피크값 추출 sample_idx = int(t * sr) win_size = int(sr * 0.01) if sample_idx + win_size < len(y_drums): peak_val = np.max(np.abs(y_drums[sample_idx : sample_idx + win_size])) else: peak_val = np.abs(y_drums[sample_idx]) # [사용자 요청] 절대 피크 임계값(min_peak=0.5) 필터링 # 에너지는 크지만 타격 순간의 어택(Transient)이 약한 노트를 제거합니다. if peak_val < 0.5: continue idx = np.searchsorted(rms_times, t) if idx >= len(rms_kick): idx = len(rms_kick) - 1 # Onset 직후(약 30ms) 구간의 최대 에너지 확인 win = 5 e_k = np.max(rms_kick[idx : idx + win]) if idx + win < len(rms_kick) else rms_kick[idx] e_s = np.max(rms_snare[idx : idx + win]) if idx + win < len(rms_snare) else rms_snare[idx] # [사용자 설정 구간] Kick과 Snare 에너지 분리 기준 snare_weight = 1.0 if e_k > (e_s * snare_weight): pitch = 60 # C3 (Kick) else: pitch = 61 # C#3 (Snare) final_notes.append((float(t), int(pitch))) print(f" 드럼 Onset 감지 분류 완료: {len(final_notes)}개 노트를 찾았습니다.") return final_notes # ───────────────────────────────────────────── # 3.7. 교차 스템 투표 분석 # ───────────────────────────────────────────── def vote_intersection_onsets(all_stem_onsets: dict, tolerance_ms: float = 50, min_votes: int = 2) -> np.ndarray: """ 여러 스템의 Onset 중 교차(합의)되는 지점만 추출한다. all_stem_onsets: {stem_name: np.ndarray(onset_times)} """ print(f" → 교차 스템 투표 분석 중 (허용오차: {tolerance_ms}ms, 최소득표: {min_votes})...") tolerance = tolerance_ms / 1000.0 # 모든 Onset을 하나의 리스트로 통합하여 시간순 정렬 master_list = [] for stem, onsets in all_stem_onsets.items(): for t in onsets: master_list.append({"time": t, "stem": stem}) master_list.sort(key=lambda x: x["time"]) final_onsets = [] used_indices = set() for i in range(len(master_list)): if i in used_indices: continue current = master_list[i] cluster = [current] cluster_stems = {current["stem"]} for j in range(i + 1, len(master_list)): candidate = master_list[j] # 시간 차이가 tolerance 이내인지 확인 if candidate["time"] - current["time"] <= tolerance: # 같은 스템에서 온 중복 Onset은 카운트에서 제외 (이미 하나 뽑았으므로) if candidate["stem"] not in cluster_stems: cluster.append(candidate) cluster_stems.add(candidate["stem"]) used_indices.add(j) else: break if len(cluster_stems) >= min_votes: # 합의된 지점: 클러스터 평균값으로 결정 avg_time = sum(c["time"] for c in cluster) / len(cluster) final_onsets.append(avg_time) print(f" 투표 결과: {len(final_onsets)}개 지점 합의 완료") return np.array(final_onsets) # ───────────────────────────────────────────── # 4. 필터링 제거 (모든 감지된 Onset 유지) # ───────────────────────────────────────────── def pass_all_onsets(onsets: List[Tuple[float, int]]) -> List[Tuple[float, int]]: """별도의 필터링 없이 감지된 모든 Onset을 반환한다.""" print("[3/5] 필터링 건너뛰기 (모든 Onset 유지)...") return onsets # ───────────────────────────────────────────── # 6. 50ms 중복 병합 # ───────────────────────────────────────────── def merge_close_onsets( onsets: List[Tuple[float, int]], min_gap: float = 0.065 # 150BPM 16분음표(0.1s) 안전 감지를 위해 0.065s로 조정 ) -> List[Tuple[float, int]]: """ min_gap 이내로 인접한 Onset을 하나로 병합하여 잔향/꼬리 중복을 방지한다. onsets: [(time, pitch), ...] """ if len(onsets) == 0: return onsets # 시간순 정렬 sorted_onsets: List[Tuple[float, int]] = sorted(onsets, key=lambda x: x[0]) if not sorted_onsets: return [] # 슬라이싱([1:]) 대신 반복자(iterator)를 사용하여 타입 체커 오류 방지 it = iter(sorted_onsets) merged = [next(it)] for current in it: curr_time, curr_pitch = current last_time, last_pitch = merged[-1] # 시간 간격이 min_gap보다 크면 유지 if curr_time - last_time >= min_gap: merged.append(current) else: # 너무 가까우면: 만약 피치가 다르면(Kick+Snare 동시타) 유지할 수도 있지만, # 현재는 꼬리 방지가 목적이므로 같은 시점 연타는 무시함. pass removed = len(onsets) - len(merged) print(f"[4/5] 꼬리/중복 병합 ({min_gap*1000:.0f}ms 기준): {removed}개 제거 → 최종 {len(merged)}개") return merged # ───────────────────────────────────────────── # 7. 퀀타이즈 (선택적) # ───────────────────────────────────────────── def quantize_onsets( onsets: List[Tuple[float, int]], bpm: float, strength: str = "1/16", offset: float = 0.0, ) -> List[Tuple[float, int]]: """ BPM과 그리드 크기에 맞춰 Onset의 시간을 가장 가까운 그리드에 스냅한다. offset을 주어 첫 박자의 딜레이를 보상할 수 있다. onsets: [(time, pitch), ...] """ fraction_map = {"1/4": 1.0, "1/8": 0.5, "1/16": 0.25, "1/32": 0.125} if strength not in fraction_map: strength = "1/16" beat_duration = 60.0 / bpm grid_size = beat_duration * fraction_map[strength] quantized = [] seen = set() for t, p in onsets: # 오프셋 원점 기준으로 퀀타이즈 후 다시 원래 공간으로 복원 qt = np.round((t - offset) / grid_size) * grid_size + offset # 음수 시간 방지 qt = max(0.0, qt) # 같은 시간에 같은 피치가 중복되지 않도록 함 if (qt, p) not in seen: quantized.append((qt, p)) seen.add((qt, p)) # 시간순 재정렬 quantized.sort(key=lambda x: float(x[0])) print(f" → 퀀타이즈 적용: BPM={bpm}, 1/{int(1/fraction_map[strength])}, Offset={offset}s") return quantized # ───────────────────────────────────────────── # 8. MIDI 생성 # ───────────────────────────────────────────── def create_midi( onsets: List[Tuple[float, int]], output_path: str, bpm: float = 120.0, velocity: int = 100, note_duration: float = 0.05, ) -> None: """ [(time, pitch), ...] 배열을 기반으로 멀티 노트 MIDI 파일을 생성한다. """ print("[5/5] MIDI 파일 생성 중...") mid = mido.MidiFile(type=0) track = mido.MidiTrack() mid.tracks.append(track) tempo = mido.bpm2tempo(bpm) track.append(mido.MetaMessage("set_tempo", tempo=tempo, time=0)) ticks_per_beat = mid.ticks_per_beat def seconds_to_ticks(sec: float) -> int: return int(mido.second2tick(sec, ticks_per_beat, tempo)) note_dur_ticks = seconds_to_ticks(note_duration) # MIDI 메시지들을 담을 리스트 (절대 틱 기준) events = [] for t_sec, pitch in onsets: abs_tick = seconds_to_ticks(t_sec) events.append({'tick': abs_tick, 'type': 'note_on', 'note': pitch, 'vel': velocity}) events.append({'tick': abs_tick + note_dur_ticks, 'type': 'note_off', 'note': pitch, 'vel': 0}) # 틱 순서대로 정렬 events.sort(key=lambda x: (x['tick'], 0 if x['type'] == 'note_off' else 1)) prev_tick = 0 for e in events: delta = max(0, e['tick'] - prev_tick) track.append(mido.Message(e['type'], note=e['note'], velocity=e['vel'], time=delta)) prev_tick = e['tick'] mid.save(output_path) # 마지막 온셋의 시간으로 곡 길이 계산 duration = 0 if len(onsets) > 0: last_item = onsets[-1] duration = last_item[0] print(f" ✓ MIDI 저장 완료 → {output_path}") print(f" 총 노트 수: {len(onsets)}개 | 곡 길이: {duration:.2f}초") # ───────────────────────────────────────────── # 9. 싱크 검증 로직 (Verification) # ───────────────────────────────────────────── def verify_sync( target_onsets: List[Tuple[float, int]], output_path: str, bpm: float ) -> None: """ 생성된 MIDI 노트를 시간(초)으로 다시 로드하여 싱크 검증. """ print("[6/6] 생성 시간과 목표 그리드 간의 싱크 검증 중...") mid = mido.MidiFile(output_path) tempo = mido.bpm2tempo(bpm) ticks_per_beat = mid.ticks_per_beat midi_onsets = [] for track in mid.tracks: track_time_sec = 0.0 for msg in track: track_time_sec += mido.tick2second(msg.time, ticks_per_beat, tempo) if msg.type == 'note_on' and msg.velocity > 0: midi_onsets.append((track_time_sec, msg.note)) # 시간순 정렬 midi_onsets.sort(key=lambda x: x[0]) target_times = [x[0] for x in target_onsets] midi_times = [x[0] for x in midi_onsets] if len(target_times) != len(midi_times): print(f" ⚠ [경고] 목표 개수({len(target_times)})와 미디 개수({len(midi_times)}) 차이 발생.") diffs = [abs(t - m) * 1000.0 for t, m in zip(target_times, midi_times)] if diffs: max_diff = max(diffs) avg_diff = sum(diffs) / len(diffs) print(f" → 최대 싱크 오차: {max_diff:.3f} ms") print(f" → 평균 싱크 오차: {avg_diff:.3f} ms") if max_diff < 2.0: print(" ✓ [검증 성공] 완벽한 싱크 유지.") # ───────────────────────────────────────────── # 10. 메인 파이프라인 # ───────────────────────────────────────────── def run_pipeline( audio_path: str, output_path: str, bpm: float, threshold_multiplier: float = 0.5, quantize_strength: str = "1/16", sr: int = 22050, target_stem: str = "drums", mode: str = "single", min_votes: int = 2, tolerance_ms: float = 50, offset: float = 0.0, shift: float = 0.0, ) -> List[Tuple[float, int]]: """전체 오토매핑 파이프라인을 실행한다.""" print("=" * 60) print(" 리듬 게임 오토매핑 스크립트 (BPM 기반 퀀타이즈 필수)") print("=" * 60) print(f" 입력: {audio_path}") print(f" 출력: {output_path}") print(f" 목표 BPM: {bpm} (강제 퀀타이즈: {quantize_strength}) | Offset: {offset}s") print(f" 작동 모드: {mode} (타겟: {target_stem if mode == 'single' else 'ALL stems'})") print("=" * 60) # 1) 스템 분리 stem_output_dir = os.path.join(os.path.dirname(output_path) or ".", "stems_output") stem_dir = separate_stems(audio_path, stem_output_dir) if mode == "vote": # (투표 모드는 현재 단일 피치 60으로 유지하거나 추후 리팩토링 필요) all_stem_onsets = {} # ... (생략된 기존 투표 로직, 단 결과는 [(t, 60), ...]로 변환 필요) # 일단은 기존과 동일하게 동작하게 하되 튜플로 변환함 # (실제 코드는 아래와 같이 구현) all_stem_onsets_raw = {} for s_name in ["drums", "vocals", "bass", "other"]: p = os.path.join(stem_dir, f"{s_name}.wav") y_s, _ = load_audio(p, sr=sr) if s_name == "drums": all_stem_onsets_raw[s_name] = detect_all_drum_onsets(y_s, sr, 0.07) elif s_name == "vocals": all_stem_onsets_raw[s_name] = detect_vocal_onsets(y_s, sr, 0.08) else: all_stem_onsets_raw[s_name] = detect_all_drum_onsets(y_s, sr, 0.07) voted_times = vote_intersection_onsets(all_stem_onsets_raw, tolerance_ms, min_votes) target_onsets = [(t, 60) for t in voted_times] else: # 기존: 단일 스템 분석 target_path = os.path.join(stem_dir, f"{target_stem}.wav") print(f"[2/5] {target_stem} 오디오 트랙 로딩 및 분석 중...") y_target, _ = load_audio(target_path, sr=sr) if target_stem == "drums": # [핵심] Kick/Snare 교차 검증 로직 사용 target_onsets = detect_kick_snare_cross_validation(y_target, sr) else: # 보컬 등 기타 스태은 기본 피치 60 사용 if target_stem == "vocals": times = detect_vocal_onsets(y_target, sr, 0.08) else: times = detect_all_drum_onsets(y_target, sr, 0.07) target_onsets = [(t, 60) for t in times] # 4) 필터링 건너뛰고 모든 Onset 병합 단계로 넘김 combined = pass_all_onsets(target_onsets) # 6) 꼬리 중복 방지 (16분음표 연타를 위해 더 정교한 간격 적용) final_onsets = merge_close_onsets(combined, min_gap=0.065) if shift != 0.0: final_onsets = [(max(0.0, t + shift), p) for t, p in final_onsets] # 7) 퀀타이즈 강제 적용 (사용자 요청: 1/8 등에서 동적 strength로 복구) quantized_onsets = quantize_onsets(final_onsets, bpm=bpm, strength=quantize_strength, offset=offset) # 8) MIDI 생성 if len(quantized_onsets) == 0: print(" ⚠ 감지된 Onset이 없습니다. MIDI 파일을 생성하지 않습니다.") return [] create_midi(quantized_onsets, output_path, bpm=bpm) # 9) 생성된 MIDI 오차 검증(Verification) verify_sync(quantized_onsets, output_path, bpm=bpm) print("=" * 60) print(" ✓ 오토매핑 및 검증 완료!") print("=" * 60) return quantized_onsets # ───────────────────────────────────────────── # CLI 인터페이스 # ───────────────────────────────────────────── def main(): parser = argparse.ArgumentParser( description="리듬 게임 오토매핑: .wav → .mid 변환 스크립트", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" 사용 예시: python auto_mapper.py song.wav --bpm 150 -o output.mid python auto_mapper.py song.wav --bpm 150 -o output.mid --threshold-multiplier 0.3 --quantize-strength 1/8 """, ) parser.add_argument("input", help="입력 오디오 파일 경로 (.wav)") parser.add_argument( "-o", "--output", default="output.mid", help="출력 MIDI 파일 경로 (기본: output.mid)" ) parser.add_argument( "--bpm", type=float, required=True, help="[필수] 곡의 엄격한 BPM (리듬 게임 격자를 생성하기 위해 반드시 필요합니다, 예: 150)", ) parser.add_argument( "--threshold-multiplier", type=float, default=0.5, help="드럼 에너지 임계치 배율 (기본: 0.5, 낮을수록 드럼 Onset 많이 사용)", ) parser.add_argument( "--quantize-strength", default="1/16", choices=["1/4", "1/8", "1/16", "1/32"], help="퀀타이즈 그리드 단위 (기본: 1/16)", ) parser.add_argument( "--target-stem", default="drums", choices=["drums", "vocals", "bass", "other"], help="단일 스템 분석 시 대상을 지정합니다 (기본: drums)", ) parser.add_argument( "--mode", default="single", choices=["single", "vote"], help="작동 모드: single(단일 스템 수행), vote(전체 스템 교차 투표)", ) parser.add_argument( "--offset", type=float, default=0.0, help="곡의 첫 박자 오프셋(초 단위). 예: 0.045", ) parser.add_argument( "--min-votes", type=int, default=2, help="투표 모드에서 Onset을 인정받기 위한 최소 합의 스템 수 (기본: 2)", ) parser.add_argument( "--tolerance-ms", type=float, default=50.0, help="투표 모드에서 두 Onset을 같은 지점으로 인정할 시간 오차(ms) (기본: 50.0)", ) parser.add_argument( "--sr", type=int, default=22050, help="오디오 샘플레이트 (기본: 22050)", ) parser.add_argument( "--shift", type=float, default=0.0, help="전체 노트 시간을 통째로 앞/뒤로 강제 이동합니다. (초 단위). 예: -0.025 (25ms 앞당김)", ) args = parser.parse_args() if not os.path.exists(args.input): print(f"오류: 입력 파일을 찾을 수 없습니다 → {args.input}") sys.exit(1) run_pipeline( audio_path=args.input, output_path=args.output, bpm=args.bpm, threshold_multiplier=args.threshold_multiplier, quantize_strength=args.quantize_strength, sr=args.sr, target_stem=args.target_stem, mode=args.mode, min_votes=args.min_votes, tolerance_ms=args.tolerance_ms, offset=args.offset, shift=args.shift, ) if __name__ == "__main__": main()