Spaces:
Running
Running
Update app.py
Browse files12345678910115 unmodified lines171819202122232425262728293031323334354 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939420 unmodified lines1151161171181191201211222 unmodified lines125126127128129130131import loggingimport osimport librosaimport soundfile as sfimport numpy as npimport scipy.signal as spsimport yt_dlpimport gradio as gr# ログの設定(コンソールとファイルへの出力)logging.basicConfig(5 unmodified lines])# ----- 音声処理関数 -----def align_audio(original_file, karaoke_file):y1, sr1 = librosa.load(original_file, sr=None, mono=True)y2, sr2 = librosa.load(karaoke_file, sr=None, mono=True)if sr1 != sr2:error_msg = "サンプリングレートが異なります。"logging.error(error_msg)raise ValueError(error_msg)y1 = y1 / np.max(np.abs(y1))y2 = y2 / np.max(np.abs(y2))corr = sps.correlate(y1, y2, mode='full')lags = sps.correlation_lags(len(y1), len(y2), mode='full')best_lag = lags[np.argmax(corr)]if best_lag > 0:y1_aligned = y1[best_lag:]y2_aligned = y24 unmodified linesreturn y1_aligned[:min_len], y2_aligned[:min_len], sr1def extract_vocals(y1, y2, sr, scale_factor=1.0):n_fft = 2048hop_length = 512orig_stft = librosa.stft(y1, n_fft=n_fft, hop_length=hop_length)kara_stft = librosa.stft(y2, n_fft=n_fft, hop_length=hop_length)orig_mag, orig_phase = np.abs(orig_stft), np.angle(orig_stft)kara_mag, _ = np.abs(kara_stft), np.angle(kara_stft)vocal_mag = np.maximum(orig_mag - kara_mag * scale_factor, 0)vocal_stft = vocal_mag * np.exp(1j * orig_phase)vocal_wave = librosa.istft(vocal_stft, hop_length=hop_length)return vocal_wave / np.max(np.abs(vocal_wave))# ----- YouTube ダウンロード関数 -----def download_audio_from_youtube(url, output_dir):ydl_opts = {'format': 'bestaudio/best','outtmpl': os.path.join(output_dir, '%(id)s.%(ext)s'),'postprocessors': [{'key': 'FFmpegExtractAudio','preferredcodec': 'wav','preferredquality': '192',}],'cookies-from-browser': 'Firefox','quiet': True,'no_warnings': True,}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info_dict = ydl.extract_info(url, download=True)filename = ydl.prepare_filename(info_dict)base, _ = os.path.splitext(filename)audio_file = base + ".wav"return audio_file# ----- メイン処理関数 (Gradio用) -----def process_vocals(music1_url, music2_url, scale_factor, output_filename):try:# ダウンロード先は "Audios" フォルダ(存在しない場合は作成)download_dir = os.path.join(os.getcwd(), "Audios")if not os.path.exists(download_dir):os.makedirs(download_dir)logging.debug("ダウンロードフォルダを作成: %s", download_dir)# YouTubeから音声のダウンロードfile1 = download_audio_from_youtube(music1_url, download_dir)file2 = download_audio_from_youtube(music2_url, download_dir)logging.info("音声ファイルをダウンロード: %s, %s", file1, file2)# タイミング補正y1, y2, sr = align_audio(file1, file2)logging.debug("タイミング補正完了")# ボーカル抽出vocals = extract_vocals(y1, y2, sr, scale_factor)20 unmodified linesiface = gr.Interface(fn=process_vocals,inputs=[gr.Textbox(label="楽器+ボーカル YouTube URL"),gr.Textbox(label="楽器のみ YouTube URL"),gr.Slider(0.0, 1.0, step=0.01, value=1.0, label="抽出精度"),gr.Textbox(label="完成音源のファイル名 (拡張子不要)")],2 unmodified linesgr.Textbox(label="エラーログ", lines=5)],title="ボーカル抽出ツール",description="YouTube の URL を入力して音声をダウンロードし、タイミング補正とボーカル抽出を行います。")if __name__ == "__main__":1234567891011125 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566674 unmodified lines7273747576777879808182838485868788899091929394959697989910010110210310410510610710820 unmodified lines1291301311321331341351362 unmodified lines139140141142143144145import loggingimport osimport tempfileimport librosaimport soundfile as sfimport numpy as npimport scipy.signal as spsimport gradio as grfrom moviepy.editor import AudioFileClip # 動画→音声変換用# ログの設定(コンソールとファイルへの出力)logging.basicConfig(5 unmodified lines])# ----- ファイルから音声パスを取得するヘルパー関数 -----def get_audio_path(uploaded_file_path):"""アップロードされたファイルのパスから、もし動画ファイルなら音声部分を抽出して一時的なwavファイルとして保存し、そのパスを返す。"""ext = os.path.splitext(uploaded_file_path)[1].lower()video_exts = [".mp4", ".mov", ".avi", ".mkv"]if ext in video_exts:logging.info("動画ファイル検出: %s。音声抽出を実施します。", uploaded_file_path)temp_audio = tempfile.mktemp(suffix=".wav")try:clip = AudioFileClip(uploaded_file_path)clip.write_audiofile(temp_audio, logger=None)clip.close()logging.info("音声抽出完了: %s", temp_audio)return temp_audioexcept Exception as e:logging.error("動画ファイルからの音声抽出エラー: %s", e)raise eelse:logging.info("音声ファイルとして処理: %s", uploaded_file_path)return uploaded_file_path# ----- 音声処理関数 -----def align_audio(original_file, karaoke_file):try:y1, sr1 = librosa.load(original_file, sr=None, mono=True)y2, sr2 = librosa.load(karaoke_file, sr=None, mono=True)except Exception as e:logging.error("音声ファイルの読み込みエラー: %s", e)raise eif sr1 != sr2:error_msg = "サンプリングレートが異なります。"logging.error(error_msg)raise ValueError(error_msg)y1 = y1 / np.max(np.abs(y1))y2 = y2 / np.max(np.abs(y2))corr = sps.correlate(y1, y2, mode='full')lags = sps.correlation_lags(len(y1), len(y2), mode='full')best_lag = lags[np.argmax(corr)]if best_lag > 0:y1_aligned = y1[best_lag:]y2_aligned = y24 unmodified linesreturn y1_aligned[:min_len], y2_aligned[:min_len], sr1def extract_vocals(y1, y2, sr, scale_factor=1.0):try:n_fft = 2048hop_length = 512orig_stft = librosa.stft(y1, n_fft=n_fft, hop_length=hop_length)kara_stft = librosa.stft(y2, n_fft=n_fft, hop_length=hop_length)orig_mag, orig_phase = np.abs(orig_stft), np.angle(orig_stft)kara_mag, _ = np.abs(kara_stft), np.angle(kara_stft)vocal_mag = np.maximum(orig_mag - kara_mag * scale_factor, 0)vocal_stft = vocal_mag * np.exp(1j * orig_phase)vocal_wave = librosa.istft(vocal_stft, hop_length=hop_length)return vocal_wave / np.max(np.abs(vocal_wave))except Exception as e:logging.error("ボーカル抽出処理でエラー発生: %s", e)raise e# ----- メイン処理関数 (Gradio用) -----def process_vocals(music1_file, music2_file, scale_factor, output_filename):"""music1_file: ユーザーがアップロードした「楽器+ボーカル」のファイル (音声または動画)music2_file: ユーザーがアップロードした「楽器のみ」のファイル (���声または動画)scale_factor: ボーカル抽出の精度調整パラメータoutput_filename: 出力ファイル名(拡張子不要)"""try:# アップロードされたファイルのパスから、必要なら音声抽出を実施music1_path = get_audio_path(music1_file)music2_path = get_audio_path(music2_file)# タイミング補正y1, y2, sr = align_audio(music1_path, music2_path)logging.info("タイミング補正完了")# ボーカル抽出vocals = extract_vocals(y1, y2, sr, scale_factor)20 unmodified linesiface = gr.Interface(fn=process_vocals,inputs=[gr.File(label="楽器+ボーカル ファイル(音声 or 動画)", type="file"),gr.File(label="楽器のみ ファイル(音声 or 動画)", type="file"),gr.Slider(0.0, 1.0, step=0.01, value=1.0, label="抽出精度"),gr.Textbox(label="完成音源のファイル名 (拡張子不要)")],2 unmodified linesgr.Textbox(label="エラーログ", lines=5)],title="ボーカル抽出ツール",description="アップロードされた音声または動画ファイルから、タイミング補正とボーカル抽出を行います。")if __name__ == "__main__":
app.py+64-50