[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KHWD37H4F2BST26MD9CJQ9":3,"skill-same:01M6KHWD37H4F2BST26MD9CJQ9":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":25,"publishedAt":37,"linkOnly":38,"markdownContent":39,"markdownBody":40,"frontMatter":41,"refName":42,"commitSha":43,"skillDirectory":44,"forksCount":13,"repositoryHtmlUrl":45,"repositoryHomepageUrl":6,"ownerHtmlUrl":46,"ownerBlogUrl":6,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M6KHWD37H4F2BST26MD9CJQ9","incremental-audio-workflow",null,"Step-by-step audio production with per-stem verification, timing alignment, and incremental quality gates","AG064\u002FOpenSpace","AG064","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184930299?v=4","01M6KHVFG7TB73NHX3RDYSTMH2","01M6KHVFMM7XA2PZA9Z83PHS3V",0,"MIT","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced\u002FSKILL.md",[17,22],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000023","Skill与智能体开发",[26,27,28,29,30,31,32,33,34,35,36],"workflow","Audio","incremental audio workflow","quality gates","verification","Production","quality","alignment","gates","timing","with","2026-11-10 10:12:30",false,"---\nname: incremental-audio-workflow\ndescription: Step-by-step audio production with per-stem verification, timing alignment, and incremental quality gates\n---\n\n# Incremental Audio Production Workflow\n\nThis skill provides a resilient pattern for audio production that emphasizes **incremental verification** and **fail-fast** principles. Each major step produces verified outputs before proceeding, reducing iteration count and catching errors early.\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\n3. **Generate and verify each stem individually** - One stem at a time with immediate verification\n4. **Generate drum stem separately** - Dedicated drum extension with rhythm patterns\n5. **Apply effects with verification** - Process each stem and verify output\n6. **Export master track** - Mix all verified stems\n7. **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- **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)\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):\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) > 1.0:  # Allow 1s tolerance\n        errors.append(f'duration: expected ~{expected_duration}s, got {info.duration}s')\n    \n    if errors:\n        return {'success': False, 'error': '; '.join(errors)}\n    \n    return {'success': True, 'info': info}\n\n# Generate stems one at a time with verification\nSAMPLE_RATE = 48000\nSUBTYPE = 'FLOAT'\nSTEM_NAMES = ['bass', 'guitars', 'synths', 'bridge']\n\ngenerated_stems = []\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, DURATION)\n    \n    if result['success']:\n        print(f\"✓ {stem_name} stem verified: {result['info'].duration:.2f}s @ {result['info'].samplerate}Hz\")\n        generated_stems.append(filepath)\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: 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(DURATION, SAMPLE_RATE, BPM, timing, subtype=SUBTYPE)\n\ndrums_result = verify_stem(drums_filepath, SAMPLE_RATE, SUBTYPE, DURATION)\nif drums_result['success']:\n    print(f\"✓ Drum stem verified: {drums_result['info'].duration:.2f}s @ {drums_result['info'].samplerate}Hz\")\n    generated_stems.append(drums_filepath)\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 5: Apply Effects with Verification\n\nProcess each 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, DURATION)\n    return result, processed\n\nprint(\"\\n=== Applying effects to all stems ===\")\nprocessed_stems = []\n\nfor stem_name in STEM_NAMES:\n    input_file = f'{stem_name}_stem.wav'\n    output_file = f'{stem_name}_processed.wav'\n    \n    print(f\"Processing {stem_name}...\")\n    result, _ = apply_effects_and_verify(input_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\n# Process drums separately\ndrums_output = 'drums_processed.wav'\ndrums_result, _ = apply_effects_and_verify('drums_stem.wav', drums_output, SAMPLE_RATE, SUBTYPE)\nif drums_result['success']:\n    print(f\"✓ Drums processed and verified\")\n    processed_stems.append(drums_output)\nelse:\n    raise RuntimeError(f\"Drums processing failed: {drums_result['error']}\")\n```\n\n## Step 6: 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 stem_file in stem_files:\n        data, _ = sf.read(stem_file)\n        if len(data) == len(master_audio):\n            master_audio += data * gain_per_stem\n        else:\n            print(f\"WARNING: {stem_file} has different length, skipping\")\n    \n    # Final limiting\n    master_audio = np.clip(master_audio, -1, 1)\n    \n    # Export\n    sf.write(output_filepath, master_audio, sample_rate, subtype=subtype, format='WAV')\n    \n    # Verify\n    info = sf.info(output_filepath)\n    return {'success': True, 'info': info}\n\nprint(\"\\n=== Creating master track ===\")\nmaster_result = create_master_track(processed_stems, 'master_track.wav', SAMPLE_RATE, SUBTYPE)\n\nif master_result['success']:\n    print(f\"✓ Master track created: {master_result['info'].duration:.2f}s @ {master_result['info'].samplerate}Hz\")\nelse:\n    raise RuntimeError(\"Master track creation failed\")\n```\n\n## Step 7: Archive and Final Verification\n\nPackage all deliverables and perform comprehensive verification:\n\n```python\nimport zipfile\n\ndef create_archive(archive_name, file_list):\n    \"\"\"Create zip archive and verify contents.\"\"\"\n    with zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED) as zipf:\n        for filepath in file_list:\n            if os.path.exists(filepath):\n                zipf.write(filepath, os.path.basename(filepath))\n            else:\n                raise FileNotFoundError(f\"Cannot archive: {filepath} not found\")\n    \n    # Verify archive\n    with zipfile.ZipFile(archive_name, 'r') as zipf:\n        contents = zipf.namelist()\n    \n    return {'success': True, 'file_count': len(contents), 'files': contents}\n\ndef final_verification(specs):\n    \"\"\"Comprehensive final verification of all outputs.\"\"\"\n    results = {'passed': 0, 'failed': 0, 'details': []}\n    \n    for filepath, expected in specs.items():\n        if not os.path.exists(filepath):\n            results['failed'] += 1\n            results['details'].append(f\"MISSING: {filepath}\")\n            continue\n        \n        info = sf.info(filepath)\n        errors = []\n        \n        if expected.get('sample_rate') and info.samplerate != expected['sample_rate']:\n            errors.append(f\"sample_rate: {info.samplerate} != {expected['sample_rate']}\")\n        \n        if expected.get('subtype') and info.subtype != expected['subtype']:\n            errors.append(f\"subtype: {info.subtype} != {expected['subtype']}\")\n        \n        if expected.get('min_duration') and info.duration \u003C expected['min_duration']:\n            errors.append(f\"duration: {info.duration}s \u003C {expected['min_duration']}s\")\n        \n        if errors:\n            results['failed'] += 1\n            results['details'].append(f\"FAILED: {filepath} - {'; '.join(errors)}\")\n        else:\n            results['passed'] += 1\n            results['details'].append(f\"PASSED: {filepath} ({info.duration:.2f}s, {info.samplerate}Hz)\")\n    \n    return results\n\nprint(\"\\n=== Creating archive ===\")\ndeliverables = ['master_track.wav'] + STEM_NAMES + ['drums']\ndeliverable_files = [f'{name}.wav' if name != 'drums' else 'drums_processed.wav' for name in ['master_track'] + STEM_NAMES + ['drums_processed']]\ndeliverable_files = ['master_track.wav'] + [f'{s}_processed.wav' for s in STEM_NAMES] + ['drums_processed.wav']\n\narchive_result = create_archive('audio_deliverables.zip', deliverable_files)\nprint(f\"✓ Archive created with {archive_result['file_count']} files\")\n\nprint(\"\\n=== Final verification ===\")\nexpected_specs = {\n    'master_track.wav': {'sample_rate': SAMPLE_RATE, 'subtype': SUBTYPE, 'min_duration': DURATION - 5},\n}\nfor stem in STEM_NAMES:\n    expected_specs[f'{stem}_processed.wav'] = {'sample_rate': SAMPLE_RATE, 'subtype': SUBTYPE, 'min_duration': DURATION - 5}\nexpected_specs['drums_processed.wav'] = {'sample_rate': SAMPLE_RATE, 'subtype': SUBTYPE, 'min_duration': DURATION - 5}\n\nverification = final_verification(expected_specs)\nprint(f\"\\nFinal verification: {verification['passed']} passed, {verification['failed']} failed\")\nfor detail in verification['details']:\n    print(f\"  {detail}\")\n\nassert verification['failed'] == 0, f\"Final verification failed: {verification['details']}\"\nprint(\"\\n✓ Workflow completed successfully!\")\n```\n\n## Complete Workflow Script\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nIncremental Audio Production Workflow\nGenerates, verifies, and archives audio stems with fail-fast checkpoints.\n\"\"\"\n\nimport soundfile as sf\nimport numpy as np\nfrom scipy import signal\nimport zipfile\nimport os\nimport sys\n\n# Configuration\nSAMPLE_RATE = 48000\nDURATION = 137\nBPM = 120\nSUBTYPE = 'FLOAT'\nSTEM_NAMES = ['bass', 'guitars', 'synths', 'bridge']\nSECTIONS = {'intro': 16, 'verse': 32, 'chorus': 32, 'bridge': 16, 'outro': 16}\n\ndef calculate_section_transitions(bpm, total_duration_sec, sections):\n    beats_per_second = bpm \u002F 60.0\n    section_durations = {}\n    cumulative_time = 0\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        }\n        cumulative_time += duration\n    return section_durations\n\ndef verify_stem(filepath, expected_sample_rate, expected_subtype, expected_duration):\n    if not os.path.exists(filepath):\n        return {'success': False, 'error': f'File not found: {filepath}'}\n    info = sf.info(filepath)\n    errors = []\n    if info.samplerate != expected_sample_rate:\n        errors.append(f'sample_rate mismatch')\n    if info.subtype != expected_subtype:\n        errors.append(f'subtype mismatch')\n    if abs(info.duration - expected_duration) > 1.0:\n        errors.append(f'duration mismatch')\n    if errors:\n        return {'success': False, 'error': '; '.join(errors)}\n    return {'success': True, 'info': info}\n\ndef generate_stem(name, duration_sec, sample_rate, subtype='FLOAT'):\n    frames = int(duration_sec * sample_rate)\n    t = np.linspace(0, duration_sec, frames)\n    freqs = {'bass': 110, 'guitars': 440, 'synths': 880, 'bridge': 220}\n    freq = freqs.get(name, 440)\n    audio_data = (np.sin(2 * np.pi * freq * t) * 0.5).astype(np.float32)\n    filepath = f'{name}_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    return filepath, audio_data\n\ndef generate_drum_stem(duration_sec, sample_rate, bpm, subtype='FLOAT'):\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    for beat_time in np.arange(0, duration_sec, 1.0 \u002F beats_per_second):\n        start_frame = int(beat_time * sample_rate)\n        if start_frame \u003C frames:\n            kick_duration = 0.1\n            kick_frames = int(kick_duration * sample_rate)\n            end_frame = min(start_frame + kick_frames, frames)\n            t = np.linspace(0, kick_duration, end_frame - start_frame)\n            kick = np.exp(-5 * t) * np.sin(2 * np.pi * 60 * t)\n            audio_data[start_frame:end_frame] += kick * 0.9\n    audio_data = np.clip(audio_data, -1, 1)\n    filepath = 'drums_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    return filepath, audio_data\n\ndef apply_effects(input_filepath, output_filepath, sample_rate, subtype):\n    data, sr = sf.read(input_filepath)\n    nyquist = sample_rate \u002F 2\n    b, a = signal.butter(4, 8000 \u002F nyquist, btype='low')\n    processed = signal.filtfilt(b, a, data)\n    processed = np.clip(processed, -1, 1)\n    sf.write(output_filepath, processed, sample_rate, subtype=subtype, format='WAV')\n    return verify_stem(output_filepath, sample_rate, subtype, DURATION)\n\ndef run_workflow():\n    print(\"=\" * 60)\n    print(\"INCREMENTAL AUDIO PRODUCTION WORKFLOW\")\n    print(\"=\" * 60)\n    \n    # Step 1: Calculate timing\n    print(\"\\n[Step 1] Calculating timing parameters...\")\n    timing = calculate_section_transitions(BPM, DURATION, SECTIONS)\n    print(f\"✓ Timing calculated for {len(SECTIONS)} sections\")\n    \n    # Step 2: Verify reference\n    print(\"\\n[Step 2] Verifying reference file...\")\n    if os.path.exists('reference.wav'):\n        ref_info = sf.info('reference.wav')\n        print(f\"✓ Reference: {ref_info.duration:.2f}s @ {ref_info.samplerate}Hz\")\n    else:\n        print(\"! No reference file found, proceeding with defaults\")\n    \n    # Step 3: Generate stems individually\n    print(\"\\n[Step 3] Generating stems (one at a time)...\")\n    generated_stems = []\n    for stem_name in STEM_NAMES:\n        print(f\"  Generating {stem_name}...\")\n        filepath, _ = generate_stem(stem_name, DURATION, SAMPLE_RATE, subtype=SUBTYPE)\n        result = verify_stem(filepath, SAMPLE_RATE, SUBTYPE, DURATION)\n        if result['success']:\n            print(f\"  ✓ {stem_name} verified\")\n            generated_stems.append(filepath)\n        else:\n            print(f\"  ✗ {stem_name} FAILED: {result['error']}\")\n            sys.exit(1)\n    \n    # Step 4: Generate drums\n    print(\"\\n[Step 4] Generating drum stem...\")\n    drums_filepath, _ = generate_drum_stem(DURATION, SAMPLE_RATE, BPM, subtype=SUBTYPE)\n    drums_result = verify_stem(drums_filepath, SAMPLE_RATE, SUBTYPE, DURATION)\n    if drums_result['success']:\n        print(f\"✓ Drums verified\")\n        generated_stems.append(drums_filepath)\n    else:\n        print(f\"✗ Drums FAILED: {drums_result['error']}\")\n        sys.exit(1)\n    \n    # Step 5: Apply effects\n    print(\"\\n[Step 5] Applying effects...\")\n    processed_stems = []\n    for stem_name in STEM_NAMES:\n        input_file = f'{stem_name}_stem.wav'\n        output_file = f'{stem_name}_processed.wav'\n        result = apply_effects(input_file, output_file, SAMPLE_RATE, SUBTYPE)\n        if result['success']:\n            print(f\"  ✓ {stem_name} processed\")\n            processed_stems.append(output_file)\n        else:\n            print(f\"  ✗ {stem_name} processing FAILED\")\n            sys.exit(1)\n    \n    drums_processed = 'drums_processed.wav'\n    drums_fx_result = apply_effects('drums_stem.wav', drums_processed, SAMPLE_RATE, SUBTYPE)\n    if drums_fx_result['success']:\n        print(f\"  ✓ Drums processed\")\n        processed_stems.append(drums_processed)\n    else:\n        sys.exit(1)\n    \n    # Step 6: Create master\n    print(\"\\n[Step 6] Creating master track...\")\n    first_data, _ = sf.read(processed_stems[0])\n    master_audio = np.zeros(len(first_data), dtype=np.float32)\n    for stem_file in processed_stems:\n        data, _ = sf.read(stem_file)\n        master_audio += data * 0.4\n    master_audio = np.clip(master_audio, -1, 1)\n    sf.write('master_track.wav', master_audio, SAMPLE_RATE, subtype=SUBTYPE, format='WAV')\n    master_info = sf.info('master_track.wav')\n    print(f\"✓ Master track: {master_info.duration:.2f}s @ {master_info.samplerate}Hz\")\n    \n    # Step 7: Archive and verify\n    print(\"\\n[Step 7] Creating archive and final verification...\")\n    all_files = ['master_track.wav'] + processed_stems\n    with zipfile.ZipFile('audio_deliverables.zip', 'w', zipfile.ZIP_DEFLATED) as zf:\n        for f in all_files:\n            zf.write(f)\n    \n    with zipfile.ZipFile('audio_deliverables.zip', 'r') as zf:\n        print(f\"✓ Archive contains {len(zf.namelist())} files\")\n    \n    # Final verification\n    specs = {f: {'sample_rate': SAMPLE_RATE, 'subtype': SUBTYPE} for f in all_files}\n    passed = failed = 0\n    for filepath, expected in specs.items():\n        info = sf.info(filepath)\n        if info.samplerate == expected['sample_rate'] and info.subtype == expected['subtype']:\n            passed += 1\n        else:\n            failed += 1\n            print(f\"  ✗ {filepath} verification failed\")\n    \n    print(f\"\\nFinal verification: {passed} passed, {failed} failed\")\n    if failed > 0:\n        sys.exit(1)\n    \n    print(\"\\n\" + \"=\" * 60)\n    print(\"WORKFLOW COMPLETED SUCCESSFULLY\")\n    print(\"=\" * 60)\n    return 0\n\nif __name__ == '__main__':\n    sys.exit(run_workflow())\n```\n\n## Troubleshooting\n\n### Common Issues\n\n**Memory errors during stem generation:**\n- Process stems one at a time (this skill's default approach)\n- Reduce duration or sample rate for testing\n- Use `np.float32` instead of `np.float64`\n\n**Sample rate mismatches:**\n- Always specify `sample_rate` explicitly in `sf.write()`\n- Verify with `sf.info()` after each write operation\n- Check that `subtype` parameter is specified\n\n**Archive creation failures:**\n- Verify all files exist before archiving\n- Use `zipfile.ZIP_DEFLATED` for compression\n- Check file permissions\n\n### Best Practices\n\n1. **Run incrementally**: Test each step independently before running full workflow\n2. **Verify early**: Check output properties immediately after generation\n3. **Use explicit types**: Always specify `subtype` and `format` parameters\n4. **Monitor memory**: Process large files in chunks if needed\n5. **Keep logs**: Save verification results for debugging\n","# Incremental Audio Production Workflow\n\nThis skill provides a resilient pattern for audio production that emphasizes **incremental verification** and **fail-fast** principles. Each major step produces verified outputs before proceeding, reducing iteration count and catching errors early.\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\n3. **Generate and verify each stem individually** - One stem at a time with immediate verification\n4. **Generate drum stem separately** - Dedicated drum extension with rhythm patterns\n5. **Apply effects with verification** - Process each stem and verify output\n6. **Export master track** - Mix all verified stems\n7. **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- **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)\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):\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) > 1.0:  # Allow 1s tolerance\n        errors.append(f'duration: expected ~{expected_duration}s, got {info.duration}s')\n    \n    if errors:\n        return {'success': False, 'error': '; '.join(errors)}\n    \n    return {'success': True, 'info': info}\n\n# Generate stems one at a time with verification\nSAMPLE_RATE = 48000\nSUBTYPE = 'FLOAT'\nSTEM_NAMES = ['bass', 'guitars', 'synths', 'bridge']\n\ngenerated_stems = []\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, DURATION)\n    \n    if result['success']:\n        print(f\"✓ {stem_name} stem verified: {result['info'].duration:.2f}s @ {result['info'].samplerate}Hz\")\n        generated_stems.append(filepath)\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: 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(DURATION, SAMPLE_RATE, BPM, timing, subtype=SUBTYPE)\n\ndrums_result = verify_stem(drums_filepath, SAMPLE_RATE, SUBTYPE, DURATION)\nif drums_result['success']:\n    print(f\"✓ Drum stem verified: {drums_result['info'].duration:.2f}s @ {drums_result['info'].samplerate}Hz\")\n    generated_stems.append(drums_filepath)\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 5: Apply Effects with Verification\n\nProcess each 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, DURATION)\n    return result, processed\n\nprint(\"\\n=== Applying effects to all stems ===\")\nprocessed_stems = []\n\nfor stem_name in STEM_NAMES:\n    input_file = f'{stem_name}_stem.wav'\n    output_file = f'{stem_name}_processed.wav'\n    \n    print(f\"Processing {stem_name}...\")\n    result, _ = apply_effects_and_verify(input_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\n# Process drums separately\ndrums_output = 'drums_processed.wav'\ndrums_result, _ = apply_effects_and_verify('drums_stem.wav', drums_output, SAMPLE_RATE, SUBTYPE)\nif drums_result['success']:\n    print(f\"✓ Drums processed and verified\")\n    processed_stems.append(drums_output)\nelse:\n    raise RuntimeError(f\"Drums processing failed: {drums_result['error']}\")\n```\n\n## Step 6: 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 stem_file in stem_files:\n        data, _ = sf.read(stem_file)\n        if len(data) == len(master_audio):\n            master_audio += data * gain_per_stem\n        else:\n            print(f\"WARNING: {stem_file} has different length, skipping\")\n    \n    # Final limiting\n    master_audio = np.clip(master_audio, -1, 1)\n    \n    # Export\n    sf.write(output_filepath, master_audio, sample_rate, subtype=subtype, format='WAV')\n    \n    # Verify\n    info = sf.info(output_filepath)\n    return {'success': True, 'info': info}\n\nprint(\"\\n=== Creating master track ===\")\nmaster_result = create_master_track(processed_stems, 'master_track.wav', SAMPLE_RATE, SUBTYPE)\n\nif master_result['success']:\n    print(f\"✓ Master track created: {master_result['info'].duration:.2f}s @ {master_result['info'].samplerate}Hz\")\nelse:\n    raise RuntimeError(\"Master track creation failed\")\n```\n\n## Step 7: Archive and Final Verification\n\nPackage all deliverables and perform comprehensive verification:\n\n```python\nimport zipfile\n\ndef create_archive(archive_name, file_list):\n    \"\"\"Create zip archive and verify contents.\"\"\"\n    with zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED) as zipf:\n        for filepath in file_list:\n            if os.path.exists(filepath):\n                zipf.write(filepath, os.path.basename(filepath))\n            else:\n                raise FileNotFoundError(f\"Cannot archive: {filepath} not found\")\n    \n    # Verify archive\n    with zipfile.ZipFile(archive_name, 'r') as zipf:\n        contents = zipf.namelist()\n    \n    return {'success': True, 'file_count': len(contents), 'files': contents}\n\ndef final_verification(specs):\n    \"\"\"Comprehensive final verification of all outputs.\"\"\"\n    results = {'passed': 0, 'failed': 0, 'details': []}\n    \n    for filepath, expected in specs.items():\n        if not os.path.exists(filepath):\n            results['failed'] += 1\n            results['details'].append(f\"MISSING: {filepath}\")\n            continue\n        \n        info = sf.info(filepath)\n        errors = []\n        \n        if expected.get('sample_rate') and info.samplerate != expected['sample_rate']:\n            errors.append(f\"sample_rate: {info.samplerate} != {expected['sample_rate']}\")\n        \n        if expected.get('subtype') and info.subtype != expected['subtype']:\n            errors.append(f\"subtype: {info.subtype} != {expected['subtype']}\")\n        \n        if expected.get('min_duration') and info.duration \u003C expected['min_duration']:\n            errors.append(f\"duration: {info.duration}s \u003C {expected['min_duration']}s\")\n        \n        if errors:\n            results['failed'] += 1\n            results['details'].append(f\"FAILED: {filepath} - {'; '.join(errors)}\")\n        else:\n            results['passed'] += 1\n            results['details'].append(f\"PASSED: {filepath} ({info.duration:.2f}s, {info.samplerate}Hz)\")\n    \n    return results\n\nprint(\"\\n=== Creating archive ===\")\ndeliverables = ['master_track.wav'] + STEM_NAMES + ['drums']\ndeliverable_files = [f'{name}.wav' if name != 'drums' else 'drums_processed.wav' for name in ['master_track'] + STEM_NAMES + ['drums_processed']]\ndeliverable_files = ['master_track.wav'] + [f'{s}_processed.wav' for s in STEM_NAMES] + ['drums_processed.wav']\n\narchive_result = create_archive('audio_deliverables.zip', deliverable_files)\nprint(f\"✓ Archive created with {archive_result['file_count']} files\")\n\nprint(\"\\n=== Final verification ===\")\nexpected_specs = {\n    'master_track.wav': {'sample_rate': SAMPLE_RATE, 'subtype': SUBTYPE, 'min_duration': DURATION - 5},\n}\nfor stem in STEM_NAMES:\n    expected_specs[f'{stem}_processed.wav'] = {'sample_rate': SAMPLE_RATE, 'subtype': SUBTYPE, 'min_duration': DURATION - 5}\nexpected_specs['drums_processed.wav'] = {'sample_rate': SAMPLE_RATE, 'subtype': SUBTYPE, 'min_duration': DURATION - 5}\n\nverification = final_verification(expected_specs)\nprint(f\"\\nFinal verification: {verification['passed']} passed, {verification['failed']} failed\")\nfor detail in verification['details']:\n    print(f\"  {detail}\")\n\nassert verification['failed'] == 0, f\"Final verification failed: {verification['details']}\"\nprint(\"\\n✓ Workflow completed successfully!\")\n```\n\n## Complete Workflow Script\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nIncremental Audio Production Workflow\nGenerates, verifies, and archives audio stems with fail-fast checkpoints.\n\"\"\"\n\nimport soundfile as sf\nimport numpy as np\nfrom scipy import signal\nimport zipfile\nimport os\nimport sys\n\n# Configuration\nSAMPLE_RATE = 48000\nDURATION = 137\nBPM = 120\nSUBTYPE = 'FLOAT'\nSTEM_NAMES = ['bass', 'guitars', 'synths', 'bridge']\nSECTIONS = {'intro': 16, 'verse': 32, 'chorus': 32, 'bridge': 16, 'outro': 16}\n\ndef calculate_section_transitions(bpm, total_duration_sec, sections):\n    beats_per_second = bpm \u002F 60.0\n    section_durations = {}\n    cumulative_time = 0\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        }\n        cumulative_time += duration\n    return section_durations\n\ndef verify_stem(filepath, expected_sample_rate, expected_subtype, expected_duration):\n    if not os.path.exists(filepath):\n        return {'success': False, 'error': f'File not found: {filepath}'}\n    info = sf.info(filepath)\n    errors = []\n    if info.samplerate != expected_sample_rate:\n        errors.append(f'sample_rate mismatch')\n    if info.subtype != expected_subtype:\n        errors.append(f'subtype mismatch')\n    if abs(info.duration - expected_duration) > 1.0:\n        errors.append(f'duration mismatch')\n    if errors:\n        return {'success': False, 'error': '; '.join(errors)}\n    return {'success': True, 'info': info}\n\ndef generate_stem(name, duration_sec, sample_rate, subtype='FLOAT'):\n    frames = int(duration_sec * sample_rate)\n    t = np.linspace(0, duration_sec, frames)\n    freqs = {'bass': 110, 'guitars': 440, 'synths': 880, 'bridge': 220}\n    freq = freqs.get(name, 440)\n    audio_data = (np.sin(2 * np.pi * freq * t) * 0.5).astype(np.float32)\n    filepath = f'{name}_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    return filepath, audio_data\n\ndef generate_drum_stem(duration_sec, sample_rate, bpm, subtype='FLOAT'):\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    for beat_time in np.arange(0, duration_sec, 1.0 \u002F beats_per_second):\n        start_frame = int(beat_time * sample_rate)\n        if start_frame \u003C frames:\n            kick_duration = 0.1\n            kick_frames = int(kick_duration * sample_rate)\n            end_frame = min(start_frame + kick_frames, frames)\n            t = np.linspace(0, kick_duration, end_frame - start_frame)\n            kick = np.exp(-5 * t) * np.sin(2 * np.pi * 60 * t)\n            audio_data[start_frame:end_frame] += kick * 0.9\n    audio_data = np.clip(audio_data, -1, 1)\n    filepath = 'drums_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    return filepath, audio_data\n\ndef apply_effects(input_filepath, output_filepath, sample_rate, subtype):\n    data, sr = sf.read(input_filepath)\n    nyquist = sample_rate \u002F 2\n    b, a = signal.butter(4, 8000 \u002F nyquist, btype='low')\n    processed = signal.filtfilt(b, a, data)\n    processed = np.clip(processed, -1, 1)\n    sf.write(output_filepath, processed, sample_rate, subtype=subtype, format='WAV')\n    return verify_stem(output_filepath, sample_rate, subtype, DURATION)\n\ndef run_workflow():\n    print(\"=\" * 60)\n    print(\"INCREMENTAL AUDIO PRODUCTION WORKFLOW\")\n    print(\"=\" * 60)\n    \n    # Step 1: Calculate timing\n    print(\"\\n[Step 1] Calculating timing parameters...\")\n    timing = calculate_section_transitions(BPM, DURATION, SECTIONS)\n    print(f\"✓ Timing calculated for {len(SECTIONS)} sections\")\n    \n    # Step 2: Verify reference\n    print(\"\\n[Step 2] Verifying reference file...\")\n    if os.path.exists('reference.wav'):\n        ref_info = sf.info('reference.wav')\n        print(f\"✓ Reference: {ref_info.duration:.2f}s @ {ref_info.samplerate}Hz\")\n    else:\n        print(\"! No reference file found, proceeding with defaults\")\n    \n    # Step 3: Generate stems individually\n    print(\"\\n[Step 3] Generating stems (one at a time)...\")\n    generated_stems = []\n    for stem_name in STEM_NAMES:\n        print(f\"  Generating {stem_name}...\")\n        filepath, _ = generate_stem(stem_name, DURATION, SAMPLE_RATE, subtype=SUBTYPE)\n        result = verify_stem(filepath, SAMPLE_RATE, SUBTYPE, DURATION)\n        if result['success']:\n            print(f\"  ✓ {stem_name} verified\")\n            generated_stems.append(filepath)\n        else:\n            print(f\"  ✗ {stem_name} FAILED: {result['error']}\")\n            sys.exit(1)\n    \n    # Step 4: Generate drums\n    print(\"\\n[Step 4] Generating drum stem...\")\n    drums_filepath, _ = generate_drum_stem(DURATION, SAMPLE_RATE, BPM, subtype=SUBTYPE)\n    drums_result = verify_stem(drums_filepath, SAMPLE_RATE, SUBTYPE, DURATION)\n    if drums_result['success']:\n        print(f\"✓ Drums verified\")\n        generated_stems.append(drums_filepath)\n    else:\n        print(f\"✗ Drums FAILED: {drums_result['error']}\")\n        sys.exit(1)\n    \n    # Step 5: Apply effects\n    print(\"\\n[Step 5] Applying effects...\")\n    processed_stems = []\n    for stem_name in STEM_NAMES:\n        input_file = f'{stem_name}_stem.wav'\n        output_file = f'{stem_name}_processed.wav'\n        result = apply_effects(input_file, output_file, SAMPLE_RATE, SUBTYPE)\n        if result['success']:\n            print(f\"  ✓ {stem_name} processed\")\n            processed_stems.append(output_file)\n        else:\n            print(f\"  ✗ {stem_name} processing FAILED\")\n            sys.exit(1)\n    \n    drums_processed = 'drums_processed.wav'\n    drums_fx_result = apply_effects('drums_stem.wav', drums_processed, SAMPLE_RATE, SUBTYPE)\n    if drums_fx_result['success']:\n        print(f\"  ✓ Drums processed\")\n        processed_stems.append(drums_processed)\n    else:\n        sys.exit(1)\n    \n    # Step 6: Create master\n    print(\"\\n[Step 6] Creating master track...\")\n    first_data, _ = sf.read(processed_stems[0])\n    master_audio = np.zeros(len(first_data), dtype=np.float32)\n    for stem_file in processed_stems:\n        data, _ = sf.read(stem_file)\n        master_audio += data * 0.4\n    master_audio = np.clip(master_audio, -1, 1)\n    sf.write('master_track.wav', master_audio, SAMPLE_RATE, subtype=SUBTYPE, format='WAV')\n    master_info = sf.info('master_track.wav')\n    print(f\"✓ Master track: {master_info.duration:.2f}s @ {master_info.samplerate}Hz\")\n    \n    # Step 7: Archive and verify\n    print(\"\\n[Step 7] Creating archive and final verification...\")\n    all_files = ['master_track.wav'] + processed_stems\n    with zipfile.ZipFile('audio_deliverables.zip', 'w', zipfile.ZIP_DEFLATED) as zf:\n        for f in all_files:\n            zf.write(f)\n    \n    with zipfile.ZipFile('audio_deliverables.zip', 'r') as zf:\n        print(f\"✓ Archive contains {len(zf.namelist())} files\")\n    \n    # Final verification\n    specs = {f: {'sample_rate': SAMPLE_RATE, 'subtype': SUBTYPE} for f in all_files}\n    passed = failed = 0\n    for filepath, expected in specs.items():\n        info = sf.info(filepath)\n        if info.samplerate == expected['sample_rate'] and info.subtype == expected['subtype']:\n            passed += 1\n        else:\n            failed += 1\n            print(f\"  ✗ {filepath} verification failed\")\n    \n    print(f\"\\nFinal verification: {passed} passed, {failed} failed\")\n    if failed > 0:\n        sys.exit(1)\n    \n    print(\"\\n\" + \"=\" * 60)\n    print(\"WORKFLOW COMPLETED SUCCESSFULLY\")\n    print(\"=\" * 60)\n    return 0\n\nif __name__ == '__main__':\n    sys.exit(run_workflow())\n```\n\n## Troubleshooting\n\n### Common Issues\n\n**Memory errors during stem generation:**\n- Process stems one at a time (this skill's default approach)\n- Reduce duration or sample rate for testing\n- Use `np.float32` instead of `np.float64`\n\n**Sample rate mismatches:**\n- Always specify `sample_rate` explicitly in `sf.write()`\n- Verify with `sf.info()` after each write operation\n- Check that `subtype` parameter is specified\n\n**Archive creation failures:**\n- Verify all files exist before archiving\n- Use `zipfile.ZIP_DEFLATED` for compression\n- Check file permissions\n\n### Best Practices\n\n1. **Run incrementally**: Test each step independently before running full workflow\n2. **Verify early**: Check output properties immediately after generation\n3. **Use explicit types**: Always specify `subtype` and `format` parameters\n4. **Monitor memory**: Process large files in chunks if needed\n5. **Keep logs**: Save verification results for debugging\n",{"name":5,"description":7},"main","ff671ef61ed6587c49bd54c81cdc751c0b99e363","gdpval_bench\u002Fskills\u002Faudio-track-production-enhanced","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace","https:\u002F\u002Fgithub.com\u002FAG064","AG064, E.Mi.\r\n\r\nA person who thinks all the time, yet all they have to think about is nothing. I want to improve the world and work on open source projects","2026-10-08 06:53:48",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add AG064\u002FOpenSpace --skill incremental-audio-workflow",{"tool":55,"command":56},"bunx","bunx skills add AG064\u002FOpenSpace --skill incremental-audio-workflow",{"tool":58,"command":59},"pnpm","pnpm dlx skills add AG064\u002FOpenSpace --skill incremental-audio-workflow","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced\u002FSKILL.md",true,[63],{"path":64,"resourceType":65,"resourceTypeDesc":66,"sizeBytes":67,"sourceHtmlUrl":68},".skill_id","OTHER","其他",45,"https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced\u002F.skill_id",[70,94,109,118,148,164],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":37},"01M6KKMPWA0B5SCCH766F8M5EA","write-special-chars-ts-check","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, plus a reliable TypeScript type-checking step that filters output to only the newly-written files to avoid being misled by pre-existing errors.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93],"write special chars ts check","check","write","filters","Existing","type-checking","for","errors","script","output","type","files","only","template","file","python","typescript",{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":37},"01M6KKMJXVBNVEY3TRK055F4A7","write-special-chars-readback","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of \u002Ftmp helper scripts.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[101,102,79,90,103,104,91,92,105,30,106,107,108,83,85,36],"readback","write special chars readback","cleanup","read","scripts","via","post","helper",{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":37},"01M6KKMEGX9M9NC105J0W3Q5B9","write-special-chars-heredoc","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) by using a Python heredoc script executed via shell.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-heredoc\u002FSKILL.md",[],[79,116,92,83,106,90,117,91,85],"write special chars heredoc","shell",{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":129,"publishedAt":37},"01M6KKM8EJ2AATVHZBNB916WT0","worldmonitor-reference","Curated architecture index of the WorldMonitor open-source dashboard. Reference for extracting patterns — vanilla TypeScript, Panel class hierarchy, service layer, CSS grid, API edge functions, refresh scheduler, and 60+ data source integrations.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fworldmonitor-reference\u002FSKILL.md",[124],{"categoryNo":125,"categoryName":126,"taxonomyType":127,"taxonomyTypeDesc":128},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[130,131,132,133,93,134,135,136,137,138,83,139,140,141,142,143,144,145,146,147],"reference","worldmonitor","worldmonitor reference","dashboard","css","architecture","extracting","hierarchy","source","layer","panel","patterns","edge functions","integrations","open","api","data","scheduler",{"skillNo":149,"name":150,"nameZh":6,"description":151,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":152,"categories":153,"keywords":154,"publishedAt":37},"01M6KKM39PHYK627F19GE2B9XN","virtual-list","Implement efficient virtual scrolling for rendering large lists with DOM recycling, chunk-based rendering, and performance optimizations","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fvirtual-list\u002FSKILL.md",[],[155,156,157,158,83,159,36,160,161,162,163],"virtual list","list","virtual","chunk","dom","rendering","recycling","implement","performance",{"skillNo":165,"name":166,"nameZh":6,"description":167,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":168,"categories":169,"keywords":170,"publishedAt":37},"01M6KKKY7T2P61Y0JH54CDEJKQ","verify-directory-structure","Diagnose and resolve file access issues by first verifying the directory structure.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fverify-directory-structure\u002FSKILL.md",[],[171,172,173,174,175,176,91,177,178,179],"directory","verify","structure","verify directory structure","access","first","issues","diagnose","file access"]