pedroapfilho commited on
Commit
6c32e21
·
unverified ·
1 Parent(s): 5ae1ea5

Use HF dataset repo as source of truth for dataset.json

Browse files

Push dataset.json to HF repo after every label/preprocess batch so
progress persists across ephemeral Space restarts. On download, pull
the JSON back and restore labels before scanning.

- Add upload_dataset_json_to_hf() and pull dataset.json in download
- Remove hf_token param (use HF_TOKEN env var)
- Reconcile stale .pt preprocessed flags on restart
- Simplify Data Source UI: remove upload files, HF token, resume accordion
- Add batch mode (max_count) for labeling and preprocessing
- Add preprocessed flag to AudioSample, scan dedup via existing_paths
- Make @spaces.GPU a no-op when running locally

acestep/training/dataset_builder_modules/core.py CHANGED
@@ -18,3 +18,7 @@ class CoreMixin:
18
  def get_labeled_count(self) -> int:
19
  """Get the number of labeled samples."""
20
  return sum(1 for s in self.samples if s.labeled)
 
 
 
 
 
18
  def get_labeled_count(self) -> int:
19
  """Get the number of labeled samples."""
20
  return sum(1 for s in self.samples if s.labeled)
21
+
22
+ def get_preprocessed_count(self) -> int:
23
+ """Get the number of preprocessed samples."""
24
+ return sum(1 for s in self.samples if s.preprocessed)
acestep/training/dataset_builder_modules/label_all.py CHANGED
@@ -14,9 +14,14 @@ class LabelAllMixin:
14
  transcribe_lyrics: bool = False,
15
  skip_metas: bool = False,
16
  only_unlabeled: bool = False,
 
17
  progress_callback=None,
18
  ) -> Tuple[List[AudioSample], str]:
19
- """Label all samples in the dataset."""
 
 
 
 
20
  if not self.samples:
21
  return [], "❌ No samples to label. Please scan a directory first."
22
 
@@ -30,6 +35,9 @@ class LabelAllMixin:
30
  if not samples_to_label:
31
  return self.samples, "✅ All samples already labeled"
32
 
 
 
 
33
  success_count = 0
34
  fail_count = 0
35
  total = len(samples_to_label)
@@ -53,10 +61,13 @@ class LabelAllMixin:
53
  else:
54
  fail_count += 1
55
 
56
- status_msg = f"✅ Labeled {success_count}/{total} samples"
 
 
 
 
57
  if fail_count > 0:
58
  status_msg += f" ({fail_count} failed)"
59
- if only_unlabeled:
60
- status_msg += f" (unlabeled only, {len(self.samples)} total)"
61
 
62
  return self.samples, status_msg
 
14
  transcribe_lyrics: bool = False,
15
  skip_metas: bool = False,
16
  only_unlabeled: bool = False,
17
+ max_count: int = 0,
18
  progress_callback=None,
19
  ) -> Tuple[List[AudioSample], str]:
20
+ """Label all samples in the dataset.
21
+
22
+ Args:
23
+ max_count: When > 0, stop after labeling this many samples (batch mode).
24
+ """
25
  if not self.samples:
26
  return [], "❌ No samples to label. Please scan a directory first."
27
 
 
35
  if not samples_to_label:
36
  return self.samples, "✅ All samples already labeled"
37
 
38
+ batch_limit = max_count if max_count > 0 else len(samples_to_label)
39
+ samples_to_label = samples_to_label[:batch_limit]
40
+
41
  success_count = 0
42
  fail_count = 0
43
  total = len(samples_to_label)
 
61
  else:
62
  fail_count += 1
63
 
64
+ total_labeled = sum(1 for s in self.samples if s.labeled)
65
+ total_samples = len(self.samples)
66
+ remaining = total_samples - total_labeled
67
+
68
+ status_msg = f"✅ Labeled {success_count} this batch"
69
  if fail_count > 0:
70
  status_msg += f" ({fail_count} failed)"
71
+ status_msg += f" | {total_labeled}/{total_samples} labeled total, {remaining} remaining"
 
72
 
73
  return self.samples, status_msg
acestep/training/dataset_builder_modules/models.py CHANGED
@@ -31,6 +31,7 @@ class AudioSample:
31
  is_instrumental: bool = True
32
  custom_tag: str = ""
33
  labeled: bool = False
 
34
  prompt_override: Optional[str] = None # None=use global ratio, "caption" or "genre"
35
 
36
  def __post_init__(self):
 
31
  is_instrumental: bool = True
32
  custom_tag: str = ""
33
  labeled: bool = False
34
+ preprocessed: bool = False
35
  prompt_override: Optional[str] = None # None=use global ratio, "caption" or "genre"
36
 
37
  def __post_init__(self):
acestep/training/dataset_builder_modules/preprocess.py CHANGED
@@ -29,16 +29,30 @@ class PreprocessMixin:
29
  dit_handler,
30
  output_dir: str,
31
  max_duration: float = 240.0,
 
32
  progress_callback=None,
33
  ) -> Tuple[List[str], str]:
