ray-006 commited on
Commit
624ca3b
·
verified ·
1 Parent(s): 11fa35c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -23
app.py CHANGED
@@ -1,38 +1,63 @@
1
  import os
2
  import gradio as gr
3
  from audio_separator.separator import Separator
4
- import tempfile
5
  import shutil
6
  import threading
7
  import time
8
-
9
-
10
- def delayed_delete(path, delay=1800):
11
- """Delete a file or directory after a delay (default: 30 minutes)."""
12
-
13
- def command():
14
- time.sleep(delay)
 
 
 
 
 
 
 
 
 
15
  try:
16
- if os.path.isdir(path):
17
- shutil.rmtree(path)
18
- elif os.path.isfile(path):
19
- os.remove(path)
20
- print(f"Cleanup: Deleted {path}")
 
 
 
 
 
 
 
 
 
21
  except Exception as e:
22
- print(f"Cleanup error for {path}: {e}")
 
 
 
23
 
24
- threading.Thread(target=command, daemon=True).start()
 
25
 
26
 
27
  def separate_audio(input_file, model_name):
28
  if input_file is None:
29
  return (None, None, None, None, None, None)
30
 
31
- temp_dir = tempfile.mkdtemp()
 
 
 
 
32
 
33
  try:
34
  separator = Separator(
35
- output_dir=temp_dir,
36
  output_format="MP3",
37
  output_bitrate="128k",
38
  )
@@ -44,18 +69,21 @@ def separate_audio(input_file, model_name):
44
  results = []
45
 
46
  for stem in stems:
 
47
  match = next(
48
- (os.path.join(temp_dir, f) for f in output_files if stem in f),
49
  None,
50
  )
51
  results.append(match)
52
 
53
- delayed_delete(temp_dir, delay=1800)
 
54
  return tuple(results)
55
 
56
  except Exception as e:
57
- if os.path.exists(temp_dir):
58
- shutil.rmtree(temp_dir)
 
59
  raise RuntimeError(f"Separation failed: {e}") from e
60
 
61
 
@@ -114,7 +142,7 @@ with gr.Blocks() as demo:
114
  )
115
 
116
  gr.Markdown(
117
- "⚠️ **Note:** Processing may take 1–2 minutes depending on file length and Space hardware."
118
  )
119
 
120
 
@@ -125,4 +153,4 @@ if __name__ == "__main__":
125
  primary_hue="indigo",
126
  secondary_hue="blue",
127
  ),
128
- )
 
1
  import os
2
  import gradio as gr
3
  from audio_separator.separator import Separator
 
4
  import shutil
5
  import threading
6
  import time
7
+ import uuid
8
+
9
+ # Configuration
10
+ # Directory where files will be stored temporarily
11
+ UPLOAD_DIR = "output_storage"
12
+ MAX_FILE_AGE = 1800
13
+
14
+ # Ensure the storage directory exists
15
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
16
+
17
+ def cleanup_scheduler():
18
+ """
19
+ Background task that runs forever.
20
+ It scans the UPLOAD_DIR every minute and deletes folders older than MAX_FILE_AGE.
21
+ """
22
+ while True:
23
  try:
24
+ current_time = time.time()
25
+ # Iterate over all items in the storage directory
26
+ for filename in os.listdir(UPLOAD_DIR):
27
+ file_path = os.path.join(UPLOAD_DIR, filename)
28
+
29
+ # Check if it's a directory (we create one folder per request)
30
+ if os.path.isdir(file_path):
31
+ # Get the folder's creation/modification time
32
+ file_age = current_time - os.path.getmtime(file_path)
33
+
34
+ if file_age > MAX_FILE_AGE:
35
+ print(f"🧹 Cleanup: Removing old folder {filename} ({int(file_age)}s old)")
36
+ shutil.rmtree(file_path)
37
+
38
  except Exception as e:
39
+ print(f"Error during cleanup: {e}")
40
+
41
+ # Wait for 60 seconds before checking again
42
+ time.sleep(60)
43
 
44
+ # Start the cleanup thread immediately (Daemon means it dies when the main app dies)
45
+ threading.Thread(target=cleanup_scheduler, daemon=True).start()
46
 
47
 
48
  def separate_audio(input_file, model_name):
49
  if input_file is None:
50
  return (None, None, None, None, None, None)
51
 
52
+ # Create a unique subfolder for this specific request inside our managed directory
53
+ # Using UUID ensures no filename collisions between users
54
+ session_id = str(uuid.uuid4())
55
+ session_dir = os.path.join(UPLOAD_DIR, session_id)
56
+ os.makedirs(session_dir, exist_ok=True)
57
 
58
  try:
59
  separator = Separator(
60
+ output_dir=session_dir,
61
  output_format="MP3",
62
  output_bitrate="128k",
63
  )
 
69
  results = []
70
 
71
  for stem in stems:
72
+ # Find the file that matches the stem name
73
  match = next(
74
+ (os.path.join(session_dir, f) for f in output_files if stem in f),
75
  None,
76
  )
77
  results.append(match)
78
 
79
+ # Note: We do NOT call a delete function here anymore.
80
+ # The background scheduler will handle it later.
81
  return tuple(results)
82
 
83
  except Exception as e:
84
+ # If the actual separation fails, clean up this specific failed folder immediately
85
+ if os.path.exists(session_dir):
86
+ shutil.rmtree(session_dir)
87
  raise RuntimeError(f"Separation failed: {e}") from e
88
 
89
 
 
142
  )
143
 
144
  gr.Markdown(
145
+ "⚠️ **Note:** Processing may take 1–2 minutes. Files are automatically cleaned up after 1 hour."
146
  )
147
 
148
 
 
153
  primary_hue="indigo",
154
  secondary_hue="blue",
155
  ),
156
+ )