gere commited on
Commit
34b4ff9
·
verified ·
1 Parent(s): bdee77c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -68
app.py CHANGED
@@ -1,91 +1,147 @@
1
  import os
2
- import torch
3
- import torchaudio
4
- import librosa
5
- import numpy as np
6
  import io
7
- import tempfile
8
- import wave
 
 
 
 
9
  from flask import Flask, request, send_file, jsonify
10
  from flask_cors import CORS
11
- from audiocraft.models import MusicGen
 
 
 
12
 
13
  app = Flask(__name__)
14
  CORS(app)
15
 
16
- class FusionEngine:
17
- def __init__(self):
18
- self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
19
- # Using melody model as required for melody conditioning
20
- self.model = MusicGen.get_pretrained('facebook/musicgen-melody')
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- def process(self, melody_bytes, style_bytes):
23
- with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as m_file:
24
- m_file.write(melody_bytes)
25
- m_path = m_file.name
26
- with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as s_file:
27
- s_file.write(style_bytes)
28
- s_path = s_file.name
29
- try:
30
- y2, sr2 = librosa.load(s_path, duration=10)
31
- tempo_val, _ = librosa.beat.beat_track(y=y2, sr=sr2)
32
- tempo = float(tempo_val[0]) if isinstance(tempo_val, (np.ndarray, list)) else float(tempo_val)
33
- spec_centroid = np.mean(librosa.feature.spectral_centroid(y=y2, sr=sr2))
34
- vibe = "electronic" if spec_centroid > 2500 else "organic"
35
- accurate_prompt = f"A {vibe} version, {int(tempo)} BPM, studio quality."
36
-
37
- self.model.set_generation_params(duration=15, use_sampling=True, top_k=250, temperature=0.7)
38
-
39
- m_wav, sr = torchaudio.load(m_path)
40
- if m_wav.shape[0] > 1:
41
- m_wav = m_wav.mean(dim=0, keepdim=True)
42
-
43
- if sr != 32000:
44
- resampler = torchaudio.transforms.Resample(sr, 32000)
45
- m_wav = resampler(m_wav)
46
- sr = 32000
47
-
48
- result = self.model.generate_with_chroma(
49
- descriptions=[accurate_prompt],
50
- melody_wavs=m_wav[None, ...].to(self.device),
51
- melody_sample_rate=sr
52
- )
53
- return result[0].cpu().numpy(), self.model.sample_rate
54
- finally:
55
- if os.path.exists(m_path): os.remove(m_path)
56
- if os.path.exists(s_path): os.remove(s_path)
57
 
58
- engine = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  @app.route('/', methods=['GET'])
61
  def health():
62
  return jsonify({"status": "ready"}), 200
63
 
64
  @app.route('/fuse', methods=['POST'])
65
- def fuse():
66
- global engine
67
- if engine is None:
68
- engine = FusionEngine()
69
  try:
70
- m = request.files['melody'].read()
71
- s = request.files['style'].read()
72
- out_wav, sr = engine.process(m, s)
73
-
74
- # Manually construct the WAV file to bypass FFmpeg AVFormatContext errors
75
- buffer = io.BytesIO()
76
- # MusicGen outputs (Channels, Samples), we need (Samples, Channels) for wave
77
- audio_data = (out_wav[0] * 32767).astype(np.int16)
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
- with wave.open(buffer, 'wb') as wf:
80
- wf.setnchannels(1)
81
- wf.setsampwidth(2)
82
- wf.setframerate(sr)
83
- wf.writeframes(audio_data.tobytes())
84
-
85
- buffer.seek(0)
86
- return send_file(buffer, mimetype='audio/wav', as_attachment=True, download_name="fused.wav")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  except Exception as e:
88
  return jsonify({"error": str(e)}), 500
 
 
 
 
 
89
 
90
  if __name__ == "__main__":
91
  app.run(host='0.0.0.0', port=7860)
 
1
  import os
 
 
 
 
2
  import io
3
+ import uuid
4
+ import shutil
5
+ import numpy as np
6
+ import librosa
7
+ import soundfile as sf
8
+ import pyloudnorm as pyln
9
  from flask import Flask, request, send_file, jsonify
10
  from flask_cors import CORS
11
+ from scipy.signal import butter, lfilter
12
+ from pedalboard import Pedalboard, Compressor, Limiter, HighpassFilter, LowpassFilter, Gain
13
+ import subprocess
14
+ from pydub import AudioSegment
15
 
16
  app = Flask(__name__)
17
  CORS(app)
18
 
19
+ SR = 44100
20
+ TARGET_LOUDNESS = -9.0
21
+
22
+ def convert_to_wav(input_path):
23
+ if input_path.lower().endswith(".mp3"):
24
+ wav_path = input_path.rsplit(".", 1)[0] + f"_{uuid.uuid4().hex}.wav"
25
+ AudioSegment.from_mp3(input_path).export(wav_path, format="wav")
26
+ return wav_path
27
+ return input_path
28
+
29
+ def load_mono(file):
30
+ y, _ = librosa.load(file, sr=SR, mono=True)
31
+ return y
32
+
33
+ def normalize_audio(y):
34
+ return y / (np.max(np.abs(y)) + 1e-9)
35
 