34
- """Preprocess all labeled samples to tensor files for efficient training."""
35
- debug_log_for("dataset", f"preprocess_to_tensors: output_dir='{output_dir}', max_duration={max_duration}")
 
 
 
 
36
  if not self.samples:
37
  return [], "❌ No samples to preprocess"
38
 
39
- labeled_samples = [s for s in self.samples if s.labeled]
 
 
 
 
 
40
  if not labeled_samples:
41
- return [], "❌ No labeled samples to preprocess"
 
 
 
 
42
 
43
  if dit_handler is None or dit_handler.model is None:
44
  return [], "❌ Model not initialized. Please initialize the service first."
@@ -190,6 +204,7 @@ class PreprocessMixin:
190
  torch.save(output_data, output_path)
191
  debug_end_verbose_for("dataset", f"torch.save[{i}]", t0)
192
  output_paths.append(output_path)
 
193
  success_count += 1
194
 
195
  except Exception as e:
@@ -202,8 +217,13 @@ class PreprocessMixin:
202
  save_manifest(output_dir, self.metadata, output_paths)
203
  debug_end_verbose_for("dataset", "save_manifest", t0)
204
 
205
- status = f"✅ Preprocessed {success_count}/{len(labeled_samples)} samples to {output_dir}"
 
 
 
 
206
  if fail_count > 0:
207
  status += f" ({fail_count} failed)"
 
208
 
209
  return output_paths, status
 
29
  dit_handler,
30
  output_dir: str,
31
  max_duration: float = 240.0,
32
+ max_count: int = 0,
33
  progress_callback=None,
34
  ) -> Tuple[List[str], str]:
35
+ """Preprocess labeled samples to tensor files for efficient training.
36
+
37
+ Args:
38
+ max_count: When > 0, stop after processing this many new samples (batch mode).
39
+ """
40
+ debug_log_for("dataset", f"preprocess_to_tensors: output_dir='{output_dir}', max_duration={max_duration}, max_count={max_count}")
41
  if not self.samples:
42
  return [], "❌ No samples to preprocess"
43
 
44
+ # Reset stale preprocessed flags (ephemeral .pt files may be gone after restart)
45
+ for s in self.samples:
46
+ if s.preprocessed and not os.path.exists(os.path.join(output_dir, f"{s.id}.pt")):
47
+ s.preprocessed = False
48
+
49
+ labeled_samples = [s for s in self.samples if s.labeled and not s.preprocessed]
50
  if not labeled_samples:
51
+ total_preprocessed = sum(1 for s in self.samples if s.preprocessed)
52
+ return [], f"✅ All labeled samples already preprocessed ({total_preprocessed} total)"
53
+
54
+ if max_count > 0:
55
+ labeled_samples = labeled_samples[:max_count]
56
 
57
  if dit_handler is None or dit_handler.model is None:
58
  return [], "❌ Model not initialized. Please initialize the service first."
 
204
  torch.save(output_data, output_path)
205
  debug_end_verbose_for("dataset", f"torch.save[{i}]", t0)
206
  output_paths.append(output_path)
207
+ sample.preprocessed = True
208
  success_count += 1
209
 
210
  except Exception as e:
 
217
  save_manifest(output_dir, self.metadata, output_paths)
218
  debug_end_verbose_for("dataset", "save_manifest", t0)
219
 
220
+ total_preprocessed = sum(1 for s in self.samples if s.preprocessed)
221
+ total_labeled = sum(1 for s in self.samples if s.labeled)
222
+ remaining = total_labeled - total_preprocessed
223
+
224
+ status = f"✅ Preprocessed {success_count} new samples"
225
  if fail_count > 0:
226
  status += f" ({fail_count} failed)"
227
+ status += f" | {total_preprocessed}/{total_labeled} done, {remaining} remaining"
228
 
229
  return output_paths, status
acestep/training/dataset_builder_modules/scan.py CHANGED
@@ -20,7 +20,7 @@ class ScanMixin:
20
  return [], f"❌ Not a directory: {directory}"
21
 
22
  self._current_dir = directory
23
- self.samples = []
24
 
25
  audio_files = []
26
  for root, _, files in os.walk(directory):
@@ -29,19 +29,27 @@ class ScanMixin:
29
  if ext in SUPPORTED_AUDIO_FORMATS:
30
  audio_files.append(os.path.join(root, file))
31
 
32
- if not audio_files:
 
 
 
 
 
 
 
 
 
 
33
  return [], (
34
  f"❌ No audio files found in {directory}\n"
35
  f"Supported formats: {', '.join(SUPPORTED_AUDIO_FORMATS)}"
36
  )
37
 
38
- audio_files.sort()
39
-
40
  csv_metadata = load_csv_metadata(directory)
41
  csv_count = 0
42
  lyrics_count = 0
43
 
44
- for audio_path in audio_files:
45
  try:
46
  duration = get_audio_duration(audio_path)
47
  lyrics_content, has_lyrics_file = load_lyrics_file(audio_path)
@@ -78,7 +86,9 @@ class ScanMixin:
78
 
79
  self.metadata.num_samples = len(self.samples)
80
 
81
- status = f"✅ Found {len(self.samples)} audio files in {directory}"
 
 
82
  if lyrics_count > 0:
