[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KF9RZB0G39PXCAVSVD5A48":3,"skill-same:01M6KF9RZB0G39PXCAVSVD5A48":70},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":26,"publishedAt":37,"linkOnly":38,"markdownContent":39,"markdownBody":40,"frontMatter":41,"refName":42,"commitSha":43,"skillDirectory":44,"forksCount":14,"repositoryHtmlUrl":45,"repositoryHomepageUrl":6,"ownerHtmlUrl":46,"ownerBlogUrl":47,"ownerDescription":48,"updatedAt":49,"install":50,"resources":63},"01M6KF9RZB0G39PXCAVSVD5A48","aligned-stem-workflow",null,"Incremental audio production with duration alignment handling, per-stem verification, and adaptive extension strategies","xyliu-cs\u002FOpenSpace-GDPval","xyliu-cs","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F89236536?v=4","01M6KF8Z1V4TXS86CKSH48BY8T","xy","01M6KF8Z67443W0SHXM85JEF0B",0,"MIT","https:\u002F\u002Fgithub.com\u002Fxyliu-cs\u002FOpenSpace-GDPval\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced-enhanced\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[27,28,29,30,31,32,33,34,35,36],"workflow","aligned stem workflow","verification","Production","Audio","alignment","strategies","extension","with","adaptive","2026-11-10 10:12:30",false,"---\nname: aligned-stem-workflow\ndescription: Incremental audio production with duration alignment handling, per-stem verification, and adaptive extension strategies\n---\n\n# Aligned Stem Audio Production Workflow\n\nThis skill provides a resilient pattern for audio production that emphasizes **incremental verification**, **fail-fast** principles, and **automatic duration alignment**. Each major step produces verified outputs before proceeding, with explicit handling for stem duration mismatches using appropriate extension strategies.\n\n## Overview\n\nFollow these steps in strict order. Each step must complete successfully and pass verification before proceeding to the next:\n\n1. **Early timing calculation** - Derive section transitions from BPM and duration first\n2. **Verify reference audio** - Validate input file properties and extract target duration\n3. **Generate and verify each stem individually** - One stem at a time with immediate verification\n4. **Detect and resolve duration mismatches** - Apply appropriate extension strategy (zero-pad, loop, or crossfade)\n5. **Generate drum stem separately** - Dedicated drum extension with rhythm patterns\n6. **Apply effects with verification** - Process each stem and verify output\n7. **Export master track** - Mix all verified stems\n8. **Archive and final verification** - Package deliverables with comprehensive checks\n\n## Key Differences from Standard Workflow\n\n- **Incremental verification**: Verify each stem immediately after generation, not just at the end\n- **Fail-fast approach**: Stop and report errors at each step rather than accumulating failures\n- **Early timing**: Calculate section transitions before any audio generation\n- **Duration alignment**: Explicit detection and resolution of stem duration mismatches\n- **Adaptive extension**: Choose appropriate strategy (zero-pad\u002Floop\u002Fcrossfade) based on stem type\n- **Separated drums**: Drum stem generation is a distinct step with rhythm-specific processing\n- **Memory-efficient**: Process stems individually to avoid large array operations that cause sandbox failures\n\n## Step 1: Calculate Timing Parameters (Early)\n\nCalculate all timing parameters **before** generating any audio. This ensures consistent timing across all stems:\n\n```python\ndef calculate_section_transitions(bpm, total_duration_sec, sections):\n    \"\"\"Calculate beat-aligned transition points for song sections.\"\"\"\n    beats_per_second = bpm \u002F 60.0\n    \n    section_durations = {}\n    cumulative_time = 0\n    \n    for section_name, beat_count in sections.items():\n        duration = beat_count \u002F beats_per_second\n        section_durations[section_name] = {\n            'start': cumulative_time,\n            'end': cumulative_time + duration,\n            'beats': beat_count,\n            'start_beat': cumulative_time * beats_per_second\n        }\n        cumulative_time += duration\n    \n    return section_durations\n\n# Configuration\nBPM = 120\nDURATION = 137\nSECTIONS = {'intro': 16, 'verse': 32, 'chorus': 32, 'bridge': 16, 'outro': 16}\n\ntiming = calculate_section_transitions(BPM, DURATION, SECTIONS)\nprint(\"Timing calculated:\")\nfor section, data in timing.items():\n    print(f\"  {section}: {data['start']:.2f}s - {data['end']:.2f}s ({data['beats']} beats)\")\n```\n\n## Step 2: Verify Reference Audio\n\nValidate the reference file exists and has expected properties:\n\n```python\nimport soundfile as sf\nimport os\n\ndef verify_reference_file(filepath, expected_sample_rate=None, min_duration=None):\n    \"\"\"Verify reference audio file and return info dict.\"\"\"\n    if not os.path.exists(filepath):\n        raise FileNotFoundError(f\"Reference file not found: {filepath}\")\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if expected_sample_rate and info.samplerate != expected_sample_rate:\n        errors.append(f\"Sample rate mismatch: expected {expected_sample_rate}, got {info.samplerate}\")\n    \n    if min_duration and info.duration \u003C min_duration:\n        errors.append(f\"Duration too short: expected >= {min_duration}s, got {info.duration}s\")\n    \n    if errors:\n        raise ValueError(f\"Reference file validation failed: {'; '.join(errors)}\")\n    \n    print(f\"Reference verified: {info.duration:.2f}s @ {info.samplerate}Hz, {info.channels}ch, {info.subtype}\")\n    return {\n        'sample_rate': info.samplerate,\n        'duration': info.duration,\n        'channels': info.channels,\n        'subtype': info.subtype\n    }\n\n# Verify reference\nref_info = verify_reference_file('reference.wav', expected_sample_rate=48000, min_duration=130)\nTARGET_DURATION = ref_info['duration']  # Use actual reference duration as target\n```\n\n## Step 3: Generate and Verify Each Stem Individually\n\nGenerate one stem at a time, verify it immediately before proceeding to the next:\n\n```python\nimport numpy as np\n\ndef generate_stem(name, duration_sec, sample_rate, subtype='FLOAT', section_timing=None):\n    \"\"\"Generate a single stem with explicit sample type.\"\"\"\n    frames = int(duration_sec * sample_rate)\n    t = np.linspace(0, duration_sec, frames)\n    \n    # Generate stem-specific content (customize per stem type)\n    if name == 'bass':\n        freq = 110  # A2\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.8\n    elif name == 'guitars':\n        freq = 440  # A4\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.6\n    elif name == 'synths':\n        freq = 880  # A5\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.5\n    elif name == 'bridge':\n        freq = 220  # A3\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.7\n    else:\n        audio_data = np.sin(2 * np.pi * 440 * t) * 0.5\n    \n    # Ensure proper data type\n    if subtype == 'FLOAT':\n        audio_data = audio_data.astype(np.float32)\n    elif subtype == 'PCM_24':\n        audio_data = np.clip(audio_data, -1, 1) * (2**23 - 1)\n        audio_data = audio_data.astype(np.int32)\n    \n    filepath = f'{name}_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return filepath, audio_data\n\ndef verify_stem(filepath, expected_sample_rate, expected_subtype, expected_duration, tolerance_sec=1.0):\n    \"\"\"Verify a single stem meets specifications.\"\"\"\n    if not os.path.exists(filepath):\n        return {'success': False, 'error': f'File not found: {filepath}'}\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if info.samplerate != expected_sample_rate:\n        errors.append(f'sample_rate: expected {expected_sample_rate}, got {info.samplerate}')\n    \n    if info.subtype != expected_subtype:\n        errors.append(f'subtype: expected {expected_subtype}, got {info.subtype}')\n    \n    if abs(info.duration - expected_duration) > tolerance_sec:\n        errors.append(f'duration: expected ~{expected_duration}s, got {info.duration}s')\n    \n    # Calculate duration discrepancy\n    duration_diff = info.duration - expected_duration\n    \n    if errors:\n        return {'success': False, 'error': '; '.join(errors), 'duration_diff': duration_diff}\n    \n    return {'success': True, 'info': info, 'duration_diff': duration_diff}\n\n# Generate stems one at a time with verification\nSAMPLE_RATE = 48000\nSUBTYPE = 'FLOAT'\nSTEM_NAMES = ['bass', 'guitars', 'synths', 'bridge']\n\ngenerated_stems = []\nstem_info = {}  # Track duration discrepancies\n\nfor stem_name in STEM_NAMES:\n    print(f\"\\n=== Generating {stem_name} stem ===\")\n    \n    # Generate\n    filepath, data = generate_stem(stem_name, DURATION, SAMPLE_RATE, subtype=SUBTYPE)\n    \n    # Verify immediately\n    result = verify_stem(filepath, SAMPLE_RATE, SUBTYPE, TARGET_DURATION)\n    \n    if result['success']:\n        print(f\"✓ {stem_name} stem verified: {result['info'].duration:.2f}s @ {result['info'].samplerate}Hz\")\n        if abs(result['duration_diff']) > 0.1:\n            print(f\"  ⚠ Duration discrepancy: {result['duration_diff']:+.2f}s\")\n        generated_stems.append(filepath)\n        stem_info[stem_name] = result\n    else:\n        print(f\"✗ {stem_name} stem FAILED: {result['error']}\")\n        raise RuntimeError(f\"Stem generation failed for {stem_name}: {result['error']}\")\n\nprint(f\"\\nAll {len(generated_stems)} stems generated and verified successfully\")\n```\n\n## Step 4: Detect and Resolve Duration Mismatches\n\nWhen stems have different durations, apply the appropriate extension strategy:\n\n### Strategy Selection Guidelines\n\n| Strategy | Best For | Duration Gap | Sound Characteristic |\n|----------|----------|--------------|---------------------|\n| **Zero-padding** | Short gaps (\u003C0.5s), silence sections, endings | Small | Clean, abrupt |\n| **Looping** | Repetitive patterns (drums, bass, rhythmic elements) | Medium to large | Seamless, rhythmic |\n| **Crossfade extension** | Melodic content, sustained instruments, vocals | Any | Natural, smooth |\n\n```python\ndef align_stem_duration(input_filepath, output_filepath, target_duration, strategy='auto', \n                        sample_rate=None, subtype='FLOAT', loop_seamless=True):\n    \"\"\"\n    Align stem duration to target using appropriate strategy.\n    \n    Args:\n        input_filepath: Path to source stem\n        output_filepath: Path for aligned output\n        target_duration: Target duration in seconds\n        strategy: 'zero_pad', 'loop', 'crossfade', or 'auto'\n        sample_rate: Sample rate (auto-detected if None)\n        subtype: Audio subtype\n        loop_seamless: Apply crossfade at loop boundaries if True\n    \n    Returns:\n        dict with success status and alignment details\n    \"\"\"\n    if not os.path.exists(input_filepath):\n        return {'success': False, 'error': f'Input file not found: {input_filepath}'}\n    \n    # Load source\n    data, sr = sf.read(input_filepath)\n    if sample_rate is None:\n        sample_rate = sr\n    \n    source_duration = len(data) \u002F sample_rate\n    duration_diff = target_duration - source_duration\n    \n    # If already aligned (within tolerance), just copy\n    if abs(duration_diff) \u003C 0.01:\n        sf.write(output_filepath, data, sample_rate, subtype=subtype, format='WAV')\n        return {'success': True, 'strategy': 'none', 'duration_diff': 0}\n    \n    if duration_diff > 0:\n        # Need to EXTEND\n        extend_frames = int(duration_diff * sample_rate)\n        \n        if strategy == 'auto':\n            # Auto-select based on duration gap and stem type\n            if duration_diff \u003C 0.5:\n                strategy = 'zero_pad'\n            elif 'drum' in input_filepath or 'bass' in input_filepath:\n                strategy = 'loop'\n            else:\n                strategy = 'crossfade'\n        \n        if strategy == 'zero_pad':\n            # Append zeros\n            padding = np.zeros(extend_frames, dtype=data.dtype)\n            aligned_data = np.concatenate([data, padding])\n            \n        elif strategy == 'loop':\n            # Loop the content\n            loop_frames = len(data)\n            loops_needed = int(np.ceil(extend_frames \u002F loop_frames))\n            \n            if loop_seamless and loops_needed > 1:\n                # Apply crossfade at loop boundaries for seamless looping\n                crossfade_frames = min(int(0.05 * sample_rate), loop_frames \u002F\u002F 4)\n                loop_extension = np.zeros(extend_frames, dtype=data.dtype)\n                \n                for i in range(loops_needed):\n                    start = i * loop_frames\n                    end = min(start + loop_frames, extend_frames)\n                    actual_len = end - start\n                    \n                    # Extract loop segment\n                    loop_segment = data[:actual_len].copy()\n                    \n                    # Apply crossfade at boundaries\n                    if i > 0 and actual_len >= crossfade_frames * 2:\n                        # Fade in from previous loop\n                        fade_in = np.linspace(0, 1, crossfade_frames)\n                        loop_segment[:crossfade_frames] *= fade_in\n                    \n                    if i \u003C loops_needed - 1 and actual_len >= crossfade_frames * 2:\n                        # Fade out for next loop\n                        fade_out = np.linspace(1, 0, crossfade_frames)\n                        loop_segment[-crossfade_frames:] *= fade_out\n                    \n                    loop_extension[start:end] = loop_segment\n                \n                extend_frames_actual = len(loop_extension)\n            else:\n                # Simple tiling\n                loop_extension = np.tile(data, loops_needed)[:extend_frames]\n                extend_frames_actual = extend_frames\n            \n            aligned_data = np.concatenate([data, loop_extension[:extend_frames_actual]])\n            \n        elif strategy == 'crossfade':\n            # Extend using crossfade from the end of the source\n            # Take last portion and crossfade it onto itself\n            fade_duration = min(duration_diff * 0.3, 2.0)  # 30% of gap, max 2s\n            fade_frames = int(fade_duration * sample_rate)\n            \n            if fade_frames >= len(data) \u002F\u002F 2:\n                # Source too short for crossfade, fall back to loop\n                fade_frames = len(data) \u002F\u002F 4\n            \n            # Extract tail segment for extension\n            tail_segment = data[-fade_frames:].copy()\n            \n            # Create extended portion with crossfade\n            extended_portion = np.zeros(extend_frames, dtype=data.dtype)\n            \n            if extend_frames \u003C= fade_frames:\n                # Short extension: just crossfade tail onto itself\n                fade_in = np.linspace(0, 1, extend_frames)\n                extended_portion = tail_segment[:extend_frames] * fade_in\n            else:\n                # Longer extension: loop tail with crossfades\n                loops = int(np.ceil(extend_frames \u002F fade_frames))\n                for i in range(loops):\n                    start = i * fade_frames\n                    end = min(start + fade_frames, extend_frames)\n                    seg_len = end - start\n                    \n                    segment = tail_segment[:seg_len].copy()\n                    \n                    # Crossfade boundaries\n                    if seg_len >= 100:\n                        cf_len = min(50, seg_len \u002F\u002F 4)\n                        if i > 0:\n                            fade_in = np.linspace(0, 1, cf_len)\n                            segment[:cf_len] *= fade_in\n                    \n                    extended_portion[start:end] = segment\n            \n            aligned_data = np.concatenate([data, extended_portion])\n        \n        else:\n            return {'success': False, 'error': f'Unknown extension strategy: {strategy}'}\n        \n    else:\n        # Need to TRUNCATE\n        truncate_frames = int(abs(duration_diff) * sample_rate)\n        aligned_data = data[:len(data) - truncate_frames]\n        strategy = 'truncate'\n    \n    # Ensure proper data type and clip\n    if subtype == 'FLOAT':\n        aligned_data = aligned_data.astype(np.float32)\n    elif subtype == 'PCM_24':\n        aligned_data = np.clip(aligned_data, -1, 1) * (2**23 - 1)\n        aligned_data = aligned_data.astype(np.int32)\n    else:\n        aligned_data = np.clip(aligned_data, -1, 1)\n    \n    # Export aligned stem\n    sf.write(output_filepath, aligned_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return {\n        'success': True, \n        'strategy': strategy,\n        'source_duration': source_duration,\n        'target_duration': target_duration,\n        'duration_diff': duration_diff,\n        'aligned_frames': len(aligned_data)\n    }\n\n# Apply duration alignment to all stems\nprint(\"\\n=== Aligning stem durations ===\")\naligned_stems = []\n\nTARGET_DURATION = ref_info['duration']  # Use reference as target\n\nfor stem_name in STEM_NAMES:\n    input_file = f'{stem_name}_stem.wav'\n    output_file = f'{stem_name}_aligned.wav'\n    \n    # Determine strategy based on stem type\n    if stem_name in ['bass', 'drums']:\n        strategy = 'loop'  # Rhythmic elements loop well\n    elif stem_name in ['bridge', 'outro']:\n        strategy = 'crossfade'  # Sustained content benefits from crossfade\n    else:\n        strategy = 'auto'  # Let the function decide\n    \n    print(f\"Aligning {stem_name} (strategy: {strategy})...\")\n    result = align_stem_duration(input_file, output_file, TARGET_DURATION, \n                                  strategy=strategy, sample_rate=SAMPLE_RATE, subtype=SUBTYPE)\n    \n    if result['success']:\n        if result['strategy'] != 'none':\n            print(f\"✓ {stem_name} aligned: {result['source_duration']:.2f}s -> {result['target_duration']:.2f}s via {result['strategy']}\")\n        else:\n            print(f\"✓ {stem_name} already aligned at {result['target_duration']:.2f}s\")\n        aligned_stems.append(output_file)\n    else:\n        print(f\"✗ {stem_name} alignment FAILED: {result['error']}\")\n        raise RuntimeError(f\"Duration alignment failed for {stem_name}: {result['error']}\")\n\nprint(f\"\\nAll {len(aligned_stems)} stems duration-aligned successfully\")\n```\n\n## Step 5: Generate Drum Stem Separately\n\nDrums require different processing (rhythm patterns, percussion sounds):\n\n```python\ndef generate_drum_stem(duration_sec, sample_rate, bpm, section_timing, subtype='FLOAT'):\n    \"\"\"Generate drum stem with rhythm patterns aligned to sections.\"\"\"\n    frames = int(duration_sec * sample_rate)\n    audio_data = np.zeros(frames, dtype=np.float32)\n    beats_per_second = bpm \u002F 60.0\n    \n    # Simple kick drum pattern (every beat)\n    kick_freq = 60\n    kick_duration = 0.1\n    kick_frames = int(kick_duration * sample_rate)\n    \n    for beat_time in np.arange(0, duration_sec, 1.0 \u002F beats_per_second):\n        start_frame = int(beat_time * sample_rate)\n        end_frame = min(start_frame + kick_frames, frames)\n        \n        if start_frame \u003C frames:\n            t = np.linspace(0, kick_duration, end_frame - start_frame)\n            kick = np.exp(-5 * t) * np.sin(2 * np.pi * kick_freq * t)\n            audio_data[start_frame:end_frame] += kick * 0.9\n    \n    # Simple snare pattern (every 2nd and 4th beat)\n    snare_freq = 200\n    snare_duration = 0.05\n    snare_frames = int(snare_duration * sample_rate)\n    \n    for beat_time in np.arange(0, duration_sec, 2.0 \u002F beats_per_second):\n        start_frame = int((beat_time + 0.5 \u002F beats_per_second) * sample_rate)\n        end_frame = min(start_frame + snare_frames, frames)\n        \n        if start_frame \u003C frames:\n            t = np.linspace(0, snare_duration, end_frame - start_frame)\n            snare = np.exp(-10 * t) * np.random.uniform(-1, 1, len(t)) * 0.5\n            audio_data[start_frame:end_frame] += snare * 0.7\n    \n    audio_data = np.clip(audio_data, -1, 1)\n    \n    filepath = 'drums_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return filepath, audio_data\n\nprint(\"\\n=== Generating drum stem ===\")\ndrums_filepath, drums_data = generate_drum_stem(TARGET_DURATION, SAMPLE_RATE, BPM, timing, subtype=SUBTYPE)\n\ndrums_result = verify_stem(drums_filepath, SAMPLE_RATE, SUBTYPE, TARGET_DURATION)\nif drums_result['success']:\n    print(f\"✓ Drum stem verified: {drums_result['info'].duration:.2f}s @ {drums_result['info'].samplerate}Hz\")\n    # Align drums if needed (usually uses loop strategy)\n    drums_aligned = 'drums_aligned.wav'\n    drums_align_result = align_stem_duration(drums_filepath, drums_aligned, TARGET_DURATION,\n                                              strategy='loop', sample_rate=SAMPLE_RATE, subtype=SUBTYPE)\n    if drums_align_result['success']:\n        aligned_stems.append(drums_aligned)\n        print(f\"✓ Drums aligned via {drums_align_result['strategy']}\")\n    else:\n        print(f\"✗ Drum alignment FAILED: {drums_align_result['error']}\")\n        raise RuntimeError(f\"Drum alignment failed: {drums_align_result['error']}\")\nelse:\n    print(f\"✗ Drum stem FAILED: {drums_result['error']}\")\n    raise RuntimeError(f\"Drum stem generation failed: {drums_result['error']}\")\n```\n\n## Step 6: Apply Effects with Verification\n\nProcess each aligned stem and verify the output:\n\n```python\nfrom scipy import signal\n\ndef apply_lowpass_filter(audio_data, sample_rate, cutoff_freq=8000):\n    \"\"\"Apply lowpass filter using scipy.signal.\"\"\"\n    nyquist = sample_rate \u002F 2\n    normalized_cutoff = cutoff_freq \u002F nyquist\n    b, a = signal.butter(4, normalized_cutoff, btype='low')\n    return signal.filtfilt(b, a, audio_data)\n\ndef apply_effects_and_verify(input_filepath, output_filepath, sample_rate, subtype):\n    \"\"\"Apply effects to stem and verify output.\"\"\"\n    data, sr = sf.read(input_filepath)\n    \n    # Apply effects\n    processed = apply_lowpass_filter(data, sr, cutoff_freq=8000)\n    processed = np.clip(processed, -1, 1)\n    \n    # Export\n    sf.write(output_filepath, processed, sample_rate, subtype=subtype, format='WAV')\n    \n    # Verify\n    result = verify_stem(output_filepath, sample_rate, subtype, TARGET_DURATION, tolerance_sec=2.0)\n    return result, processed\n\nprint(\"\\n=== Applying effects to all aligned stems ===\")\nprocessed_stems = []\n\nfor aligned_file in aligned_stems:\n    stem_name = os.path.basename(aligned_file).replace('_aligned.wav', '')\n    output_file = f'{stem_name}_processed.wav'\n    \n    print(f\"Processing {stem_name}...\")\n    result, _ = apply_effects_and_verify(aligned_file, output_file, SAMPLE_RATE, SUBTYPE)\n    \n    if result['success']:\n        print(f\"✓ {stem_name} processed and verified\")\n        processed_stems.append(output_file)\n    else:\n        print(f\"✗ {stem_name} processing FAILED: {result['error']}\")\n        raise RuntimeError(f\"Effects processing failed for {stem_name}\")\n\nprint(f\"\\nAll {len(processed_stems)} stems processed successfully\")\n```\n\n## Step 7: Export Master Track\n\nMix all verified stems into master track:\n\n```python\ndef create_master_track(stem_files, output_filepath, sample_rate, subtype):\n    \"\"\"Create master track from verified stems.\"\"\"\n    # Load first stem to get dimensions\n    first_data, sr = sf.read(stem_files[0])\n    master_audio = np.zeros(len(first_data), dtype=np.float32)\n    \n    # Mix all stems with gain staging\n    gain_per_stem = 0.4  # Prevent clipping with 5 stems\n    \n    for i, stem_file in enumerate(stem_files):\n        print(f\"  Mixing stem {i+1}\u002F{len(stem_files)}: {stem_file}\")\n        data, sr = sf.read(stem_file)\n        \n        # Ensure same length as master\n        if len(data) > len(master_audio):\n            data = data[:len(master_audio)]\n        elif len(data) \u003C len(master_audio):\n            # Pad with zeros if shorter (shouldn't happen after alignment)\n            padding = np.zeros(len(master_audio) - len(data), dtype=np.float32)\n            data = np.concatenate([data, padding])\n        \n        master_audio += data * gain_per_stem\n    \n    # Apply master bus processing\n    master_audio = np.clip(master_audio, -1, 1)\n    \n    # Export master\n    sf.write(output_filepath, master_audio, sample_rate, subtype=subtype, format='WAV')\n    \n    return output_filepath, master_audio\n\nprint(\"\\n=== Creating master track ===\")\nmaster_filepath, master_data = create_master_track(processed_stems, 'master.wav', SAMPLE_RATE, SUBTYPE)\n\n# Verify master\nmaster_info = sf.info(master_filepath)\nprint(f\"Master exported: {master_filepath}\")\nprint(f\"  Duration: {master_info.duration:.2f}s\")\nprint(f\"  Sample rate: {master_info.samplerate}Hz\")\nprint(f\"  Channels: {master_info.channels}\")\nprint(f\"  Subtype: {master_info.subtype}\")\n```\n\n## Step 8: Archive and Final Verification\n\nPackage deliverables with comprehensive checks:\n\n```python\ndef create_archive(stem_files, master_file, output_archive='audio交付.zip'):\n    \"\"\"Create archive of all deliverables.\"\"\"\n    import zipfile\n    \n    all_files = stem_files + [master_file]\n    \n    with zipfile.ZipFile(output_archive, 'w', zipfile.ZIP_DEFLATED) as zipf:\n        for filepath in all_files:\n            if os.path.exists(filepath):\n                zipf.write(filepath)\n                print(f\"  Added: {filepath}\")\n    \n    return output_archive\n\ndef final_verification(master_filepath, expected_duration=None, expected_sample_rate=None):\n    \"\"\"Comprehensive final verification.\"\"\"\n    issues = []\n    \n    # Verify master file\n    if not os.path.exists(master_filepath):\n        return {'success': False, 'error': 'Master file not found'}\n    \n    info = sf.info(master_filepath)\n    \n    if expected_duration and abs(info.duration - expected_duration) > 2.0:\n        issues.append(f\"Duration mismatch: expected ~{expected_duration}s, got {info.duration}s\")\n    \n    if expected_sample_rate and info.samplerate != expected_sample_rate:\n        issues.append(f\"Sample rate mismatch: expected {expected_sample_rate}, got {info.samplerate}\")\n    \n    # Check for clipping\n    data, _ = sf.read(master_filepath)\n    clip_ratio = np.sum(np.abs(data) >= 0.99) \u002F len(data)\n    if clip_ratio > 0.001:  # More than 0.1% clipped\n        issues.append(f\"Excessive clipping detected: {clip_ratio*100:.2f}% of samples at max level\")\n    \n    # Check for silence\n    rms = np.sqrt(np.mean(data**2))\n    if rms \u003C 0.01:\n        issues.append(f\"Audio too quiet: RMS level {rms:.4f}\")\n    \n    success = len(issues) == 0\n    \n    return {\n        'success': success,\n        'issues': issues,\n        'info': {\n            'duration': info.duration,\n            'sample_rate': info.samplerate,\n            'channels': info.channels,\n            'subtype': info.subtype,\n            'clipping_ratio': clip_ratio,\n            'rms_level': rms\n        }\n    }\n\nprint(\"\\n=== Final verification ===\")\nfinal_result = final_verification(master_filepath, expected_duration=TARGET_DURATION, \n                                   expected_sample_rate=SAMPLE_RATE)\n\nif final_result['success']:\n    print(\"✓ All verification checks passed\")\n    print(f\"  Master: {final_result['info']['duration']:.2f}s @ {final_result['info']['sample_rate']}Hz\")\n    print(f\"  RMS level: {final_result['info']['rms_level']:.4f}\")\n    print(f\"  Clipping: {final_result['info']['clipping_ratio']*100:.2f}%\")\n    \n    # Create archive\n    print(\"\\n=== Creating archive ===\")\n    archive_path = create_archive(processed_stems, master_filepath, 'audio_deliverables.zip')\n    print(f\"✓ Archive created: {archive_path}\")\nelse:\n    print(\"✗ Verification failed:\")\n    for issue in final_result['issues']:\n        print(f\"  - {issue}\")\n```\n\n## Troubleshooting\n\n### Duration Mismatch Issues\n\n**Problem**: Stems have significantly different durations causing alignment artifacts\n\n**Solutions**:\n1. **Check source generation**: Ensure all stems use the same duration parameter\n2. **Adjust strategy**: Switch from `auto` to explicit strategy based on content type\n3. **Tune crossfade parameters**: Increase `fade_duration` for smoother transitions\n4. **Enable seamless looping**: Set `loop_seamless=True` for rhythmic content\n\n### Extension Quality Issues\n\n**Problem**: Loop points audible or crossfade sounds unnatural\n\n**Solutions**:\n1. **For looping**: Find better loop points (at zero-crossings or beat boundaries)\n2. **For crossfade**: Increase overlap duration or use different source segments\n3. **For padding**: Only use for very short gaps (\u003C0.3s) at song endings\n\n### Memory Issues\n\n**Problem**: Large files cause sandbox failures\n\n**Solutions**:\n1. **Process in chunks**: Use streaming I\u002FO for very long files\n2. **Reduce sample rate**: Temporarily work at 44.1kHz, upsample for final export\n3. **Process stems sequentially**: Clear memory between stem operations\n","# Aligned Stem Audio Production Workflow\n\nThis skill provides a resilient pattern for audio production that emphasizes **incremental verification**, **fail-fast** principles, and **automatic duration alignment**. Each major step produces verified outputs before proceeding, with explicit handling for stem duration mismatches using appropriate extension strategies.\n\n## Overview\n\nFollow these steps in strict order. Each step must complete successfully and pass verification before proceeding to the next:\n\n1. **Early timing calculation** - Derive section transitions from BPM and duration first\n2. **Verify reference audio** - Validate input file properties and extract target duration\n3. **Generate and verify each stem individually** - One stem at a time with immediate verification\n4. **Detect and resolve duration mismatches** - Apply appropriate extension strategy (zero-pad, loop, or crossfade)\n5. **Generate drum stem separately** - Dedicated drum extension with rhythm patterns\n6. **Apply effects with verification** - Process each stem and verify output\n7. **Export master track** - Mix all verified stems\n8. **Archive and final verification** - Package deliverables with comprehensive checks\n\n## Key Differences from Standard Workflow\n\n- **Incremental verification**: Verify each stem immediately after generation, not just at the end\n- **Fail-fast approach**: Stop and report errors at each step rather than accumulating failures\n- **Early timing**: Calculate section transitions before any audio generation\n- **Duration alignment**: Explicit detection and resolution of stem duration mismatches\n- **Adaptive extension**: Choose appropriate strategy (zero-pad\u002Floop\u002Fcrossfade) based on stem type\n- **Separated drums**: Drum stem generation is a distinct step with rhythm-specific processing\n- **Memory-efficient**: Process stems individually to avoid large array operations that cause sandbox failures\n\n## Step 1: Calculate Timing Parameters (Early)\n\nCalculate all timing parameters **before** generating any audio. This ensures consistent timing across all stems:\n\n```python\ndef calculate_section_transitions(bpm, total_duration_sec, sections):\n    \"\"\"Calculate beat-aligned transition points for song sections.\"\"\"\n    beats_per_second = bpm \u002F 60.0\n    \n    section_durations = {}\n    cumulative_time = 0\n    \n    for section_name, beat_count in sections.items():\n        duration = beat_count \u002F beats_per_second\n        section_durations[section_name] = {\n            'start': cumulative_time,\n            'end': cumulative_time + duration,\n            'beats': beat_count,\n            'start_beat': cumulative_time * beats_per_second\n        }\n        cumulative_time += duration\n    \n    return section_durations\n\n# Configuration\nBPM = 120\nDURATION = 137\nSECTIONS = {'intro': 16, 'verse': 32, 'chorus': 32, 'bridge': 16, 'outro': 16}\n\ntiming = calculate_section_transitions(BPM, DURATION, SECTIONS)\nprint(\"Timing calculated:\")\nfor section, data in timing.items():\n    print(f\"  {section}: {data['start']:.2f}s - {data['end']:.2f}s ({data['beats']} beats)\")\n```\n\n## Step 2: Verify Reference Audio\n\nValidate the reference file exists and has expected properties:\n\n```python\nimport soundfile as sf\nimport os\n\ndef verify_reference_file(filepath, expected_sample_rate=None, min_duration=None):\n    \"\"\"Verify reference audio file and return info dict.\"\"\"\n    if not os.path.exists(filepath):\n        raise FileNotFoundError(f\"Reference file not found: {filepath}\")\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if expected_sample_rate and info.samplerate != expected_sample_rate:\n        errors.append(f\"Sample rate mismatch: expected {expected_sample_rate}, got {info.samplerate}\")\n    \n    if min_duration and info.duration \u003C min_duration:\n        errors.append(f\"Duration too short: expected >= {min_duration}s, got {info.duration}s\")\n    \n    if errors:\n        raise ValueError(f\"Reference file validation failed: {'; '.join(errors)}\")\n    \n    print(f\"Reference verified: {info.duration:.2f}s @ {info.samplerate}Hz, {info.channels}ch, {info.subtype}\")\n    return {\n        'sample_rate': info.samplerate,\n        'duration': info.duration,\n        'channels': info.channels,\n        'subtype': info.subtype\n    }\n\n# Verify reference\nref_info = verify_reference_file('reference.wav', expected_sample_rate=48000, min_duration=130)\nTARGET_DURATION = ref_info['duration']  # Use actual reference duration as target\n```\n\n## Step 3: Generate and Verify Each Stem Individually\n\nGenerate one stem at a time, verify it immediately before proceeding to the next:\n\n```python\nimport numpy as np\n\ndef generate_stem(name, duration_sec, sample_rate, subtype='FLOAT', section_timing=None):\n    \"\"\"Generate a single stem with explicit sample type.\"\"\"\n    frames = int(duration_sec * sample_rate)\n    t = np.linspace(0, duration_sec, frames)\n    \n    # Generate stem-specific content (customize per stem type)\n    if name == 'bass':\n        freq = 110  # A2\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.8\n    elif name == 'guitars':\n        freq = 440  # A4\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.6\n    elif name == 'synths':\n        freq = 880  # A5\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.5\n    elif name == 'bridge':\n        freq = 220  # A3\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.7\n    else:\n        audio_data = np.sin(2 * np.pi * 440 * t) * 0.5\n    \n    # Ensure proper data type\n    if subtype == 'FLOAT':\n        audio_data = audio_data.astype(np.float32)\n    elif subtype == 'PCM_24':\n        audio_data = np.clip(audio_data, -1, 1) * (2**23 - 1)\n        audio_data = audio_data.astype(np.int32)\n    \n    filepath = f'{name}_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return filepath, audio_data\n\ndef verify_stem(filepath, expected_sample_rate, expected_subtype, expected_duration, tolerance_sec=1.0):\n    \"\"\"Verify a single stem meets specifications.\"\"\"\n    if not os.path.exists(filepath):\n        return {'success': False, 'error': f'File not found: {filepath}'}\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if info.samplerate != expected_sample_rate:\n        errors.append(f'sample_rate: expected {expected_sample_rate}, got {info.samplerate}')\n    \n    if info.subtype != expected_subtype:\n        errors.append(f'subtype: expected {expected_subtype}, got {info.subtype}')\n    \n    if abs(info.duration - expected_duration) > tolerance_sec:\n        errors.append(f'duration: expected ~{expected_duration}s, got {info.duration}s')\n    \n    # Calculate duration discrepancy\n    duration_diff = info.duration - expected_duration\n    \n    if errors:\n        return {'success': False, 'error': '; '.join(errors), 'duration_diff': duration_diff}\n    \n    return {'success': True, 'info': info, 'duration_diff': duration_diff}\n\n# Generate stems one at a time with verification\nSAMPLE_RATE = 48000\nSUBTYPE = 'FLOAT'\nSTEM_NAMES = ['bass', 'guitars', 'synths', 'bridge']\n\ngenerated_stems = []\nstem_info = {}  # Track duration discrepancies\n\nfor stem_name in STEM_NAMES:\n    print(f\"\\n=== Generating {stem_name} stem ===\")\n    \n    # Generate\n    filepath, data = generate_stem(stem_name, DURATION, SAMPLE_RATE, subtype=SUBTYPE)\n    \n    # Verify immediately\n    result = verify_stem(filepath, SAMPLE_RATE, SUBTYPE, TARGET_DURATION)\n    \n    if result['success']:\n        print(f\"✓ {stem_name} stem verified: {result['info'].duration:.2f}s @ {result['info'].samplerate}Hz\")\n        if abs(result['duration_diff']) > 0.1:\n            print(f\"  ⚠ Duration discrepancy: {result['duration_diff']:+.2f}s\")\n        generated_stems.append(filepath)\n        stem_info[stem_name] = result\n    else:\n        print(f\"✗ {stem_name} stem FAILED: {result['error']}\")\n        raise RuntimeError(f\"Stem generation failed for {stem_name}: {result['error']}\")\n\nprint(f\"\\nAll {len(generated_stems)} stems generated and verified successfully\")\n```\n\n## Step 4: Detect and Resolve Duration Mismatches\n\nWhen stems have different durations, apply the appropriate extension strategy:\n\n### Strategy Selection Guidelines\n\n| Strategy | Best For | Duration Gap | Sound Characteristic |\n|----------|----------|--------------|---------------------|\n| **Zero-padding** | Short gaps (\u003C0.5s), silence sections, endings | Small | Clean, abrupt |\n| **Looping** | Repetitive patterns (drums, bass, rhythmic elements) | Medium to large | Seamless, rhythmic |\n| **Crossfade extension** | Melodic content, sustained instruments, vocals | Any | Natural, smooth |\n\n```python\ndef align_stem_duration(input_filepath, output_filepath, target_duration, strategy='auto', \n                        sample_rate=None, subtype='FLOAT', loop_seamless=True):\n    \"\"\"\n    Align stem duration to target using appropriate strategy.\n    \n    Args:\n        input_filepath: Path to source stem\n        output_filepath: Path for aligned output\n        target_duration: Target duration in seconds\n        strategy: 'zero_pad', 'loop', 'crossfade', or 'auto'\n        sample_rate: Sample rate (auto-detected if None)\n        subtype: Audio subtype\n        loop_seamless: Apply crossfade at loop boundaries if True\n    \n    Returns:\n        dict with success status and alignment details\n    \"\"\"\n    if not os.path.exists(input_filepath):\n        return {'success': False, 'error': f'Input file not found: {input_filepath}'}\n    \n    # Load source\n    data, sr = sf.read(input_filepath)\n    if sample_rate is None:\n        sample_rate = sr\n    \n    source_duration = len(data) \u002F sample_rate\n    duration_diff = target_duration - source_duration\n    \n    # If already aligned (within tolerance), just copy\n    if abs(duration_diff) \u003C 0.01:\n        sf.write(output_filepath, data, sample_rate, subtype=subtype, format='WAV')\n        return {'success': True, 'strategy': 'none', 'duration_diff': 0}\n    \n    if duration_diff > 0:\n        # Need to EXTEND\n        extend_frames = int(duration_diff * sample_rate)\n        \n        if strategy == 'auto':\n            # Auto-select based on duration gap and stem type\n            if duration_diff \u003C 0.5:\n                strategy = 'zero_pad'\n            elif 'drum' in input_filepath or 'bass' in input_filepath:\n                strategy = 'loop'\n            else:\n                strategy = 'crossfade'\n        \n        if strategy == 'zero_pad':\n            # Append zeros\n            padding = np.zeros(extend_frames, dtype=data.dtype)\n            aligned_data = np.concatenate([data, padding])\n            \n        elif strategy == 'loop':\n            # Loop the content\n            loop_frames = len(data)\n            loops_needed = int(np.ceil(extend_frames \u002F loop_frames))\n            \n            if loop_seamless and loops_needed > 1:\n                # Apply crossfade at loop boundaries for seamless looping\n                crossfade_frames = min(int(0.05 * sample_rate), loop_frames \u002F\u002F 4)\n                loop_extension = np.zeros(extend_frames, dtype=data.dtype)\n                \n                for i in range(loops_needed):\n                    start = i * loop_frames\n                    end = min(start + loop_frames, extend_frames)\n                    actual_len = end - start\n                    \n                    # Extract loop segment\n                    loop_segment = data[:actual_len].copy()\n                    \n                    # Apply crossfade at boundaries\n                    if i > 0 and actual_len >= crossfade_frames * 2:\n                        # Fade in from previous loop\n                        fade_in = np.linspace(0, 1, crossfade_frames)\n                        loop_segment[:crossfade_frames] *= fade_in\n                    \n                    if i \u003C loops_needed - 1 and actual_len >= crossfade_frames * 2:\n                        # Fade out for next loop\n                        fade_out = np.linspace(1, 0, crossfade_frames)\n                        loop_segment[-crossfade_frames:] *= fade_out\n                    \n                    loop_extension[start:end] = loop_segment\n                \n                extend_frames_actual = len(loop_extension)\n            else:\n                # Simple tiling\n                loop_extension = np.tile(data, loops_needed)[:extend_frames]\n                extend_frames_actual = extend_frames\n            \n            aligned_data = np.concatenate([data, loop_extension[:extend_frames_actual]])\n            \n        elif strategy == 'crossfade':\n            # Extend using crossfade from the end of the source\n            # Take last portion and crossfade it onto itself\n            fade_duration = min(duration_diff * 0.3, 2.0)  # 30% of gap, max 2s\n            fade_frames = int(fade_duration * sample_rate)\n            \n            if fade_frames >= len(data) \u002F\u002F 2:\n                # Source too short for crossfade, fall back to loop\n                fade_frames = len(data) \u002F\u002F 4\n            \n            # Extract tail segment for extension\n            tail_segment = data[-fade_frames:].copy()\n            \n            # Create extended portion with crossfade\n            extended_portion = np.zeros(extend_frames, dtype=data.dtype)\n            \n            if extend_frames \u003C= fade_frames:\n                # Short extension: just crossfade tail onto itself\n                fade_in = np.linspace(0, 1, extend_frames)\n                extended_portion = tail_segment[:extend_frames] * fade_in\n            else:\n                # Longer extension: loop tail with crossfades\n                loops = int(np.ceil(extend_frames \u002F fade_frames))\n                for i in range(loops):\n                    start = i * fade_frames\n                    end = min(start + fade_frames, extend_frames)\n                    seg_len = end - start\n                    \n                    segment = tail_segment[:seg_len].copy()\n                    \n                    # Crossfade boundaries\n                    if seg_len >= 100:\n                        cf_len = min(50, seg_len \u002F\u002F 4)\n                        if i > 0:\n                            fade_in = np.linspace(0, 1, cf_len)\n                            segment[:cf_len] *= fade_in\n                    \n                    extended_portion[start:end] = segment\n            \n            aligned_data = np.concatenate([data, extended_portion])\n        \n        else:\n            return {'success': False, 'error': f'Unknown extension strategy: {strategy}'}\n        \n    else:\n        # Need to TRUNCATE\n        truncate_frames = int(abs(duration_diff) * sample_rate)\n        aligned_data = data[:len(data) - truncate_frames]\n        strategy = 'truncate'\n    \n    # Ensure proper data type and clip\n    if subtype == 'FLOAT':\n        aligned_data = aligned_data.astype(np.float32)\n    elif subtype == 'PCM_24':\n        aligned_data = np.clip(aligned_data, -1, 1) * (2**23 - 1)\n        aligned_data = aligned_data.astype(np.int32)\n    else:\n        aligned_data = np.clip(aligned_data, -1, 1)\n    \n    # Export aligned stem\n    sf.write(output_filepath, aligned_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return {\n        'success': True, \n        'strategy': strategy,\n        'source_duration': source_duration,\n        'target_duration': target_duration,\n        'duration_diff': duration_diff,\n        'aligned_frames': len(aligned_data)\n    }\n\n# Apply duration alignment to all stems\nprint(\"\\n=== Aligning stem durations ===\")\naligned_stems = []\n\nTARGET_DURATION = ref_info['duration']  # Use reference as target\n\nfor stem_name in STEM_NAMES:\n    input_file = f'{stem_name}_stem.wav'\n    output_file = f'{stem_name}_aligned.wav'\n    \n    # Determine strategy based on stem type\n    if stem_name in ['bass', 'drums']:\n        strategy = 'loop'  # Rhythmic elements loop well\n    elif stem_name in ['bridge', 'outro']:\n        strategy = 'crossfade'  # Sustained content benefits from crossfade\n    else:\n        strategy = 'auto'  # Let the function decide\n    \n    print(f\"Aligning {stem_name} (strategy: {strategy})...\")\n    result = align_stem_duration(input_file, output_file, TARGET_DURATION, \n                                  strategy=strategy, sample_rate=SAMPLE_RATE, subtype=SUBTYPE)\n    \n    if result['success']:\n        if result['strategy'] != 'none':\n            print(f\"✓ {stem_name} aligned: {result['source_duration']:.2f}s -> {result['target_duration']:.2f}s via {result['strategy']}\")\n        else:\n            print(f\"✓ {stem_name} already aligned at {result['target_duration']:.2f}s\")\n        aligned_stems.append(output_file)\n    else:\n        print(f\"✗ {stem_name} alignment FAILED: {result['error']}\")\n        raise RuntimeError(f\"Duration alignment failed for {stem_name}: {result['error']}\")\n\nprint(f\"\\nAll {len(aligned_stems)} stems duration-aligned successfully\")\n```\n\n## Step 5: Generate Drum Stem Separately\n\nDrums require different processing (rhythm patterns, percussion sounds):\n\n```python\ndef generate_drum_stem(duration_sec, sample_rate, bpm, section_timing, subtype='FLOAT'):\n    \"\"\"Generate drum stem with rhythm patterns aligned to sections.\"\"\"\n    frames = int(duration_sec * sample_rate)\n    audio_data = np.zeros(frames, dtype=np.float32)\n    beats_per_second = bpm \u002F 60.0\n    \n    # Simple kick drum pattern (every beat)\n    kick_freq = 60\n    kick_duration = 0.1\n    kick_frames = int(kick_duration * sample_rate)\n    \n    for beat_time in np.arange(0, duration_sec, 1.0 \u002F beats_per_second):\n        start_frame = int(beat_time * sample_rate)\n        end_frame = min(start_frame + kick_frames, frames)\n        \n        if start_frame \u003C frames:\n            t = np.linspace(0, kick_duration, end_frame - start_frame)\n            kick = np.exp(-5 * t) * np.sin(2 * np.pi * kick_freq * t)\n            audio_data[start_frame:end_frame] += kick * 0.9\n    \n    # Simple snare pattern (every 2nd and 4th beat)\n    snare_freq = 200\n    snare_duration = 0.05\n    snare_frames = int(snare_duration * sample_rate)\n    \n    for beat_time in np.arange(0, duration_sec, 2.0 \u002F beats_per_second):\n        start_frame = int((beat_time + 0.5 \u002F beats_per_second) * sample_rate)\n        end_frame = min(start_frame + snare_frames, frames)\n        \n        if start_frame \u003C frames:\n            t = np.linspace(0, snare_duration, end_frame - start_frame)\n            snare = np.exp(-10 * t) * np.random.uniform(-1, 1, len(t)) * 0.5\n            audio_data[start_frame:end_frame] += snare * 0.7\n    \n    audio_data = np.clip(audio_data, -1, 1)\n    \n    filepath = 'drums_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return filepath, audio_data\n\nprint(\"\\n=== Generating drum stem ===\")\ndrums_filepath, drums_data = generate_drum_stem(TARGET_DURATION, SAMPLE_RATE, BPM, timing, subtype=SUBTYPE)\n\ndrums_result = verify_stem(drums_filepath, SAMPLE_RATE, SUBTYPE, TARGET_DURATION)\nif drums_result['success']:\n    print(f\"✓ Drum stem verified: {drums_result['info'].duration:.2f}s @ {drums_result['info'].samplerate}Hz\")\n    # Align drums if needed (usually uses loop strategy)\n    drums_aligned = 'drums_aligned.wav'\n    drums_align_result = align_stem_duration(drums_filepath, drums_aligned, TARGET_DURATION,\n                                              strategy='loop', sample_rate=SAMPLE_RATE, subtype=SUBTYPE)\n    if drums_align_result['success']:\n        aligned_stems.append(drums_aligned)\n        print(f\"✓ Drums aligned via {drums_align_result['strategy']}\")\n    else:\n        print(f\"✗ Drum alignment FAILED: {drums_align_result['error']}\")\n        raise RuntimeError(f\"Drum alignment failed: {drums_align_result['error']}\")\nelse:\n    print(f\"✗ Drum stem FAILED: {drums_result['error']}\")\n    raise RuntimeError(f\"Drum stem generation failed: {drums_result['error']}\")\n```\n\n## Step 6: Apply Effects with Verification\n\nProcess each aligned stem and verify the output:\n\n```python\nfrom scipy import signal\n\ndef apply_lowpass_filter(audio_data, sample_rate, cutoff_freq=8000):\n    \"\"\"Apply lowpass filter using scipy.signal.\"\"\"\n    nyquist = sample_rate \u002F 2\n    normalized_cutoff = cutoff_freq \u002F nyquist\n    b, a = signal.butter(4, normalized_cutoff, btype='low')\n    return signal.filtfilt(b, a, audio_data)\n\ndef apply_effects_and_verify(input_filepath, output_filepath, sample_rate, subtype):\n    \"\"\"Apply effects to stem and verify output.\"\"\"\n    data, sr = sf.read(input_filepath)\n    \n    # Apply effects\n    processed = apply_lowpass_filter(data, sr, cutoff_freq=8000)\n    processed = np.clip(processed, -1, 1)\n    \n    # Export\n    sf.write(output_filepath, processed, sample_rate, subtype=subtype, format='WAV')\n    \n    # Verify\n    result = verify_stem(output_filepath, sample_rate, subtype, TARGET_DURATION, tolerance_sec=2.0)\n    return result, processed\n\nprint(\"\\n=== Applying effects to all aligned stems ===\")\nprocessed_stems = []\n\nfor aligned_file in aligned_stems:\n    stem_name = os.path.basename(aligned_file).replace('_aligned.wav', '')\n    output_file = f'{stem_name}_processed.wav'\n    \n    print(f\"Processing {stem_name}...\")\n    result, _ = apply_effects_and_verify(aligned_file, output_file, SAMPLE_RATE, SUBTYPE)\n    \n    if result['success']:\n        print(f\"✓ {stem_name} processed and verified\")\n        processed_stems.append(output_file)\n    else:\n        print(f\"✗ {stem_name} processing FAILED: {result['error']}\")\n        raise RuntimeError(f\"Effects processing failed for {stem_name}\")\n\nprint(f\"\\nAll {len(processed_stems)} stems processed successfully\")\n```\n\n## Step 7: Export Master Track\n\nMix all verified stems into master track:\n\n```python\ndef create_master_track(stem_files, output_filepath, sample_rate, subtype):\n    \"\"\"Create master track from verified stems.\"\"\"\n    # Load first stem to get dimensions\n    first_data, sr = sf.read(stem_files[0])\n    master_audio = np.zeros(len(first_data), dtype=np.float32)\n    \n    # Mix all stems with gain staging\n    gain_per_stem = 0.4  # Prevent clipping with 5 stems\n    \n    for i, stem_file in enumerate(stem_files):\n        print(f\"  Mixing stem {i+1}\u002F{len(stem_files)}: {stem_file}\")\n        data, sr = sf.read(stem_file)\n        \n        # Ensure same length as master\n        if len(data) > len(master_audio):\n            data = data[:len(master_audio)]\n        elif len(data) \u003C len(master_audio):\n            # Pad with zeros if shorter (shouldn't happen after alignment)\n            padding = np.zeros(len(master_audio) - len(data), dtype=np.float32)\n            data = np.concatenate([data, padding])\n        \n        master_audio += data * gain_per_stem\n    \n    # Apply master bus processing\n    master_audio = np.clip(master_audio, -1, 1)\n    \n    # Export master\n    sf.write(output_filepath, master_audio, sample_rate, subtype=subtype, format='WAV')\n    \n    return output_filepath, master_audio\n\nprint(\"\\n=== Creating master track ===\")\nmaster_filepath, master_data = create_master_track(processed_stems, 'master.wav', SAMPLE_RATE, SUBTYPE)\n\n# Verify master\nmaster_info = sf.info(master_filepath)\nprint(f\"Master exported: {master_filepath}\")\nprint(f\"  Duration: {master_info.duration:.2f}s\")\nprint(f\"  Sample rate: {master_info.samplerate}Hz\")\nprint(f\"  Channels: {master_info.channels}\")\nprint(f\"  Subtype: {master_info.subtype}\")\n```\n\n## Step 8: Archive and Final Verification\n\nPackage deliverables with comprehensive checks:\n\n```python\ndef create_archive(stem_files, master_file, output_archive='audio交付.zip'):\n    \"\"\"Create archive of all deliverables.\"\"\"\n    import zipfile\n    \n    all_files = stem_files + [master_file]\n    \n    with zipfile.ZipFile(output_archive, 'w', zipfile.ZIP_DEFLATED) as zipf:\n        for filepath in all_files:\n            if os.path.exists(filepath):\n                zipf.write(filepath)\n                print(f\"  Added: {filepath}\")\n    \n    return output_archive\n\ndef final_verification(master_filepath, expected_duration=None, expected_sample_rate=None):\n    \"\"\"Comprehensive final verification.\"\"\"\n    issues = []\n    \n    # Verify master file\n    if not os.path.exists(master_filepath):\n        return {'success': False, 'error': 'Master file not found'}\n    \n    info = sf.info(master_filepath)\n    \n    if expected_duration and abs(info.duration - expected_duration) > 2.0:\n        issues.append(f\"Duration mismatch: expected ~{expected_duration}s, got {info.duration}s\")\n    \n    if expected_sample_rate and info.samplerate != expected_sample_rate:\n        issues.append(f\"Sample rate mismatch: expected {expected_sample_rate}, got {info.samplerate}\")\n    \n    # Check for clipping\n    data, _ = sf.read(master_filepath)\n    clip_ratio = np.sum(np.abs(data) >= 0.99) \u002F len(data)\n    if clip_ratio > 0.001:  # More than 0.1% clipped\n        issues.append(f\"Excessive clipping detected: {clip_ratio*100:.2f}% of samples at max level\")\n    \n    # Check for silence\n    rms = np.sqrt(np.mean(data**2))\n    if rms \u003C 0.01:\n        issues.append(f\"Audio too quiet: RMS level {rms:.4f}\")\n    \n    success = len(issues) == 0\n    \n    return {\n        'success': success,\n        'issues': issues,\n        'info': {\n            'duration': info.duration,\n            'sample_rate': info.samplerate,\n            'channels': info.channels,\n            'subtype': info.subtype,\n            'clipping_ratio': clip_ratio,\n            'rms_level': rms\n        }\n    }\n\nprint(\"\\n=== Final verification ===\")\nfinal_result = final_verification(master_filepath, expected_duration=TARGET_DURATION, \n                                   expected_sample_rate=SAMPLE_RATE)\n\nif final_result['success']:\n    print(\"✓ All verification checks passed\")\n    print(f\"  Master: {final_result['info']['duration']:.2f}s @ {final_result['info']['sample_rate']}Hz\")\n    print(f\"  RMS level: {final_result['info']['rms_level']:.4f}\")\n    print(f\"  Clipping: {final_result['info']['clipping_ratio']*100:.2f}%\")\n    \n    # Create archive\n    print(\"\\n=== Creating archive ===\")\n    archive_path = create_archive(processed_stems, master_filepath, 'audio_deliverables.zip')\n    print(f\"✓ Archive created: {archive_path}\")\nelse:\n    print(\"✗ Verification failed:\")\n    for issue in final_result['issues']:\n        print(f\"  - {issue}\")\n```\n\n## Troubleshooting\n\n### Duration Mismatch Issues\n\n**Problem**: Stems have significantly different durations causing alignment artifacts\n\n**Solutions**:\n1. **Check source generation**: Ensure all stems use the same duration parameter\n2. **Adjust strategy**: Switch from `auto` to explicit strategy based on content type\n3. **Tune crossfade parameters**: Increase `fade_duration` for smoother transitions\n4. **Enable seamless looping**: Set `loop_seamless=True` for rhythmic content\n\n### Extension Quality Issues\n\n**Problem**: Loop points audible or crossfade sounds unnatural\n\n**Solutions**:\n1. **For looping**: Find better loop points (at zero-crossings or beat boundaries)\n2. **For crossfade**: Increase overlap duration or use different source segments\n3. **For padding**: Only use for very short gaps (\u003C0.3s) at song endings\n\n### Memory Issues\n\n**Problem**: Large files cause sandbox failures\n\n**Solutions**:\n1. **Process in chunks**: Use streaming I\u002FO for very long files\n2. **Reduce sample rate**: Temporarily work at 44.1kHz, upsample for final export\n3. **Process stems sequentially**: Clear memory between stem operations\n",{"name":5,"description":7},"main","af1b40a42167d09c30b3a63000aa14ace4c1e229","gdpval_bench\u002Fskills\u002Faudio-track-production-enhanced-enhanced","https:\u002F\u002Fgithub.com\u002Fxyliu-cs\u002FOpenSpace-GDPval","https:\u002F\u002Fgithub.com\u002Fxyliu-cs","https:\u002F\u002Fxyliu-cs.github.io","PhD Student in CS, CUHK-Shenzhen.","2026-04-06 20:32:15",{"source":8,"skillName":5,"commands":51,"prompt":61,"zipAvailable":62},[52,55,58],{"tool":53,"command":54},"npx","npx skills add xyliu-cs\u002FOpenSpace-GDPval --skill aligned-stem-workflow",{"tool":56,"command":57},"bunx","bunx skills add xyliu-cs\u002FOpenSpace-GDPval --skill aligned-stem-workflow",{"tool":59,"command":60},"pnpm","pnpm dlx skills add xyliu-cs\u002FOpenSpace-GDPval --skill aligned-stem-workflow","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fxyliu-cs\u002FOpenSpace-GDPval\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced-enhanced\u002FSKILL.md",true,[64],{"path":65,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":68,"sourceHtmlUrl":69},".skill_id","OTHER","其他",54,"https:\u002F\u002Fgithub.com\u002Fxyliu-cs\u002FOpenSpace-GDPval\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced-enhanced\u002F.skill_id",[71,84,92,107,133,151],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":37},"01M6KG8MF1S664SWBDENYRSCK8","zip-export-deliverable","Ensures codebase deliverables are properly exported as ZIP archives through a dedicated finalization step","https:\u002F\u002Fgithub.com\u002Fxyliu-cs\u002FOpenSpace-GDPval\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Fzip-export-deliverable\u002FSKILL.md",[],[78,79,80,81,82,83],"zip export deliverable","zip","export","deliverables","codebase","as",{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":37},"01M6KG8GAZWHHEK7VNJDW0ME21","zip-deliverable-finalization","Ensure codebase deliverables are properly packaged as ZIP exports in a dedicated final step","https:\u002F\u002Fgithub.com\u002Fxyliu-cs\u002FOpenSpace-GDPval\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Fzip-deliverable-finalization\u002FSKILL.md",[],[91,79,81,82,83],"zip deliverable finalization",{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":37},"01M6KG8CMQQ1PYMNTSRZ9VS1MD","zero-iteration-failure-analysis","Identify and handle agent failures with 0 iterations as pre-execution system issues","https:\u002F\u002Fgithub.com\u002Fxyliu-cs\u002FOpenSpace-GDPval\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Fzero-iteration-failure-analysis\u002FSKILL.md",[],[99,100,101,102,103,35,104,105,83,106],"failure analysis","ZeRO","analysis","iteration","zero iteration failure analysis","issues","execution","system",{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":118,"publishedAt":37},"01M6KG86W3PA07FT9W58YHHERM","write-file-fallback-report","Generate professional documents using write_file when primary data sources fail, leveraging embedded domain knowledge instead of external retrieval","https:\u002F\u002Fgithub.com\u002Fxyliu-cs\u002FOpenSpace-GDPval\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Fwrite-file-fallback-report\u002FSKILL.md",[113],{"categoryNo":114,"categoryName":115,"taxonomyType":116,"taxonomyTypeDesc":117},"01JBSEEDCAT000000000000034","行政与办公人员","PROFESSION","适用职业",[119,120,121,122,123,124,125,126,127,128,129,130,131,132],"fallback","write","file","report","write file fallback report","domain","professional","sources","retrieval","generate","embedded","documents","data","knowledge",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":140,"publishedAt":37},"01M6KG82GAEY3GG77CMGCK1C2T","fallback-doc-with-delegation","Generate professional documents after tool failures using shell_agent for complex formats or write_file for simple text\u002Fmarkdown","https:\u002F\u002Fgithub.com\u002Fxyliu-cs\u002FOpenSpace-GDPval\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Fwrite-file-fallback-report-enhanced\u002FSKILL.md",[139],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[141,35,119,142,143,144,130,128,121,145,146,147,120,148,125,149,150],"fallback doc with delegation","doc","delegation","shell","markdown","tool","text","simple","formats","for",{"skillNo":152,"name":153,"nameZh":6,"description":154,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":155,"categories":156,"keywords":158,"publishedAt":37},"01M6KG7WT7GX5NYCGEFHW22NV7","context-anchored-fallback-report","Generate documents with write_file when retrieval tools fail, with explicit guardrails against task context drift","https:\u002F\u002Fgithub.com\u002Fxyliu-cs\u002FOpenSpace-GDPval\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Fwrite-file-fallback-report-enhanced-4bc5c2\u002FSKILL.md",[157],{"categoryNo":114,"categoryName":115,"taxonomyType":116,"taxonomyTypeDesc":117},[119,122,159,160,128,121,161,162,120,163,164,127,35,165,130],"context","context anchored fallback report","Guardrails","Tools","task","drift","context drift"]