ASesYusuf1 commited on
Commit
be32e81
·
verified ·
1 Parent(s): 8a49b0c

Update processing.py

Browse files
Files changed (1) hide show
  1. processing.py +150 -33
processing.py CHANGED
@@ -85,8 +85,19 @@ def refresh_auto_output():
85
  except Exception as e:
86
  return None, f"Error refreshing output: {str(e)}"
87
 
 
 
 
 
 
 
 
 
 
 
88
  def update_progress_html(progress_label, progress_percent):
89
- progress_percent = min(max(round(progress_percent), 0), 100) # %1 hassasiyet ve sınır kontrolü
 
90
  return f"""
91
  <div id="custom-progress" style="margin-top: 10px;">
92
  <div style="font-size: 1rem; color: #C0C0C0; margin-bottom: 5px;" id="progress-label">{progress_label}</div>
@@ -104,6 +115,103 @@ def extract_model_name_from_checkpoint(checkpoint_path):
104
  print(f"Original checkpoint path: {checkpoint_path}, extracted model_name: {model_name}")
105
  return model_name.strip()
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  def run_command_and_process_files(
108
  model_type,
109
  config_path,
@@ -141,8 +249,9 @@ def run_command_and_process_files(
141
  os.makedirs(OUTPUT_DIR, exist_ok=True)
142
 
143
  # Komut oluştur
 
144
  cmd_parts = [
145
- "python", "-m", "inference",
146
  "--model_type", str(model_type),
147
  "--config_path", str(config_path),
148
  "--start_check_point", str(start_check_point),
@@ -188,7 +297,7 @@ def run_command_and_process_files(
188
  stdout_output += line + "\n"
189
  if i18n("loaded_audio").lower() in line.lower():
190
  processed_files += 1
191
- progress_value = round((processed_files / total_files) * 80)
192
  if progress is not None and callable(getattr(progress, '__call__', None)):
193
  progress(progress_value / 100, desc=i18n("running_separation").format(processed_files, total_files))
194
  update_progress_html(i18n("running_separation").format(processed_files, total_files), progress_value)
@@ -217,7 +326,7 @@ def run_command_and_process_files(
217
  filename_model = extract_model_name_from_checkpoint(start_check_point)
218
  output_files = sorted(os.listdir(OUTPUT_DIR))
219
  if not output_files:
220
- raise FileNotFoundError("No output files created in OUTPUT_DIR")
221
 
222
  # Dosya yeniden adlandırma: 80-90%
223
  total_output_files = len(output_files)
@@ -248,7 +357,7 @@ def run_command_and_process_files(
248
 
249
  output_files = sorted(os.listdir(OUTPUT_DIR))
250
  if not output_files:
251
- raise FileNotFoundError("No output files in OUTPUT_DIR after renaming")
252
 
253
  # Çıktıları eşleştir
254
  def find_file(keyword):
@@ -270,38 +379,47 @@ def run_command_and_process_files(
270
  for i, output_file in enumerate(output_list):
271
  if output_file and os.path.exists(output_file):
272
  normalized_file = os.path.join(OUTPUT_DIR, f"{sanitize_filename(os.path.splitext(os.path.basename(output_file))[0])}.{output_format}")
273
- if output_file.endswith(f".{output_format}") and output_file != normalized_file:
274
- shutil.copy(output_file, normalized_file)
275
- elif output_file != normalized_file:
276
- audio, sr = librosa.load(output_file, sr=None, mono=False)
277
- sf.write(normalized_file, audio.T if audio.ndim > 1 else audio, sr)
278
- else:
279
- normalized_file = output_file
280
- normalized_outputs.append(normalized_file)
281
-
282
- progress_value = round(90 + (i + 1) / len(output_list) * 5)
283
- if progress is not None and callable(getattr(progress, '__call__', None)):
284
- progress(progress_value / 100, desc=f"Normalizing output {i+1}/{len(output_list)}")
285
- update_progress_html(f"Normalizing output {i+1}/{len(output_list)}", progress_value)
 
 
 
 
286
  else:
287
  normalized_outputs.append(None)
288
 
289
  # Apollo işlemi: 95-100%
290
  if use_apollo:
291
- from apollo_processing import process_with_apollo # Varsayılan modül
292
- normalized_outputs = process_with_apollo(
293
- output_files=normalized_outputs,
294
- output_dir=OUTPUT_DIR,
295
- apollo_chunk_size=apollo_chunk_size,
296
- apollo_overlap=apollo_overlap,
297
- apollo_method=apollo_method,
298
- apollo_normal_model=apollo_normal_model,
299
- apollo_midside_model=apollo_midside_model,
300
- output_format=output_format,
301
- progress=lambda p, desc: progress((95 + p * 5) / 100, desc=desc) if progress else None,
302
- total_progress_start=95,
303
- total_progress_end=100
304
- )
 
 
 
 
 
305
 
306
  # Tamamlandı
307
  if progress is not None and callable(getattr(progress, '__call__', None)):
@@ -313,7 +431,6 @@ def run_command_and_process_files(
313
 
314
  except Exception as e:
315
  logging.error(f"run_command_and_process_files error: {str(e)}")
316
- import traceback
317
  traceback.print_exc(file=sys.stderr)
318
  return (None,) * 14
319
 
 
85
  except Exception as e:
86
  return None, f"Error refreshing output: {str(e)}"
87
 
88
+ import logging
89
+
90
+ # Loglama ayarları
91
+ logging.basicConfig(
92
+ level=logging.DEBUG,
93
+ filename='utils.log',
94
+ filemode='a',
95
+ format='%(asctime)s - %(levelname)s - %(message)s'
96
+ )
97
+
98
  def update_progress_html(progress_label, progress_percent):
99
+ """Gradio arayüzü için ilerleme çubuğu HTML'si oluşturur."""
100
+ progress_percent = min(max(round(progress_percent), 0), 100) # %1 hassasiyet
101
  return f"""
102
  <div id="custom-progress" style="margin-top: 10px;">
103
  <div style="font-size: 1rem; color: #C0C0C0; margin-bottom: 5px;" id="progress-label">{progress_label}</div>
 
115
  print(f"Original checkpoint path: {checkpoint_path}, extracted model_name: {model_name}")
116
  return model_name.strip()
117
 
118
+ Hata mesajlarını inceledim ve sorun, run_command_and_process_files fonksiyonunda logging modülünün tanımlı olmaması nedeniyle ortaya çıkıyor. Bu, NameError: name 'logging' is not defined hatasına neden oluyor. Ayrıca, önceki konuşmalarımızda tqdm'yi kaldırarak time modülüyle %1'lik artışlarla (örneğin %23, %24, %25) ilerleme takibi yapmayı hedeflediğimiz için, bu entegrasyonu da tutarlı bir şekilde uygulayacağız. Aşağıda, hatayı çözmek ve istenen ilerleme takibini sağlamak için adım adım çözüm sunuyorum.
119
+
120
+ Hata Analizi
121
+ Hata Detayları:
122
+ Birincil Hata: logging.info çağrısı, logging modülünün run_command_and_process_files fonksiyonunda tanımlı olmaması nedeniyle NameError üretiyor (satır 128, processing.py).
123
+ İkincil Hata: Hata işleme bloğunda (except bloğu, satır 315), yine logging.error çağrısı aynı NameError'ü tetikliyor.
124
+ Dosya ve Konum: Hata, /home/user/app/processing.py içinde run_command_and_process_files fonksiyonunda meydana geliyor.
125
+ Bağlam: process_audio fonksiyonu, run_command_and_process_files üzerinden bir ses dosyasını işlerken bu hatayla karşılaşıyor.
126
+ Olası Nedenler:
127
+ logging modülü, processing.py dosyasında içe aktarılmamış.
128
+ Önceki kod düzenlemelerinde logging import'u atlanmış veya yanlışlıkla silinmiş.
129
+ run_command_and_process_files fonksiyonu, bağımsız bir modül olarak çalıştırıldığında bağımlılıkları eksik olabilir.
130
+ Hedefler:
131
+ NameError hatasını çözmek için logging modülünü processing.py dosyasına ekleyeceğiz.
132
+ run_command_and_process_files fonksiyonunu, tqdm'yi tamamen kaldırarak ve time modülüyle %1'lik ilerleme güncellemeleriyle Gradio arayüzüne uyumlu hale getireceğiz.
133
+ process_audio ve ilgili fonksiyonların hata yönetimini güçlendireceğiz.
134
+ ZeroGPU (Hugging Face Spaces) ortamında uyumluluğu koruyacağız.
135
+ Çözüm
136
+ 1. logging Modülünü Ekleme
137
+ NameError'ü çözmek için processing.py dosyasına logging modülünü içe aktaracağız ve loglama ayarlarını yapılandıracağız. Ayrıca, log dosyasının (utils.log) doğru çalıştığından emin olacağız.
138
+
139
+ python
140
+
141
+ Collapse
142
+
143
+ Wrap
144
+
145
+ Run
146
+
147
+ Copy
148
+ import logging
149
+
150
+ # Loglama ayarları
151
+ logging.basicConfig(
152
+ level=logging.DEBUG,
153
+ filename='utils.log',
154
+ filemode='a',
155
+ format='%(asctime)s - %(levelname)s - %(message)s'
156
+ )
157
+ Bu kodu processing.py dosyasının en üstüne ekleyeceğiz.
158
+
159
+ 2. run_command_and_process_files Fonksiyonunu Güncelleme
160
+ run_command_and_process_files fonksiyonunu, logging hatasını düzelterek, tqdm'yi kaldırarak ve time modülüyle %1'lik ilerleme takibi ekleyerek güncelliyoruz. Ayrıca, hata yönetimini güçlendirelim ve Gradio arayüzüyle uyumluluğu sağlayalım.
161
+
162
+ Aşağıda, güncellenmiş run_command_and_process_files fonksiyonu:
163
+
164
+ python
165
+
166
+ Collapse
167
+
168
+ Wrap
169
+
170
+ Run
171
+
172
+ Copy
173
+ import subprocess
174
+ import shutil
175
+ import time
176
+ import glob
177
+ import os
178
+ import librosa
179
+ import soundfile as sf
180
+ import sys
181
+ import traceback
182
+ import logging
183
+
184
+ # Loglama ayarları
185
+ logging.basicConfig(
186
+ level=logging.DEBUG,
187
+ filename='utils.log',
188
+ filemode='a',
189
+ format='%(asctime)s - %(levelname)s - %(message)s'
190
+ )
191
+
192
+ from assets.i18n.i18n import I18nAuto
193
+ i18n = I18nAuto()
194
+
195
+ def extract_model_name_from_checkpoint(checkpoint_path):
196
+ """Checkpoint dosya adından model adını çıkarır."""
197
+ return os.path.splitext(os.path.basename(checkpoint_path))[0]
198
+
199
+ def sanitize_filename(filename):
200
+ """Dosya adını güvenli hale getirir."""
201
+ return "".join(c if c.isalnum() or c in "._-" else "-" for c in filename)
202
+
203
+ def update_progress_html(progress_label, progress_percent):
204
+ """Gradio arayüzü için ilerleme çubuğu HTML'si oluşturur."""
205
+ progress_percent = min(max(round(progress_percent), 0), 100) # %1 hassasiyet
206
+ return f"""
207
+ <div id="custom-progress" style="margin-top: 10px;">
208
+ <div style="font-size: 1rem; color: #C0C0C0; margin-bottom: 5px;" id="progress-label">{progress_label}</div>
209
+ <div style="width: 100%; background-color: #444; border-radius: 5px; overflow: hidden;">
210
+ <div id="progress-bar" style="width: {progress_percent}%; height: 20px; background-color: #6e8efb; transition: width 0.3s; max-width: 100%;"></div>
211
+ </div>
212
+ </div>
213
+ """
214
+
215
  def run_command_and_process_files(
216
  model_type,
217
  config_path,
 
249
  os.makedirs(OUTPUT_DIR, exist_ok=True)
250
 
251
  # Komut oluştur
252
+ INFERENCE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "inference.py")
253
  cmd_parts = [
254
+ "python", INFERENCE_PATH,
255
  "--model_type", str(model_type),
256
  "--config_path", str(config_path),
257
  "--start_check_point", str(start_check_point),
 
297
  stdout_output += line + "\n"
298
  if i18n("loaded_audio").lower() in line.lower():
299
  processed_files += 1
300
+ progress_value = round(processed_files * base_progress_per_file)
301
  if progress is not None and callable(getattr(progress, '__call__', None)):
302
  progress(progress_value / 100, desc=i18n("running_separation").format(processed_files, total_files))
303
  update_progress_html(i18n("running_separation").format(processed_files, total_files), progress_value)
 
326
  filename_model = extract_model_name_from_checkpoint(start_check_point)
327
  output_files = sorted(os.listdir(OUTPUT_DIR))
328
  if not output_files:
329
+ raise FileNotFoundError(i18n("no_output_files").format(OUTPUT_DIR))
330
 
331
  # Dosya yeniden adlandırma: 80-90%
332
  total_output_files = len(output_files)
 
357
 
358
  output_files = sorted(os.listdir(OUTPUT_DIR))
359
  if not output_files:
360
+ raise FileNotFoundError(i18n("no_output_files_after_rename").format(OUTPUT_DIR))
361
 
362
  # Çıktıları eşleştir
363
  def find_file(keyword):
 
379
  for i, output_file in enumerate(output_list):
380
  if output_file and os.path.exists(output_file):
381
  normalized_file = os.path.join(OUTPUT_DIR, f"{sanitize_filename(os.path.splitext(os.path.basename(output_file))[0])}.{output_format}")
382
+ try:
383
+ if output_file.endswith(f".{output_format}") and output_file != normalized_file:
384
+ shutil.copy(output_file, normalized_file)
385
+ elif output_file != normalized_file:
386
+ audio, sr = librosa.load(output_file, sr=None, mono=False)
387
+ sf.write(normalized_file, audio.T if audio.ndim > 1 else audio, sr)
388
+ else:
389
+ normalized_file = output_file
390
+ normalized_outputs.append(normalized_file)
391
+
392
+ progress_value = round(90 + (i + 1) / len(output_list) * 5)
393
+ if progress is not None and callable(getattr(progress, '__call__', None)):
394
+ progress(progress_value / 100, desc=i18n("normalizing_output").format(i + 1, len(output_list)))
395
+ update_progress_html(i18n("normalizing_output").format(i + 1, len(output_list), progress_value))
396
+ except Exception as e:
397
+ logging.error(f"Normalization failed for {output_file}: {e}")
398
+ normalized_outputs.append(None)
399
  else:
400
  normalized_outputs.append(None)
401
 
402
  # Apollo işlemi: 95-100%
403
  if use_apollo:
404
+ try:
405
+ from apollo_processing import process_with_apollo
406
+ normalized_outputs = process_with_apollo(
407
+ output_files=normalized_outputs,
408
+ output_dir=OUTPUT_DIR,
409
+ apollo_chunk_size=apollo_chunk_size,
410
+ apollo_overlap=apollo_overlap,
411
+ apollo_method=apollo_method,
412
+ apollo_normal_model=apollo_normal_model,
413
+ apollo_midside_model=apollo_midside_model,
414
+ output_format=output_format,
415
+ progress=lambda p, desc: progress((95 + p * 5) / 100, desc=desc) if progress else None,
416
+ total_progress_start=95,
417
+ total_progress_end=100
418
+ )
419
+ except ImportError:
420
+ logging.warning("apollo_processing module not found, skipping Apollo processing")
421
+ except Exception as e:
422
+ logging.error(f"Apollo processing failed: {e}")
423
 
424
  # Tamamlandı
425
  if progress is not None and callable(getattr(progress, '__call__', None)):
 
431
 
432
  except Exception as e:
433
  logging.error(f"run_command_and_process_files error: {str(e)}")
 
434
  traceback.print_exc(file=sys.stderr)
435
  return (None,) * 14
436