83
  status += f"\n 📝 {lyrics_count} files have accompanying lyrics (.txt)"
84
  if csv_count > 0:
 
20
  return [], f"❌ Not a directory: {directory}"
21
 
22
  self._current_dir = directory
23
+ existing_paths = {s.audio_path for s in self.samples}
24
 
25
  audio_files = []
26
  for root, _, files in os.walk(directory):
 
29
  if ext in SUPPORTED_AUDIO_FORMATS:
30
  audio_files.append(os.path.join(root, file))
31
 
32
+ audio_files.sort()
33
+
34
+ new_audio_files = [f for f in audio_files if f not in existing_paths]
35
+
36
+ if not new_audio_files and existing_paths:
37
+ return self.samples, (
38
+ f"✅ No new audio files in {directory} "
39
+ f"({len(self.samples)} samples already loaded)"
40
+ )
41
+
42
+ if not new_audio_files:
43
  return [], (
44
  f"❌ No audio files found in {directory}\n"
45
  f"Supported formats: {', '.join(SUPPORTED_AUDIO_FORMATS)}"
46
  )
47
 
 
 
48
  csv_metadata = load_csv_metadata(directory)
49
  csv_count = 0
50
  lyrics_count = 0
51
 
52
+ for audio_path in new_audio_files:
53
  try:
54
  duration = get_audio_duration(audio_path)
55
  lyrics_content, has_lyrics_file = load_lyrics_file(audio_path)
 
86
 
87
  self.metadata.num_samples = len(self.samples)
88
 
89
+ new_count = len(new_audio_files)
90
+ total_count = len(self.samples)
91
+ status = f"✅ Added {new_count} new files ({total_count} total samples)"
92
  if lyrics_count > 0:
93
  status += f"\n 📝 {lyrics_count} files have accompanying lyrics (.txt)"
94
  if csv_count > 0:
app.py CHANGED
@@ -7,16 +7,24 @@ A comprehensive music generation system with three main interfaces:
7
  """
8
 
9
  import gradio as gr
 
10
  import torch
11
  import numpy as np
12
  from pathlib import Path
13
  import json
14
  from typing import Optional, List, Tuple
15
- import spaces
 
 
 
 
 
 
 
16
 
17
  from src.ace_step_engine import ACEStepEngine
18
  from src.timeline_manager import TimelineManager
19
- from src.lora_trainer import download_hf_dataset
20
  from src.audio_processor import AudioProcessor
21
  from src.utils import setup_logging, load_config
22
  from acestep.training.dataset_builder import DatasetBuilder
@@ -289,80 +297,99 @@ def timeline_reset(session_state: dict) -> Tuple[None, None, str, dict]:
289
  DATAFRAME_HEADERS = ["#", "Filename", "Duration", "Lyrics", "Labeled", "BPM", "Key", "Caption"]
290
 
291
 
 
 
 
 
 
 
 
 
 
 
292
  def _build_review_dataframe():
293
  """Build editable dataframe rows from current dataset builder state."""
294
  builder = get_dataset_builder()
295
  return builder.get_samples_dataframe_data()
296
 
297
 
298
- def lora_upload_and_scan(files, training_state):
299
- """Copy uploaded audio files to working dir and scan."""
300
  try:
301
- if not files:
302
- return "No files uploaded", training_state
303
 
304
- import shutil
 
305
 
306
- work_dir = Path("lora_training") / "uploaded"
307
- work_dir.mkdir(parents=True, exist_ok=True)
 
 
 
308
 
309
- for f in files:
310
- src = Path(f)
311
- shutil.copy2(str(src), str(work_dir / src.name))
312
 
313
  builder = get_dataset_builder()
314
- samples, status = builder.scan_directory(str(work_dir))
315
-
316
- training_state = training_state or {}
317
- training_state["audio_dir"] = str(work_dir)
318
 
319
- return f"Scanned {len(samples)} audio files from uploads", training_state
 
 
 
 
320
 
321
- except Exception as e:
322
- logger.error(f"Upload scan failed: {e}")
323
- return f"Error: {e}", training_state or {}
324
 
 
 
 
 
325
 
326
- def lora_download_hf(dataset_id, hf_token, max_files, training_state):
327
- """Download HuggingFace dataset and scan for audio files."""
328
- try:
329
- if not dataset_id or not dataset_id.strip():
330
- return "Enter a dataset ID (e.g. pedroapfilho/lofi-tracks)", training_state
331
 
332
- token = hf_token.strip() if hf_token else None
333
 
334
- local_dir, dl_status = download_hf_dataset(
335
- dataset_id.strip(), max_files=int(max_files), hf_token=token
336
- )
337
 
338
- if not local_dir:
339
- return f"Download failed: {dl_status}", training_state
340
 
 
 
 
341
  builder = get_dataset_builder()
342
- samples, scan_status = builder.scan_directory(local_dir)
 
 
343
 
344
  training_state = training_state or {}
345
- training_state["audio_dir"] = local_dir
 
 
 
 
346
 
347
- return f"{dl_status} | {scan_status}", training_state
348
 
349
  except Exception as e:
350
- logger.error(f"HF download failed: {e}")
351
- return f"Error: {e}", training_state or {}
352
 
353
 
354
  @spaces.GPU(duration=300)
355
- def lora_auto_label(training_state, progress=gr.Progress()):
356
- """Auto-label all samples using LLM analysis."""
357
  try:
358
  builder = get_dataset_builder()
359
 
360
  if builder.get_sample_count() == 0:
361
- return [], "No samples loaded. Upload files or download a dataset first."
362
 
363
  engine = get_ace_engine()
364
  if not engine.is_initialized():
365
- return [], "ACE-Step engine not initialized. Models may still be loading."
366
 
367
  def progress_callback(msg):
368
  progress(0, desc=msg)
@@ -370,14 +397,32 @@ def lora_auto_label(training_state, progress=gr.Progress()):
370
  samples, status = builder.label_all_samples(
371
  dit_handler=engine.dit_handler,
372
  llm_handler=engine.llm_handler,
 
 
373
  progress_callback=progress_callback,
374
  )
375
 
376
- return _build_review_dataframe(), status
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
 
378
  except Exception as e:
379
  logger.error(f"Auto-label failed: {e}")
380
- return [], f"Error: {e}"
381
 
382
 
383
  def lora_save_edits(df_data, training_state):
@@ -385,11 +430,22 @@ def lora_save_edits(df_data, training_state):
385
  try:
386
  builder = get_dataset_builder()
387
 
388
- if not df_data or len(df_data) == 0:
 
 
 
 
 
 
 
 
 
 
 
389
  return "No data to save"
390
 
391
  updated = 0
392
- for row in df_data:
393
  idx = int(row[0])
394
  updates = {}
395
 
@@ -421,17 +477,17 @@ def lora_save_edits(df_data, training_state):
421
 
422
 
423
  @spaces.GPU(duration=300)
424
- def lora_preprocess(training_state, progress=gr.Progress()):
425
- """Preprocess labeled samples to training tensors."""
426
  try:
427
  builder = get_dataset_builder()
428
 
429
  if builder.get_labeled_count() == 0:
430
- return "No labeled samples. Run auto-label first."
431
 
432
  engine = get_ace_engine()
433
  if not engine.is_initialized():
434
- return "ACE-Step engine not initialized."
435
 
436
  tensor_dir = str(Path("lora_training") / "tensors")
437
 
@@ -441,17 +497,34 @@ def lora_preprocess(training_state, progress=gr.Progress()):
441
  output_paths, status = builder.preprocess_to_tensors(
442
  dit_handler=engine.dit_handler,
443
  output_dir=tensor_dir,
 
444
  progress_callback=progress_callback,
445
  )
446
 
447
  training_state = training_state or {}
448
  training_state["tensor_dir"] = tensor_dir
449
 
450
- return status
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
 
452
  except Exception as e:
453
  logger.error(f"Preprocess failed: {e}")
454
- return f"Error: {e}"
455
 
456
 
457
  @spaces.GPU(duration=600)
@@ -740,41 +813,38 @@ def create_ui():
740
 
741
  training_state = gr.State(value={})
742
 
 
 
 
 
 
 
743
  with gr.Tabs():
744
 
745
  # ---------- Sub-tab 1: Data Source ----------
746
  with gr.Tab("1. Data Source"):
747
- gr.Markdown("Choose one: upload audio files or download from HuggingFace.")
 
 
 
748
 
 
 
 
 
749
  with gr.Row():
750
- with gr.Column():
751
- gr.Markdown("#### Upload Files")
752
- lora_files = gr.File(
753
- label="Audio Files (WAV, MP3, FLAC, OGG, OPUS)",
754
- file_count="multiple",
755
- file_types=["audio"],
756
- )
757
- lora_upload_btn = gr.Button(
758
- "Upload & Scan", variant="primary"
759
- )
760
-
761
- with gr.Column():
762
- gr.Markdown("#### HuggingFace Dataset")
763
- lora_hf_id = gr.Textbox(
764
- label="Dataset ID",
765
- placeholder="pedroapfilho/lofi-tracks",
766
- )
767
- lora_hf_token = gr.Textbox(
768
- label="HF Token (optional, for private repos)",
769
- type="password",
770
- )
771
- lora_hf_max = gr.Slider(
772
- minimum=1, maximum=500, value=50, step=1,
773
- label="Max files",
774
- )
775
- lora_hf_btn = gr.Button(
776
- "Download & Scan", variant="primary"
777
- )
778
 
779
  lora_source_status = gr.Textbox(
780
  label="Status", lines=2, interactive=False
@@ -786,11 +856,16 @@ def create_ui():
786
  "Auto-label samples using the LLM, then review and edit metadata."
787
  )
788
 
 
 
 
 
789
  lora_label_btn = gr.Button(
790
- "Auto-Label All Samples", variant="primary"
 
791
  )
792
  lora_label_status = gr.Textbox(
793
- label="Label Status", lines=2, interactive=False
794
  )
795
 
796
  lora_review_df = gr.Dataframe(
@@ -800,7 +875,11 @@ def create_ui():
800
  wrap=True,
801
  )
802
 
803
- lora_save_btn = gr.Button("Save Edits")
 
 
 
 
804
  lora_save_status = gr.Textbox(
805
  label="Save Status", interactive=False
806
  )
@@ -811,8 +890,12 @@ def create_ui():
811
  "Encode audio through VAE and text encoders to create training tensors."
812
  )
813
 
 
 
 
 
814
  lora_preprocess_btn = gr.Button(
815
- "Preprocess to Tensors", variant="primary"
816
  )
817
  lora_preprocess_status = gr.Textbox(
818
  label="Preprocess Status", lines=3, interactive=False
@@ -895,23 +978,17 @@ def create_ui():
895
  # ---------- Event handlers ----------
896
 
897
  # Data Source
898
- lora_upload_btn.click(
899
- fn=lora_upload_and_scan,
900
- inputs=[lora_files, training_state],
901
- outputs=[lora_source_status, training_state],
902
- )
903
-
904
  lora_hf_btn.click(
905
  fn=lora_download_hf,
906
- inputs=[lora_hf_id, lora_hf_token, lora_hf_max, training_state],
907
- outputs=[lora_source_status, training_state],
908
  )
909
 
910
  # Label & Review
911
  lora_label_btn.click(
912
  fn=lora_auto_label,
913
- inputs=[training_state],
914
- outputs=[lora_review_df, lora_label_status],
915
  )
916
 
917
  lora_save_btn.click(
@@ -920,11 +997,17 @@ def create_ui():
920
  outputs=[lora_save_status],
921
  )
922
 
 
 
 
 
 
 
923
  # Preprocess
924
  lora_preprocess_btn.click(
925
  fn=lora_preprocess,
926
- inputs=[training_state],
927
- outputs=[lora_preprocess_status],
928
  )
929
 
930
  # Train
 
7
  """
8
 
9
  import gradio as gr
10
+ import pandas as pd
11
  import torch
12
  import numpy as np
13
  from pathlib import Path
14
  import json
15
  from typing import Optional, List, Tuple
16
+ try:
17
+ import spaces
18
+ except ImportError:
19
+ # Local dev — make @spaces.GPU a no-op
20
+ class _Spaces:
21
+ def GPU(self, fn=None, **kwargs):
22
+ return fn if fn else lambda f: f
23
+ spaces = _Spaces()
24
 
25
  from src.ace_step_engine import ACEStepEngine
26
  from src.timeline_manager import TimelineManager
27
+ from src.lora_trainer import download_hf_dataset, upload_dataset_json_to_hf
28
  from src.audio_processor import AudioProcessor
29
  from src.utils import setup_logging, load_config
30
  from acestep.training.dataset_builder import DatasetBuilder
 
297
  DATAFRAME_HEADERS = ["#", "Filename", "Duration", "Lyrics", "Labeled", "BPM", "Key", "Caption"]
298
 
299
 
300
+ def _build_progress_summary():
301
+ """Build a one-line progress summary from current dataset builder state."""
302
+ builder = get_dataset_builder()
303
+ total = builder.get_sample_count()
304
+ labeled = builder.get_labeled_count()
305
+ preprocessed = builder.get_preprocessed_count()
306
+ remaining = total - labeled
307
+ return f"Total: {total} | Labeled: {labeled} | Preprocessed: {preprocessed} | Remaining: {remaining}"
308
+
309
+
310
  def _build_review_dataframe():
311
  """Build editable dataframe rows from current dataset builder state."""
312
  builder = get_dataset_builder()
313
  return builder.get_samples_dataframe_data()
314
 
315
 
316
+ def lora_download_hf(dataset_id, max_files, hf_offset, training_state):
317
+ """Download HuggingFace dataset batch, restore labels from HF repo, and scan."""
318
  try:
319
+ if not dataset_id or not dataset_id.strip():
320
+ return "Enter a dataset ID (e.g. username/dataset-name)", training_state, int(hf_offset or 0), _build_progress_summary()
321
 
322
+ offset_val = int(hf_offset or 0)
323
+ max_files_val = int(max_files)
324
 
325
+ local_dir, dl_status = download_hf_dataset(
326
+ dataset_id.strip(),
327
+ max_files=max_files_val,
328
+ offset=offset_val,
329
+ )
330
 
331
+ if not local_dir:
332
+ return f"Download failed: {dl_status}", training_state, offset_val, _build_progress_summary()
 
333
 
334
  builder = get_dataset_builder()
 
 
 
 
335
 
336
+ # Restore labels/flags from dataset.json pulled from HF repo
337
+ dataset_json_path = str(Path(local_dir) / "dataset.json")
338
+ if Path(dataset_json_path).exists():
339
+ builder.load_dataset(dataset_json_path)
340
+ dl_status += " | Restored labels from HF repo"
341
 
342
+ # Scan directory — skips already-tracked files via existing_paths check
343
+ samples, scan_status = builder.scan_directory(local_dir)
 
344
 
345
+ training_state = training_state or {}
346
+ training_state["audio_dir"] = local_dir
347
+ training_state["dataset_id"] = dataset_id.strip()
348
+ training_state["dataset_path"] = dataset_json_path
349
 
350
+ next_offset = offset_val + max_files_val
 
 
 
 
351
 
352
+ return f"{dl_status} | {scan_status}", training_state, next_offset, _build_progress_summary()
353
 
354
+ except Exception as e:
355
+ logger.error(f"HF download failed: {e}")
356
+ return f"Error: {e}", training_state or {}, int(hf_offset or 0), _build_progress_summary()
357
 
 
 
358
 
359
+ def lora_save_dataset_to_json(training_state):
360
+ """Explicitly save the current dataset to JSON."""
361
+ try:
362
  builder = get_dataset_builder()
363
+
364
+ if builder.get_sample_count() == 0:
365
+ return "No samples to save"
366
 
367
  training_state = training_state or {}
368
+ dataset_path = training_state.get("dataset_path")
369
+ if not dataset_path:
370
+ audio_dir = training_state.get("audio_dir", "lora_training")
371
+ dataset_path = str(Path(audio_dir) / "dataset.json")
372
+ training_state["dataset_path"] = dataset_path
373
 
374
+ return builder.save_dataset(dataset_path)
375
 
376
  except Exception as e:
377
+ logger.error(f"Save dataset failed: {e}")
378
+ return f"Error: {e}"
379
 
380
 
381
  @spaces.GPU(duration=300)
382
+ def lora_auto_label(label_batch_size, training_state, progress=gr.Progress()):
383
+ """Auto-label unlabeled samples in batches using LLM analysis, then auto-save."""
384
  try:
385
  builder = get_dataset_builder()
386
 
387
  if builder.get_sample_count() == 0:
388
+ return [], "No samples loaded. Upload files or download a dataset first.", training_state, _build_progress_summary()
389
 
390
  engine = get_ace_engine()
391
  if not engine.is_initialized():
392
+ return [], "ACE-Step engine not initialized. Models may still be loading.", training_state, _build_progress_summary()
393
 
394
  def progress_callback(msg):
395
  progress(0, desc=msg)
 
397
  samples, status = builder.label_all_samples(
398
  dit_handler=engine.dit_handler,
399
  llm_handler=engine.llm_handler,
400
+ only_unlabeled=True,
401
+ max_count=int(label_batch_size),
402
  progress_callback=progress_callback,
403
  )
404
 
405
+ training_state = training_state or {}
406
+ dataset_path = training_state.get("dataset_path")
407
+ if not dataset_path:
408
+ audio_dir = training_state.get("audio_dir", "lora_training")
409
+ dataset_path = str(Path(audio_dir) / "dataset.json")
410
+ training_state["dataset_path"] = dataset_path
411
+
412
+ save_status = builder.save_dataset(dataset_path)
413
+ status += f"\n{save_status}"
414
+
415
+ # Sync to HF repo so labels persist across sessions
416
+ dataset_id = training_state.get("dataset_id")
417
+ if dataset_id:
418
+ hf_status = upload_dataset_json_to_hf(dataset_id, dataset_path)
419
+ status += f"\n{hf_status}"
420
+
421
+ return _build_review_dataframe(), status, training_state, _build_progress_summary()
422
 
423
  except Exception as e:
424
  logger.error(f"Auto-label failed: {e}")
425
+ return [], f"Error: {e}", training_state or {}, _build_progress_summary()
426
 
427
 
428
  def lora_save_edits(df_data, training_state):
 
430
  try:
431
  builder = get_dataset_builder()
432
 
433
+ if df_data is None:
434
+ return "No data to save"
435
+
436
+ if isinstance(df_data, pd.DataFrame):
437
+ if df_data.empty:
438
+ return "No data to save"
439
+ rows = df_data.values.tolist()
440
+ elif isinstance(df_data, list):
441
+ if len(df_data) == 0:
442
+ return "No data to save"
443
+ rows = df_data
444
+ else:
445
  return "No data to save"
446
 
447
  updated = 0
448
+ for row in rows:
449
  idx = int(row[0])
450
  updates = {}
451
 
 
477
 
478
 
479
  @spaces.GPU(duration=300)
480
+ def lora_preprocess(preprocess_batch_size, training_state, progress=gr.Progress()):
481
+ """Preprocess labeled samples to training tensors in batches."""
482
  try:
483
  builder = get_dataset_builder()
484
 
485
  if builder.get_labeled_count() == 0:
486
+ return "No labeled samples. Run auto-label first.", _build_progress_summary()
487
 
488
  engine = get_ace_engine()
489
  if not engine.is_initialized():
490
+ return "ACE-Step engine not initialized.", _build_progress_summary()
491
 
492
  tensor_dir = str(Path("lora_training") / "tensors")
493
 
 
497
  output_paths, status = builder.preprocess_to_tensors(
498
  dit_handler=engine.dit_handler,
499
  output_dir=tensor_dir,
500
+ max_count=int(preprocess_batch_size),
501
  progress_callback=progress_callback,
502
  )
503
 
504
  training_state = training_state or {}
505
  training_state["tensor_dir"] = tensor_dir
506
 
