owiedotch commited on
Commit
cf67794
1 Parent(s): 4a925ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -23
app.py CHANGED
@@ -4,20 +4,31 @@ import subprocess
4
  import spaces
5
  from typing import Tuple, List, Dict
6
  from pydub import AudioSegment
 
 
 
 
 
 
 
7
 
8
  @spaces.GPU
9
  def inference(audio_file: str, model_name: str, vocals: bool, drums: bool, bass: bool, other: bool, mp3: bool, mp3_bitrate: int) -> Tuple[str, gr.HTML]:
10
  log_messages = []
11
 
12
- def stream_log(message):
13
- log_messages.append(f"[{model_name}] {message}")
14
- return gr.HTML("<pre style='margin-bottom: 0;'>" + "<br>".join(log_messages) + "</pre>")
 
 
 
 
15
 
16
- yield None, stream_log("Starting separation process...")
17
- yield None, stream_log(f"Loading audio file: {audio_file}")
18
 
19
  if audio_file is None:
20
- yield None, stream_log("Error: No audio file provided")
21
  raise gr.Error("Please upload an audio file")
22
 
23
  # Use absolute paths
@@ -33,30 +44,42 @@ def inference(audio_file: str, model_name: str, vocals: bool, drums: bool, bass:
33
  audio_file
34
  ]
35
 
36
- yield None, stream_log(f"Running Demucs command: {' '.join(cmd)}")
 
37
 
38
  try:
39
  # Run the Demucs command
40
  process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
41
 
42
- # Stream the output
43
- for line in process.stdout:
44
- yield None, stream_log(line.strip())
45
-
46
- # Wait for the process to complete
47
- process.wait()
 
 
 
 
 
 
 
 
48
 
49
  if process.returncode != 0:
50
  error_output = process.stderr.read()
51
- yield None, stream_log(f"Error: Demucs command failed with return code {process.returncode}")
52
- yield None, stream_log(f"Error output: {error_output}")
53
  raise gr.Error(f"Demucs separation failed. Check the logs for details.")
54
 
55
  except Exception as e:
56
- yield None, stream_log(f"Unexpected error: {str(e)}")
57
  raise gr.Error(f"An unexpected error occurred: {str(e)}")
58
 
59
- yield None, stream_log("Separation completed. Processing stems...")
 
 
 
 
60
 
61
  # Change the stem search directory using full path
62
  stem_search_dir = os.path.join(base_output_dir, model_name, os.path.splitext(os.path.basename(audio_file))[0])
