SaltProphet commited on
Commit
43423d9
·
verified ·
1 Parent(s): 55a9c8c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -73
app.py CHANGED
@@ -21,6 +21,7 @@ matplotlib.use('Agg') # Use a non-interactive backend for plotting
21
  # --- Helper/Processing Functions ---
22
 
23
  def update_output_visibility(choice):
 
24
  if "2 Stems" in choice:
25
  return {
26
  vocals_output: gr.update(visible=True),
@@ -36,35 +37,8 @@ def update_output_visibility(choice):
36
  other_output: gr.update(visible=True, label="Other")
37
  }
38
 
39
- # --- NEW, CORRECTED BAR DETECTION FUNCTION ---
40
- def detect_bars(audio_file_path):
41
- if audio_file_path is None or not os.path.exists(audio_file_path):
42
- return None, None, None
43
-
44
- try:
45
- # 1. Load the audio file inside the function
46
- y, sr = librosa.load(audio_file_path, sr=None)
47
-
48
- # 2. Convert to mono for analysis
49
- y_mono = librosa.to_mono(y) if y.ndim > 1 else y
50
-
51
- # 3. Perform beat and tempo analysis
52
- tempo, beats = librosa.beat.beat_track(y=y_mono, sr=sr)
53
-
54
- bpm = 120 if tempo is None else int(np.round(tempo).item())
55
- beat_times = librosa.frames_to_time(beats, sr=sr)
56
-
57
- # This is a simple way to estimate bar start times (assuming 4/4 time)
58
- bar_times = beat_times[::4]
59
-
60
- return bpm, beat_times, bar_times
61
-
62
- except Exception as e:
63
- print(f"Error in detect_bars: {e}")
64
- return None, None, None
65
-
66
-
67
  async def separate_stems(audio_file_path, stem_choice, progress=gr.Progress(track_tqdm=True)):
 
68
  if audio_file_path is None: raise gr.Error("No audio file uploaded!")
69
  progress(0, desc="Starting...")
70
  try:
@@ -78,25 +52,17 @@ async def separate_stems(audio_file_path, stem_choice, progress=gr.Progress(trac
78
  if os.path.exists(output_dir): shutil.rmtree(output_dir)
79
 
80
  command = f"python3 -m demucs {model_arg} -o \"{output_dir}\" \"{stable_input_path}\""
81
- progress(0.2, desc="Running Demucs (this may take a minute)...")
82
-
83
- process = await asyncio.create_subprocess_shell(
84
- command,
85
- stdout=asyncio.subprocess.PIPE,
86
- stderr=asyncio.subprocess.PIPE)
87
-
88
  await process.communicate()
89
-
90
- if process.returncode != 0:
91
- raise gr.Error(f"Demucs failed to run. Error")
92
 
93
  progress(0.8, desc="Locating separated stem files...")
94
  stable_filename_base = os.path.basename(stable_input_path).rsplit('.', 1)[0]
95
  model_folder_name = next(os.walk(output_dir))[1][0]
96
  stems_path = os.path.join(output_dir, model_folder_name, stable_filename_base)
97
 
98
- if not os.path.exists(stems_path):
99
- raise gr.Error(f"Demucs finished, but the output directory was not found!")
100
 
101
  vocals_path = os.path.join(stems_path, "vocals.wav") if os.path.exists(os.path.join(stems_path, "vocals.wav")) else None
102
  drums_path = os.path.join(stems_path, "drums.wav") if os.path.exists(os.path.join(stems_path, "drums.wav")) else None
@@ -105,45 +71,26 @@ async def separate_stems(audio_file_path, stem_choice, progress=gr.Progress(trac
105
  other_path = os.path.join(stems_path, other_filename) if os.path.exists(os.path.join(stems_path, other_filename)) else None
106
 
107
  os.remove(stable_input_path)
108
-
109
- # --- CALLING THE NEW BAR DETECTION FUNCTION ---
110
- progress(0.9, desc="Analyzing stem structure...")
111
- all_paths = {"vocals": vocals_path, "drums": drums_path, "bass": bass_path, "other": other_path}
112
- for name, path in all_paths.items():
113
- if path:
114
- bpm, _, bar_times = detect_bars(path)
115
- if bpm and bar_times is not None:
116
- print(f"--- Analysis for {name} ---")
117
- print(f"Detected BPM: {bpm}")
118
- print(f"Found {len(bar_times)} bars.")
119
-
120
- return vocals_path, drums_path, bass_path, other_path
121
  except Exception as e:
122
- print(f"An error occurred: {e}")
123
- raise gr.Error(str(e))
124
-
125
- # This is the placeholder for the interactive editor we were building
126
- def preview_slice(active_stem_audio, onset_times, evt: gr.SelectData):
127
- if active_stem_audio is None or onset_times is None: return None
128
- sample_rate, y = active_stem_audio; clicked_time = evt.index[0]
129
- start_time = 0; end_time = len(y) / sample_rate
130
- for i, t in enumerate(onset_times):
131
- if t > clicked_time:
132
- end_time = t; break
133
- start_time = t
134
- start_sample = librosa.time_to_samples(start_time, sr=sample_rate)
135
- end_sample = librosa.time_to_samples(end_time, sr=sample_rate)
136
- sliced_audio = y[start_sample:end_sample]
137
- return (sample_rate, sliced_audio)
138
 
 
 
 
 
 
139
 
140
  # --- Create the full Gradio Interface ---
141
  with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="red")) as demo:
142
  gr.Markdown("# 🎵 Loop Architect")
143
 
144
- # State components
145
- onset_times_state = gr.State(value=None)
146
- active_stem_state = gr.State(value=None)
 
 
147
 
148
  with gr.Row():
149
  with gr.Column(scale=1):
@@ -164,8 +111,25 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="red"))
164
  other_output = gr.Audio(label="Other / Instrumental", scale=4)