507
+ # Auto-save so preprocessed flags persist across sessions
508
+ dataset_path = training_state.get("dataset_path")
509
+ if not dataset_path:
510
+ audio_dir = training_state.get("audio_dir", "lora_training")
511
+ dataset_path = str(Path(audio_dir) / "dataset.json")
512
+ training_state["dataset_path"] = dataset_path
513
+
514
+ save_status = builder.save_dataset(dataset_path)
515
+ status += f"\n{save_status}"
516
+
517
+ # Sync to HF repo so preprocessed flags persist across sessions
518
+ dataset_id = training_state.get("dataset_id")
519
+ if dataset_id:
520
+ hf_status = upload_dataset_json_to_hf(dataset_id, dataset_path)
521
+ status += f"\n{hf_status}"
522
+
523
+ return status, _build_progress_summary()
524
 
525
  except Exception as e:
526
  logger.error(f"Preprocess failed: {e}")
527
+ return f"Error: {e}", _build_progress_summary()
528
 
529
 
530
  @spaces.GPU(duration=600)
 
813
 
814
  training_state = gr.State(value={})
815
 
816
+ lora_progress = gr.Textbox(
817
+ label="Progress",
818
+ value="Total: 0 | Labeled: 0 | Preprocessed: 0 | Remaining: 0",
819
+ interactive=False,
820
+ )
821
+
822
  with gr.Tabs():
823
 
824
  # ---------- Sub-tab 1: Data Source ----------
825
  with gr.Tab("1. Data Source"):
826
+ gr.Markdown(
827
+ "Download audio from a HuggingFace dataset repo. "
828
+ "Labels and progress are synced back to the repo automatically."
829
+ )
830
 
831
+ lora_hf_id = gr.Textbox(
832
+ label="Dataset ID",
833
+ placeholder="username/dataset-name",
834
+ )
835
  with gr.Row():
836
+ lora_hf_max = gr.Slider(
837
+ minimum=1, maximum=500, value=50, step=1,
838
+ label="Batch size",
839
+ )
840
+ lora_hf_offset = gr.Number(
841
+ label="Offset (auto-increments)",
842
+ value=0,
843
+ precision=0,
844
+ )
845
+ lora_hf_btn = gr.Button(
846
+ "Download Batch & Scan", variant="primary"
847
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
848
 
849
  lora_source_status = gr.Textbox(
850
  label="Status", lines=2, interactive=False
 
856
  "Auto-label samples using the LLM, then review and edit metadata."
857
  )
858
 
859
+ lora_label_batch_size = gr.Slider(
860
+ minimum=1, maximum=500, value=50, step=1,
861
+ label="Label batch size (samples per run)",
862
+ )
863
  lora_label_btn = gr.Button(
864
+ "Label Batch (+ auto-save)",
865
+ variant="primary",
866
  )
867
  lora_label_status = gr.Textbox(
868
+ label="Label Status", lines=3, interactive=False
869
  )
870
 
871
  lora_review_df = gr.Dataframe(
 
875
  wrap=True,
876
  )
877
 
878
+ with gr.Row():
879
+ lora_save_btn = gr.Button("Save Edits")
880
+ lora_save_dataset_btn = gr.Button(
881
+ "Save Dataset to JSON", variant="secondary"
882
+ )
883
  lora_save_status = gr.Textbox(
884
  label="Save Status", interactive=False
885
  )
 
890
  "Encode audio through VAE and text encoders to create training tensors."
891
  )
892
 
893
+ lora_preprocess_batch_size = gr.Slider(
894
+ minimum=1, maximum=500, value=50, step=1,
895
+ label="Preprocess batch size (samples per run)",
896
+ )
897
  lora_preprocess_btn = gr.Button(
898
+ "Preprocess Batch (+ auto-save)", variant="primary"
899
  )