@@ -99,14 +122,16 @@ def inference(audio_file: str, model_name: str, vocals: bool, drums: bool, bass:
99
  yield None, stream_log(f"Final selected stems: {selected_stems}")
100
 
101
  if not selected_stems:
102
- yield None, stream_log("Error: No stems selected for mixing")
103
  raise gr.Error("Please select at least one stem to mix and ensure it was successfully separated.")
104
 
105
  output_file: str = os.path.join(output_dir, "mixed.wav")
106
- yield None, stream_log("Mixing selected stems...")
 
107
 
108
  if len(selected_stems) == 1:
109
- os.rename(selected_stems[0], output_file)
 
110
  else:
111
  mixed_audio: AudioSegment = AudioSegment.empty()
112
  for stem_path in selected_stems:
@@ -114,13 +139,20 @@ def inference(audio_file: str, model_name: str, vocals: bool, drums: bool, bass:
114
  mixed_audio.export(output_file, format="wav")
115
 
116
  if mp3:
117
- yield None, stream_log(f"Converting to MP3 (bitrate: {mp3_bitrate}k)...")
 
118
  mp3_output_file: str = os.path.splitext(output_file)[0] + ".mp3"
119
  mixed_audio.export(mp3_output_file, format="mp3", bitrate=str(mp3_bitrate) + "k")
120
  output_file = mp3_output_file
121
 
122
- yield None, stream_log("Process completed successfully!")
123
- yield output_file, gr.HTML("<pre style='color: green;'>Separation and mixing completed successfully!</pre>")
 
 
 
 
 
 
124
 
125
  # Define the Gradio interface
126
  with gr.Blocks() as iface:
 
4
  import spaces
5
  from typing import Tuple, List, Dict
6
  from pydub import AudioSegment
7
+ from rich.console import Console
8
+ from rich.panel import Panel
9
+ from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeRemainingColumn
10
+ from rich.text import Text
11
+ import time
12
+
13
+ console = Console()
14
 
15
  @spaces.GPU
16
  def inference(audio_file: str, model_name: str, vocals: bool, drums: bool, bass: bool, other: bool, mp3: bool, mp3_bitrate: int) -> Tuple[str, gr.HTML]:
17
  log_messages = []
18
 
19
+ def stream_log(message, style=""):
20
+ formatted_message = f"[{model_name}] {message}"
21
+ log_messages.append(formatted_message)
22
+ return gr.HTML(f"<pre style='margin-bottom: 0;{style}'>{formatted_message}</pre>")
23
+
24
+ yield None, stream_log("Initializing Demucs...", "color: #4CAF50; font-weight: bold;")
25
+ time.sleep(1) # Simulate initialization time
26
 
27
+ yield None, stream_log("Loading audio file...", "color: #2196F3;")
28
+ time.sleep(0.5) # Simulate loading time
29
 
30
  if audio_file is None:
31
+ yield None, stream_log("Error: No audio file provided", "color: #F44336;")
32
  raise gr.Error("Please upload an audio file")
33
 
34
  # Use absolute paths
 
44
  audio_file
45
  ]
46
 
47
+ yield None, stream_log("Preparing separation process...", "color: #FF9800;")
48
+ time.sleep(0.5) # Simulate preparation time
49
 
50
  try:
51
  # Run the Demucs command
52
  process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
53
 
54
+ # Simulate a loading animation
55
+ with Progress(
56
+ SpinnerColumn(),
57
+ TextColumn("[progress.description]{task.description}"),
58
+ BarColumn(),
59
+ TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
60
+ TimeRemainingColumn(),
61
+ console=console
62
+ ) as progress:
63
+ task = progress.add_task("[cyan]Separating stems...", total=100)
64
+ while process.poll() is None:
65
+ progress.update(task, advance=1)
66
+ time.sleep(0.1)
67
+ progress.update(task, completed=100)
68
 
69
  if process.returncode != 0:
70
  error_output = process.stderr.read()
71
+ yield None, stream_log(f"Error: Separation failed", "color: #F44336;")
 
72
  raise gr.Error(f"Demucs separation failed. Check the logs for details.")
73
 
74
  except Exception as e:
75
+ yield None, stream_log(f"Unexpected error: {str(e)}", "color: #F44336;")
76
  raise gr.Error(f"An unexpected error occurred: {str(e)}")
77
 
78
+ yield None, stream_log("Separation completed successfully!", "color: #4CAF50; font-weight: bold;")
79
+ time.sleep(0.5) # Pause for effect
80
+
81
+ yield None, stream_log("Processing stems...", "color: #9C27B0;")
82
+ time.sleep(0.5) # Simulate processing time
83
 
84
  # Change the stem search directory using full path
85
  stem_search_dir = os.path.join(base_output_dir, model_name, os.path.splitext(os.path.basename(audio_file))[0])
 
122
  yield None, stream_log(f"Final selected stems: {selected_stems}")
123
 
124
  if not selected_stems:
125
+ yield None, stream_log("Error: No stems selected for mixing", "color: #F44336;")
126
  raise gr.Error("Please select at least one stem to mix and ensure it was successfully separated.")
127
 
128
  output_file: str = os.path.join(output_dir, "mixed.wav")
129
+ yield None, stream_log("Mixing selected stems...", "color: #FF5722;")
130
+ time.sleep(0.5) # Simulate mixing time
131
 
132
  if len(selected_stems) == 1:
133
+ mixed_audio = AudioSegment.from_wav(selected_stems[0])
134
+ mixed_audio.export(output_file, format="wav")
135
  else:
136
  mixed_audio: AudioSegment = AudioSegment.empty()
137
  for stem_path in selected_stems:
 
139
  mixed_audio.export(output_file, format="wav")
140
 
141
  if mp3:
142
+ yield None, stream_log(f"Converting to MP3...", "color: #795548;")
143
+ time.sleep(0.5) # Simulate conversion time
144
  mp3_output_file: str = os.path.splitext(output_file)[0] + ".mp3"
145
  mixed_audio.export(mp3_output_file, format="mp3", bitrate=str(mp3_bitrate) + "k")
146
  output_file = mp3_output_file
147
 
148
+ yield None, stream_log("Process completed successfully!", "color: #4CAF50; font-weight: bold;")
149
+ yield output_file, gr.HTML(
150
+ Panel.fit(
151
+ Text("Separation and mixing completed successfully!", style="bold green"),
152
+ title="Demucs Result",
153
+ border_style="green"
154
+ ).render()
155
+ )
156
 
157
  # Define the Gradio interface
158
  with gr.Blocks() as iface: