Opera8 commited on
Commit
b281264
·
verified ·
1 Parent(s): f6b0fbc

Create yml/separate-audio.py

Browse files
Files changed (1) hide show
  1. yml/separate-audio.py +167 -0
yml/separate-audio.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import requests
4
+ from gradio_client import Client, handle_file
5
+
6
+ raw_prompt = os.environ.get('PROMPT', '')
7
+ run_id = os.environ.get('RUN_ID', '')
8
+ space_url = os.environ.get('SPACE_URL', '')
9
+ github_run_id = os.environ.get('GITHUB_RUN_ID', '')
10
+
11
+ def report_failure(error_msg):
12
+ try:
13
+ requests.post(
14
+ f"{space_url}/api/webhook/fail",
15
+ json={
16
+ "run_id": run_id,
17
+ "error": error_msg,
18
+ "event_type": "separate-audio",
19
+ "client_payload": {
20
+ "prompt": raw_prompt,
21
+ "run_id": run_id,
22
+ "space_url": space_url
23
+ },
24
+ "github_run_id": github_run_id
25
+ },
26
+ timeout=15
27
+ )
28
+ except Exception as e:
29
+ print(f"Failed to report failure: {e}")
30
+
31
+ print('1. Decoding configuration from separate payload...')
32
+ if not raw_prompt.startswith("VOICECONFIG_SEPARATE_"):
33
+ err_str = "Error: Invalid separate configuration payload signature."
34
+ print(err_str)
35
+ report_failure(err_str)
36
+ sys.exit(1)
37
+
38
+ config_str = raw_prompt[len("VOICECONFIG_SEPARATE_"):]
39
+ parts = config_str.split("_")
40
+ config = {}
41
+ i = 0
42
+ while i < len(parts) - 1:
43
+ key = parts[i]
44
+ val = parts[i+1]
45
+ config[key] = val
46
+ i += 2
47
+
48
+ user_run_id = config.get("userRunId", run_id)
49
+ ext = config.get("ext", "mp3")
50
+ stem = config.get("stem", "vocal")
51
+
52
+ # تبدیل مقادیر رشته‌ای به مقادیر و متغیرهای اصلی پایتون
53
+ main = config.get("main", "false").lower() == "true"
54
+ dereverb = config.get("dereverb", "false").lower() == "true"
55
+ vocal_effects = config.get("vocEff", "false").lower() == "true"
56
+ background_effects = config.get("bgEff", "false").lower() == "true"
57
+
58
+ vocal_reverb_room_size = float(config.get("vRevRoom", "0.15"))
59
+ vocal_reverb_damping = float(config.get("vRevDamp", "0.7"))
60
+ vocal_reverb_dryness = float(config.get("vRevDry", "0.8"))
61
+ vocal_reverb_wet_level = float(config.get("vRevWet", "0.2"))
62
+ vocal_delay_seconds = float(config.get("vDelaySec", "0.0"))
63
+ vocal_delay_mix = float(config.get("vDelayMix", "0.0"))
64
+ vocal_compressor_threshold_db = float(config.get("vCompThresh", "-15"))
65
+ vocal_compressor_ratio = float(config.get("vCompRatio", "4"))
66
+ vocal_compressor_attack_ms = float(config.get("vCompAttack", "1"))
67
+ vocal_compressor_release_ms = float(config.get("vCompRelease", "100"))
68
+ vocal_gain_db = float(config.get("vGain", "0"))
69
+
70
+ background_highpass_freq = float(config.get("bgHigh", "120"))
71
+ background_lowpass_freq = float(config.get("bgLow", "11000"))
72
+ background_reverb_room_size = float(config.get("bgRevRoom", "0.1"))
73
+ background_reverb_damping = float(config.get("bgRevDamp", "0.5"))
74
+ background_reverb_wet_level = float(config.get("bgRevWet", "0.25"))
75
+ background_compressor_threshold_db = float(config.get("bgCompThresh", "-15"))
76
+ background_compressor_ratio = float(config.get("bgCompRatio", "4"))
77
+ background_compressor_attack_ms = float(config.get("bgCompAttack", "15"))
78
+ background_compressor_release_ms = float(config.get("bgCompRelease", "60"))
79
+ background_gain_db = float(config.get("bgGain", "0"))
80
+ target_format = config.get("format", "WAV")
81
+
82
+ input_audio_url = f"{space_url}/static/images/{user_run_id}_input.{ext}"
83
+ local_input = f"input.{ext}"
84
+
85
+ print("2. Downloading source audio from host...")
86
+ try:
87
+ r_input = requests.get(input_audio_url, timeout=60)
88
+ if r_input.status_code != 200:
89
+ raise Exception(f"Input audio download failed. Status: {r_input.status_code}")
90
+ with open(local_input, 'wb') as f:
91
+ f.write(r_input.content)
92
+ except Exception as download_err:
93
+ err_str = f"Error downloading source files: {download_err}"
94
+ print(err_str)
95
+ report_failure(err_str)
96
+ sys.exit(1)
97
+
98
+ print("3. Connecting to Audio Separator Space...")
99
+ try:
100
+ client = Client("https://r3gm-audio-separator.hf.space/")
101
+
102
+ print("4. Executing separation engine...")
103
+ result = client.predict(
104
+ handle_file(local_input),
105
+ [stem],
106
+ main,
107
+ dereverb,
108
+ vocal_effects,
109
+ background_effects,
110
+ vocal_reverb_room_size,
111
+ vocal_reverb_damping,
112
+ vocal_reverb_dryness,
113
+ vocal_reverb_wet_level,
114
+ vocal_delay_seconds,
115
+ vocal_delay_mix,
116
+ vocal_compressor_threshold_db,
117
+ vocal_compressor_ratio,
118
+ vocal_compressor_attack_ms,
119
+ vocal_compressor_release_ms,
120
+ vocal_gain_db,
121
+ background_highpass_freq,
122
+ background_lowpass_freq,
123
+ background_reverb_room_size,
124
+ background_reverb_damping,
125
+ background_reverb_wet_level,
126
+ background_compressor_threshold_db,
127
+ background_compressor_ratio,
128
+ background_compressor_attack_ms,
129
+ background_compressor_release_ms,
130
+ background_gain_db,
131
+ target_format,
132
+ fn_index=3
133
+ )
134
+
135
+ def parse_file_response(f):
136
+ if not f: return None
137
+ if isinstance(f, (list, tuple)):
138
+ if len(f) > 0:
139
+ return parse_file_response(f[0])
140
+ if isinstance(f, dict):
141
+ return f.get('path') or f.get('name')
142
+ return str(f)
143
+
144
+ final_audio_path = parse_file_response(result)
145
+
146
+ if not final_audio_path or not os.path.exists(str(final_audio_path)):
147
+ raise Exception("Audio separation output file was not found or invalid.")
148
+
149
+ print("5. Uploading result file back...")
150
+ ext_out = target_format.lower()
151
+ with open(final_audio_path, 'rb') as f:
152
+ res_upload = requests.post(
153
+ f'{space_url}/api/webhook/upload',
154
+ data={'run_id': run_id, 'github_run_id': github_run_id, 'ext': ext_out},
155
+ files={'file': f}
156
+ )
157
+
158
+ if res_upload.status_code == 200:
159
+ print('6. SUCCESS! Process complete.')
160
+ else:
161
+ raise Exception(f"Webhook upload failed. Status code: {res_upload.status_code}")
162
+
163
+ except Exception as e:
164
+ err_str = str(e)
165
+ print(f"CRITICAL ERROR during separation: {err_str}")
166
+ report_failure(err_str)
167
+ sys.exit(1)