900
  lora_preprocess_status = gr.Textbox(
901
  label="Preprocess Status", lines=3, interactive=False
 
978
  # ---------- Event handlers ----------
979
 
980
  # Data Source
 
 
 
 
 
 
981
  lora_hf_btn.click(
982
  fn=lora_download_hf,
983
+ inputs=[lora_hf_id, lora_hf_max, lora_hf_offset, training_state],
984
+ outputs=[lora_source_status, training_state, lora_hf_offset, lora_progress],
985
  )
986
 
987
  # Label & Review
988
  lora_label_btn.click(
989
  fn=lora_auto_label,
990
+ inputs=[lora_label_batch_size, training_state],
991
+ outputs=[lora_review_df, lora_label_status, training_state, lora_progress],
992
  )
993
 
994
  lora_save_btn.click(
 
997
  outputs=[lora_save_status],
998
  )
999
 
1000
+ lora_save_dataset_btn.click(
1001
+ fn=lora_save_dataset_to_json,
1002
+ inputs=[training_state],
1003
+ outputs=[lora_save_status],
1004
+ )
1005
+
1006
  # Preprocess
1007
  lora_preprocess_btn.click(
1008
  fn=lora_preprocess,
1009
+ inputs=[lora_preprocess_batch_size, training_state],
1010
+ outputs=[lora_preprocess_status, lora_progress],
1011
  )
1012
 
1013
  # Train
src/lora_trainer.py CHANGED
@@ -6,8 +6,10 @@ The actual training pipeline lives in acestep/training/.
6
  """
7
 
8
  import logging
 
 
9
  from pathlib import Path
10
- from typing import Optional, Tuple
11
 
12
  logger = logging.getLogger(__name__)
13
 
@@ -17,18 +19,15 @@ AUDIO_SUFFIXES = {".wav", ".mp3", ".flac", ".ogg", ".opus"}
17
  def download_hf_dataset(
18
  dataset_id: str,
19
  max_files: int = 50,
20
- hf_token: Optional[str] = None,
21
  ) -> Tuple[str, str]:
22
  """
23
  Download a subset of audio files from a HuggingFace dataset repo.
24
 
25
- Lists repo contents first, picks the first N audio files,
26
- then downloads them individually to the HF cache.
27
 
28
- Args:
29
- dataset_id: HuggingFace dataset repo ID (e.g. "pedroapfilho/lofi-tracks")
30
- max_files: Maximum number of audio files to download
31
- hf_token: Optional HuggingFace token for private repos
32
 
33
  Returns:
34
  Tuple of (output_dir, status_message)
@@ -37,7 +36,7 @@ def download_hf_dataset(
37
  from huggingface_hub import HfApi, hf_hub_download
38
 
39
  api = HfApi()
40
- token = hf_token or None
41
 
42
  logger.info(f"Listing files in '{dataset_id}'...")
43
 
@@ -51,7 +50,7 @@ def download_hf_dataset(
51
  ]
52
 
53
  total_available = len(all_files)
54
- selected = all_files[:max_files]
55
 
56
  if not selected:
57
  return "", f"No audio files found in {dataset_id}"
@@ -76,9 +75,23 @@ def download_hf_dataset(
76
  if not dest.exists():
77
  dest.symlink_to(cached_path)
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  status = (
80
  f"Downloaded {len(selected)} of {total_available} "
81
- f"audio files from {dataset_id}"
82
  )
83
  logger.info(status)
84
  return str(output_dir), status
@@ -91,3 +104,28 @@ def download_hf_dataset(
91
  msg = f"Failed to download dataset: {e}"
92
  logger.error(msg)
93
  return "", msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  """
7
 
8
  import logging
9
+ import os
10
+ import shutil
11
  from pathlib import Path
12
+ from typing import Tuple
13
 
14
  logger = logging.getLogger(__name__)
15
 
 
19
  def download_hf_dataset(
20
  dataset_id: str,
21
  max_files: int = 50,
22
+ offset: int = 0,
23
  ) -> Tuple[str, str]:
24
  """
25
  Download a subset of audio files from a HuggingFace dataset repo.
26
 
27
+ Also pulls dataset.json from the repo if it exists (restoring labels
28
+ and preprocessed flags from a previous session).
29
 
30
+ Uses HF_TOKEN env var for authentication.
 
 
 
31
 
32
  Returns:
33
  Tuple of (output_dir, status_message)
 
36
  from huggingface_hub import HfApi, hf_hub_download
37
 
38
  api = HfApi()
39
+ token = os.environ.get("HF_TOKEN")
40
 
41
  logger.info(f"Listing files in '{dataset_id}'...")
42
 
 
50
  ]
51
 
52
  total_available = len(all_files)
53
+ selected = all_files[offset:offset + max_files]
54
 
55
  if not selected:
56
  return "", f"No audio files found in {dataset_id}"
 
75
  if not dest.exists():
76
  dest.symlink_to(cached_path)
77
 
78
+ # Pull dataset.json from repo if it exists (restores previous session state)
79
+ try:
80
+ cached_json = hf_hub_download(
81
+ repo_id=dataset_id,
82
+ filename="dataset.json",
83
+ repo_type="dataset",
84
+ token=token,
85
+ )
86
+ dest_json = output_dir / "dataset.json"
87
+ shutil.copy2(cached_json, str(dest_json))
88
+ logger.info("Pulled dataset.json from HF repo")
89
+ except Exception:
90
+ logger.info("No dataset.json in HF repo (first session)")
91
+
92
  status = (
93
  f"Downloaded {len(selected)} of {total_available} "
94
+ f"audio files from {dataset_id} (offset {offset})"
95
  )
96
  logger.info(status)
97
  return str(output_dir), status
 
104
  msg = f"Failed to download dataset: {e}"
105
  logger.error(msg)
106
  return "", msg
107
+
108
+
109
+ def upload_dataset_json_to_hf(dataset_id: str, json_path: str) -> str:
110
+ """Push dataset.json to the HF dataset repo for persistence across sessions."""
111
+ try:
112
+ from huggingface_hub import HfApi
113
+
114
+ token = os.environ.get("HF_TOKEN")
115
+ if not token:
116
+ return "HF_TOKEN not set — skipped HF sync"
117
+
118
+ api = HfApi()
119
+ api.upload_file(
120
+ path_or_fileobj=json_path,
121
+ path_in_repo="dataset.json",
122
+ repo_id=dataset_id,
123
+ repo_type="dataset",
124
+ token=token,
125
+ )
126
+ return f"Synced dataset.json to {dataset_id}"
127
+
128
+ except Exception as e:
129
+ msg = f"HF sync failed: {e}"
130
+ logger.error(msg)
131
+ return msg