[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HXEMGH2TMCRFRCWDBCEZQC":3,"skill-same:01M6HXEMGH2TMCRFRCWDBCEZQC":71},{"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":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":43,"commitSha":44,"skillDirectory":45,"forksCount":46,"repositoryHtmlUrl":47,"repositoryHomepageUrl":6,"ownerHtmlUrl":48,"ownerBlogUrl":49,"ownerDescription":6,"updatedAt":50,"install":51,"resources":64},"01M6HXEMGH2TMCRFRCWDBCEZQC","incremental-audio-workflow",null,"Step-by-step audio production with per-stem verification, timing alignment, and incremental quality gates","HKUDS\u002FAgentPilot","HKUDS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F118165258?v=4","01M6HW8VRNZP64G0P4MVJW2KKQ","✨Data Intelligence Lab@HKU✨","01M6HW8VWZVHBRHYH3T330PFWV",8029,"MIT","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-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,37],"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","6b84b0689ca0d9e7b1e4061188ff6b60758e0f8a","openspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced",944,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot","https:\u002F\u002Fgithub.com\u002FHKUDS","https:\u002F\u002Fsites.google.com\u002Fview\u002Fchaoh","2026-11-12 22:26:39",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add HKUDS\u002FAgentPilot --skill incremental-audio-workflow",{"tool":57,"command":58},"bunx","bunx skills add HKUDS\u002FAgentPilot --skill incremental-audio-workflow",{"tool":60,"command":61},"pnpm","pnpm dlx skills add HKUDS\u002FAgentPilot --skill incremental-audio-workflow","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced\u002FSKILL.md",true,[65],{"path":66,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":69,"sourceHtmlUrl":70},".skill_id","OTHER","其他",45,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced\u002F.skill_id",[72,91,110,131,155,178],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":38},"01M6HYB297NDABRERJRVG0K8R0","agentpilot","Set up AgentPilot and use its single entry to prepare missing inputs and run configured RSI experiments. Use when the user requests AgentPilot installation or work with AgentPilot.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fplugins\u002Fagentpilot\u002Fskills\u002Fagentpilot\u002FSKILL.md",[],[74,79,80,37,81,82,83,84,85,86,87,88,89,90],"prepare","requests","missing","installation","rsi","up","use","user","work","SET","run","experiments",{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":38},"01M6HYAYWXTTE1J7DJM0MFNQ4H","remember","Review auto-memory entries and propose promotions to OPENSPACE.md, OPENSPACE.local.md, or retained auto-memory topics; detect duplicates, stale facts, conflicts, and ambiguous entries before making changes.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fskills\u002Fremember\u002FSKILL.md",[],[93,98,99,100,101,102,103,104,105,106,107,108,109],"memory","review","auto","openspace","changes","facts","detect","entries","local","conflicts","stale","duplicates",{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":117,"publishedAt":38},"01M6HYAVMPM4SBDV60R2B5HPV8","skill-discovery","Search reusable OpenSpace skills locally, and browse cloud packages step by step when a cloud skill may help. Reusing proven skills saves tokens, improves reliability, and extends your capabilities beyond built-in tools.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fskill-discovery\u002FSKILL.md",[116],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[118,119,120,101,121,122,123,124,125,126,127,128,129,130],"skill discovery","discovery","reusable","step by step","tokens","packages","help","cloud","reliability","capabilities","browse","search","Tools",{"skillNo":132,"name":133,"nameZh":6,"description":134,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":135,"categories":136,"keywords":138,"publishedAt":38},"01M6HYAR811B3RB0M50RBEDGN6","delegate-task","Delegate tasks to OpenSpace — a full-stack autonomous worker for coding, DevOps, web research, and desktop automation, backed by an extensive MCP tool and skill library. Skills auto-improve through use, reducing token consumption over time. A cloud community lets agents share and collectively evolve reusable skills.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fdelegate-task\u002FSKILL.md",[137],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[139,140,141,101,142,143,144,145,146,120,100,85,147,148,149,150,151,152,153,154],"delegate","task","delegate task","time","improve","desktop automation","worker","community","autonomous","tool","stack","for","share","tasks","automation","MCP",{"skillNo":156,"name":157,"nameZh":6,"description":158,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":159,"categories":160,"keywords":161,"publishedAt":38},"01M6HYAM9FSGV6E52AYENDQXYH","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\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[162,163,164,165,166,167,168,169,170,171,172,173,174,175,150,176,177],"write special chars ts check","write","check","type","files","filters","only","template","file","python","typescript","output","Existing","type-checking","errors","script",{"skillNo":179,"name":180,"nameZh":6,"description":181,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":182,"categories":183,"keywords":184,"publishedAt":38},"01M6HYAH05HGV7SVWSVR8PJRQD","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\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[185,186,163,37,150,177,187,188,189,190,191,169,170,31,192,171],"write special chars readback","readback","helper","post","via","scripts","read","cleanup"]