165
 
166
  # --- Define Event Listeners ---
167
- submit_button.click(fn=separate_stems, inputs=[audio_input, stem_options], outputs=[vocals_output, drums_output, bass_output, other_output])
 
 
 
 
 
 
 
 
 
 
168
  stem_options.change(fn=update_output_visibility, inputs=stem_options, outputs=[vocals_output, drums_output, bass_output, other_output])
 
 
 
 
 
 
 
169
 
170
  # --- Launch the UI ---
171
  demo.launch()
 
21
  # --- Helper/Processing Functions ---
22
 
23
  def update_output_visibility(choice):
24
+ # This function remains the same
25
  if "2 Stems" in choice:
26
  return {
27
  vocals_output: gr.update(visible=True),
 
37
  other_output: gr.update(visible=True, label="Other")
38
  }
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  async def separate_stems(audio_file_path, stem_choice, progress=gr.Progress(track_tqdm=True)):
41
+ # This function now returns to both the visible UI and the hidden state
42
  if audio_file_path is None: raise gr.Error("No audio file uploaded!")
43
  progress(0, desc="Starting...")
44
  try:
 
52
  if os.path.exists(output_dir): shutil.rmtree(output_dir)
53
 
54
  command = f"python3 -m demucs {model_arg} -o \"{output_dir}\" \"{stable_input_path}\""
55
+ progress(0.2, desc="Running Demucs...");
56
+ process = await asyncio.create_subprocess_shell(command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
 
 
 
 
 
57
  await process.communicate()
58
+ if process.returncode != 0: raise gr.Error(f"Demucs failed to run.")
 
 
59
 
60
  progress(0.8, desc="Locating separated stem files...")
61
  stable_filename_base = os.path.basename(stable_input_path).rsplit('.', 1)[0]
62
  model_folder_name = next(os.walk(output_dir))[1][0]
63
  stems_path = os.path.join(output_dir, model_folder_name, stable_filename_base)
64
 
65
+ if not os.path.exists(stems_path): raise gr.Error(f"Demucs finished, but the output directory was not found!")
 
66
 
67
  vocals_path = os.path.join(stems_path, "vocals.wav") if os.path.exists(os.path.join(stems_path, "vocals.wav")) else None
68
  drums_path = os.path.join(stems_path, "drums.wav") if os.path.exists(os.path.join(stems_path, "drums.wav")) else None
 
71
  other_path = os.path.join(stems_path, other_filename) if os.path.exists(os.path.join(stems_path, other_filename)) else None
72
 
73
  os.remove(stable_input_path)
74
+ # Return values for the visible UI and the hidden state variables
75
+ return vocals_path, drums_path, bass_path, other_path, vocals_path, drums_path, bass_path, other_path
 
 
 
 
 
 
 
 
 
 
 
76
  except Exception as e:
77
+ print(f"An error occurred: {e}"); raise gr.Error(str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
+ # --- NEW FUNCTION TO REPOPULATE UI ON PAGE LOAD ---
80
+ def repopulate_ui_from_state(vocals_path, drums_path, bass_path, other_path):
81
+ # This function takes the saved paths from the state and updates the audio players
82
+ print("Page reloaded. Repopulating UI from session state.")
83
+ return vocals_path, drums_path, bass_path, other_path
84
 
85
  # --- Create the full Gradio Interface ---
86
  with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="red")) as demo:
87
  gr.Markdown("# 🎵 Loop Architect")
88
 
89
+ # --- NEW STATE COMPONENTS FOR PERSISTENCE ---
90
+ vocals_path_state = gr.State(None)
91
+ drums_path_state = gr.State(None)
92
+ bass_path_state = gr.State(None)
93
+ other_path_state = gr.State(None)
94
 
95
  with gr.Row():
96
  with gr.Column(scale=1):
 
111
  other_output = gr.Audio(label="Other / Instrumental", scale=4)
112
 
113
  # --- Define Event Listeners ---
114
+
115
+ # The submit button now updates both the visible audio players AND the hidden state variables
116
+ submit_button.click(
117
+ fn=separate_stems,
118
+ inputs=[audio_input, stem_options],
119
+ outputs=[
120
+ vocals_output, drums_output, bass_output, other_output,
121
+ vocals_path_state, drums_path_state, bass_path_state, other_path_state
122
+ ]
123
+ )
124
+
125
  stem_options.change(fn=update_output_visibility, inputs=stem_options, outputs=[vocals_output, drums_output, bass_output, other_output])
126
+
127
+ # --- NEW EVENT LISTENER FOR PAGE LOAD ---
128
+ demo.load(
129
+ fn=repopulate_ui_from_state,
130
+ inputs=[vocals_path_state, drums_path_state, bass_path_state, other_path_state],
131
+ outputs=[vocals_output, drums_output, bass_output, other_output]
132
+ )
133
 
134
  # --- Launch the UI ---
135
  demo.launch()