36
+ def highpass(data, cutoff):
37
+ b, a = butter(4, cutoff / (SR / 2), btype='high')
38
+ return lfilter(b, a, data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ def lowpass(data, cutoff):
41
+ b, a = butter(4, cutoff / (SR / 2), btype='low')
42
+ return lfilter(b, a, data)
43
+
44
+ def detect_key(y):
45
+ chroma = librosa.feature.chroma_cqt(y=y, sr=SR)
46
+ return np.argmax(np.sum(chroma, axis=1))
47
+
48
+ def match_key(source, target):
49
+ key_s = detect_key(source)
50
+ key_t = detect_key(target)
51
+ shift = key_t - key_s
52
+ return librosa.effects.pitch_shift(source, sr=SR, n_steps=float(shift))
53
+
54
+ def beat_sync_warp(source, target):
55
+ tempo_t, _ = librosa.beat.beat_track(y=target, sr=SR)
56
+ tempo_s, _ = librosa.beat.beat_track(y=source, sr=SR)
57
+ tempo_t = float(np.atleast_1d(tempo_t)[0])
58
+ tempo_s = float(np.atleast_1d(tempo_s)[0])
59
+ if tempo_t <= 0 or tempo_s <= 0:
60
+ return librosa.util.fix_length(source, size=len(target))
61
+ rate = tempo_s / tempo_t
62
+ warped = librosa.effects.time_stretch(source, rate=float(rate))
63
+ warped = librosa.util.fix_length(warped, size=len(target))
64
+ return warped
65
+
66
+ def separate_stems(input_file, job_id):
67
+ out_dir = f"separated_{job_id}"
68
+ subprocess.run(["demucs", "-n", "htdemucs", "--out", out_dir, input_file], check=True)
69
+ base = os.path.splitext(os.path.basename(input_file))[0]
70
+ stem_dir = f"{out_dir}/htdemucs/{base}"
71
+ stems = {
72
+ "drums": f"{stem_dir}/drums.wav",
73
+ "bass": f"{stem_dir}/bass.wav",
74
+ "other": f"{stem_dir}/other.wav",
75
+ "vocals": f"{stem_dir}/vocals.wav"
76
+ }
77
+ return stems, out_dir
78
 
79
  @app.route('/', methods=['GET'])
80
  def health():
81
  return jsonify({"status": "ready"}), 200
82
 
83
  @app.route('/fuse', methods=['POST'])
84
+ def fuse_api():
85
+ job_id = str(uuid.uuid4())
86
+ temp_files = []
87
+ cleanup_dirs = []
88
  try:
89
+ trad_req = request.files.get('melody')
90
+ modern_req = request.files.get('style')
91
+ if not trad_req or not modern_req:
92
+ return jsonify({"error": "missing files"}), 400
93
+ t_path = f"trad_{job_id}.wav"
94
+ m_path = f"mod_{job_id}.wav"
95
+ trad_req.save(t_path)
96
+ modern_req.save(m_path)
97
+ temp_files.extend([t_path, m_path])
98
+ t_wav = convert_to_wav(t_path)
99
+ m_wav = convert_to_wav(m_path)
100
+ if t_wav != t_path: temp_files.append(t_wav)
101
+ if m_wav != m_path: temp_files.append(m_wav)
102
+ t_stems, t_dir = separate_stems(t_wav, f"t_{job_id}")
103
+ m_stems, m_dir = separate_stems(m_wav, f"m_{job_id}")
104
+ cleanup_dirs.extend([t_dir, m_dir])
105
+ t_other = load_mono(t_stems["other"])
106
+ t_bass = load_mono(t_stems["bass"])
107
+ m_drums = load_mono(m_stems["drums"])
108
+ m_bass = load_mono(m_stems["bass"])
109
+ m_other = load_mono(m_stems["other"])
110
 
111
+ target_len = min(len(t_other), len(m_drums))
112
+ t_other = t_other[:target_len]
113
+ t_bass = t_bass[:target_len]
114
+ m_drums = m_drums[:target_len]
115
+ m_bass = m_bass[:target_len]
116
+ m_other = m_other[:target_len]
117
+
118
+ t_other = match_key(t_other, m_other)
119
+ t_bass = match_key(t_bass, m_bass)
120
+ t_other = beat_sync_warp(t_other, m_drums)
121
+ t_bass = beat_sync_warp(t_bass, m_drums)
122
+ t_other = highpass(t_other, 120)
123
+ t_bass = highpass(t_bass, 60)
124
+ m_bass = lowpass(m_bass, 250)
125
+ m_drums = lowpass(m_drums, 12000)
126
+ m_other = highpass(m_other, 150)
127
+ fusion = (1.0 * m_drums + 1.0 * m_bass + 1.2 * t_other + 0.5 * m_other + 0.8 * t_bass)
128
+ fusion = normalize_audio(fusion)
129
+ board = Pedalboard([HighpassFilter(30), LowpassFilter(18000), Compressor(threshold_db=-20, ratio=2), Gain(2.0), Limiter(threshold_db=-0.5)])
130
+ fusion_mastered = board(fusion, SR)
131
+ meter = pyln.Meter(SR)
132
+ loudness = meter.integrated_loudness(fusion_mastered)
133
+ fusion_mastered = pyln.normalize.loudness(fusion_mastered, loudness, TARGET_LOUDNESS)
134
+ buf = io.BytesIO()
135
+ sf.write(buf, fusion_mastered, SR, format='WAV')
136
+ buf.seek(0)
137
+ return send_file(buf, mimetype="audio/wav", as_attachment=True, download_name="fusion_output.wav")
138
  except Exception as e:
139
  return jsonify({"error": str(e)}), 500
140
+ finally:
141
+ for f in temp_files:
142
+ if os.path.exists(f): os.remove(f)
143
+ for d in cleanup_dirs:
144
+ if os.path.exists(d): shutil.rmtree(d, ignore_errors=True)
145
 
146
  if __name__ == "__main__":
147
  app.run(host='0.0.0.0', port=7860)