# voice-clone-tts

Adopt this skill: https://proskills.md/skills/other/nanmicoder-creator-pipeline-skills-voice-clone-tts

Page: https://proskills.md/skills/other/nanmicoder-creator-pipeline-skills-voice-clone-tts
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/voice-clone-tts/SKILL.md
size: 5152
sha: a68e0b93750abb643066edc5266123b40f8106b3
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/SKILL.md

````text
---
name: voice-clone-tts
description: 将文案与用户自己的参考录音合成为配音、SRT 和可交接时间轴。默认使用 MiniMax 与用户自己的音色；可显式选择免费本地 Qwen3-TTS（Apple Silicon 用 MLX）或 Nano CPU。适用于口播配音、声音复刻，以及为网页视频演示准备最终音频和字幕。
---

# 文案与参考声音 → 配音与时间轴

交付 `voiceover.wav`、`voiceover.mp3`、`voiceover.srt`、`voiceover.json`。WAV 是计时主文件，SRT 是原稿短段对应的采样帧时间；这不是字级强制对齐，也不能证明模型读音完全正确。

## 选择后端

默认 **MiniMax speech-2.8-hd**，使用用户自己的服务账号和已登记音色，可能消耗在线额度。优先完成一个代表性短段，经用户听审后扩展全文。用户明确选择的后端优先于默认值。

- `auto` 读取个人偏好；没有配置时选择 **minimax**。setup 与 run 使用同一逻辑。用 `configure.py` 保存偏好到技能目录外，升级不会覆盖个人音色。
- 免费本地路线显式用 `--provider local`：Apple Silicon 选择 **mlx**（Qwen3-TTS 0.6B Base 4bit），其他平台选择 **qwen**（官方 PyTorch，自动使用可用 CUDA，否则 CPU）。本地推理不需要 API key，首次需要下载模型并占用计算资源。
- **nano** 仅供用户显式选择较轻的 CPU 路线，不因 Qwen 缺依赖或运行失败自动降级。优先保证声音质量，不能把小模型的成功运行当作默认选择依据。
- MiniMax 缺账号或音色时给出配置入口；不自动使用共享音色。首次上传克隆录音需要处于用户授权的在线克隆任务中；已有授权直接执行，不反复确认。不因本地失败自动切换云服务。

各后端使用独立环境；首次运行读 [SETUP.md](references/SETUP.md)。音色来源是用户提供的本人/已获授权录音，没有共享的默认私人音色。

## 执行

先原样保存用户文案为 `script.md`；不擅自改写读法、数字或术语。只有明确的 Markdown 标题不朗读，编号列表保留。产物默认放当前项目的 `voiceover-<主题>/`，先说明位置。

`SKILL_DIR` 表示本 SKILL.md 所在目录。实际定位安装目录，不硬编码某个用户的 `~/.claude` 路径。

```bash
python3 "$SKILL_DIR/scripts/setup.py"
# 上一条会输出独立环境 Python 的实际路径；下文以 PY 表示它。
python3 "$SKILL_DIR/scripts/configure.py" --provider minimax --voice YOUR_VOICE_ID
"$PY" "$SKILL_DIR/scripts/run.py" script.md \
  --outdir voiceover-demo
```

没有 MiniMax 音色时，先按 [SETUP.md](references/SETUP.md) 登记。参考录音选干净、单人、无音乐的完整短段：MiniMax 要求 10–300 秒，通常先选 10–30 秒；本地 Qwen/Nano 通常选 3–30 秒。原录音太长时显式截取，不把全文转写误作短样本转写。Qwen 优先提供精确匹配的 `--reference-text reference.txt`，启用完整 ICL；缺省仅声音嵌入，效果可能不同。Nano 不要求参考转写。

声音条目按完整句子/语义短段组织，默认宽度 40，不为短字幕机械切碎句子。过长字幕可换行；需要更细时间时用最终 WAV 与原文做实际对齐，不按字数比例伪造 cue。

同一命令可续跑；缓存包含正文、声音内容哈希、模型/版本及生成参数。每次成功保存一个 WAV，失败段阻止拼接；改稿后重新分段、合成、拼接。不要只手改 SRT 或把旧音频配到新文案上。分步控制见 [PIPELINE.md](references/PIPELINE.md)。

## 验证与交接

1. `run.py` 会自动执行结构验证：全部段就绪，WAV/MP3/SRT 同源，文件哈希一致，字幕单调且不越界。也可单独运行 `verify.py voiceover-demo/voiceover.json`。
2. 检查实际声音，尤其数字、专名、中英混排、首尾、连接处与最长句。本地 ASR 可辅助找漏读/重读；ASR 正确不等于音色相似，不用转写结果覆盖原稿。
3. 修正有问题的段后重建所有最终产物。保留中间件便于局部重跑，不把模型或个人参考音频提交到仓库。
   本地模型的单句随机生成问题可用 `--segment-seed 2:3`（第 2 段用 seed 3），只使该句缓存失效。选择随该 ID 与正文持久保存，可重复指定，或用 `--clear-segment-seeds` 清空。MiniMax CLI 不提供可控 seed；修改 seed 不能保证复现或改善在线语音。`--force` 会重新请求所有段，并可能产生费用。
4. 接 `web-video-presentation` 时，交 `voiceover.json` 和同目录产物；用它的 `import-voiceover.mjs` 验证后导入，从最终 SRT 规划连续场景，再开发 MG。音频完成之后走网页技能的 VO-First 路径。

比较供应商时按 [VOICE-REVIEW.md](references/VOICE-REVIEW.md) 使用同参考、同文案和未参与克隆的原声片段；用户听感、内容正确性与声纹模型分数分别记录，不把单个余弦分数当作音色相似百分比。开发者保留验证边界，不复述未经实测的“实时”“零误差”“任意硬件可用”承诺。
````

## File: skills/voice-clone-tts/scripts/build.py
size: 5606
sha: cdeca77070c79bdef56a75b4e97ff85aba2c65ab
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/build.py

```text
#!/usr/bin/env python3
"""Build a PCM master, MP3, segment-level SRT and a hash-bound handoff manifest."""
import argparse
import json
import os
import subprocess
import sys
import tempfile
import wave
from pathlib import Path
from common import checked_segments, digest, trim_bounds, write_json

def timestamp(seconds):
    ms = round(seconds * 1000)
    h, ms = divmod(ms, 3600000)
    m, ms = divmod(ms, 60000)
    s, ms = divmod(ms, 1000)
    return f'{h:02}:{m:02}:{s:02},{ms:03}'

def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('segments')
    p.add_argument('-o', '--out', help='Output basename, default voiceover beside segments.json')
    p.add_argument('--no-srt', action='store_true')
    p.add_argument('--srt', action='store_true', help='Compatibility flag; SRT is already enabled by default')
    p.add_argument('--no-trim', action='store_true')
    p.add_argument('--gap-hold', type=float, default=600, help='Subtitle hold across gaps, milliseconds')
    p.add_argument('--trim-db', type=float, default=-45)
    p.add_argument('--trim-margin', type=float, default=15)
    args = p.parse_args()
    if args.gap_hold < 0 or args.trim_margin < 0 or args.trim_db >= 0:
        p.error('Invalid trim or gap parameters')
    sp = Path(args.segments).resolve()
    doc = json.loads(sp.read_text(encoding='utf-8'))
    prepared = checked_segments(doc, sp.parent)  # All validation precedes replacing deliverables.
    base = Path(args.out).resolve() if args.out else sp.parent / 'voiceover'
    base.parent.mkdir(parents=True, exist_ok=True)
    rate = prepared[0][1]['sample_rate']
    cursor, entries = 0, []
    with tempfile.TemporaryDirectory(prefix='build-', dir=base.parent) as td:
        td = Path(td)
        master, mp3, srt = [td / (base.name + ext) for ext in ('.wav', '.mp3', '.srt')]
        with wave.open(str(master), 'wb') as out:
            out.setnchannels(1)
            out.setsampwidth(2)
            out.setframerate(rate)
            for i, (seg, info, raw) in enumerate(prepared):
                first, last = (0, info['frames']) if args.no_trim else trim_bounds(raw, rate, args.trim_db, args.trim_margin)
                raw = raw[first * 2:last * 2]
                frames = len(raw) // 2
                start = cursor
                out.writeframes(raw)
                cursor += frames
                entries.append({'id': seg['id'], 'text': seg['text'], 'chapter': seg['chapter'],
                    'chapter_title': seg.get('chapter_title', ''), 'start_frame': start, 'end_frame': cursor,
                    'start': start / rate, 'end': cursor / rate})
                if i < len(prepared) - 1:
                    gap_ms = float(doc['meta'].get('silence_ms', {}).get(seg.get('boundary', 'sentence'), 180))
                    if not 0 <= gap_ms <= 10000:
                        raise ValueError('Segment pause must be 0–10000 ms')
                    gap = round(gap_ms * rate / 1000)
                    out.writeframes(b'\0' * gap * 2)
                    cursor += gap
        for i, entry in enumerate(entries):
            next_start = entries[i + 1]['start'] if i + 1 < len(entries) else cursor / rate
            entry['subtitle_end'] = next_start if (next_start-entry['end'])*1000 <= args.gap_hold else entry['end']
        subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', str(master), '-c:a', 'libmp3lame',
                        '-b:a', '128k', '-y', str(mp3)], check=True)
        # MP3 container duration can include encoder padding. Verify its decoded samples instead.
        decoded = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', str(mp3), '-f', 's16le',
            '-ac', '1', '-ar', str(rate), '-'], check=True, capture_output=True).stdout
        decoded_frames = len(decoded) // 2
        if abs(decoded_frames - cursor) > 1:
            raise ValueError(f'MP3 decoded duration mismatch: {decoded_frames} vs {cursor} frames')
        if not args.no_srt:
            srt.write_text('\n\n'.join(f"{i}\n{timestamp(e['start'])} --> {timestamp(e['subtitle_end'])}\n{e['text']}"
                for i, e in enumerate(entries, 1)) + '\n', encoding='utf-8')
        files = [master, mp3] + ([] if args.no_srt else [srt])
        manifest = {'schema_version': 1, 'timing_method': 'segment_frames', 'audio': master.name,
            'mp3': mp3.name, 'srt': None if args.no_srt else srt.name, 'sample_rate': rate,
            'total_frames': cursor, 'duration': cursor / rate, 'mp3_decoded_frames': decoded_frames,
            'source_text_sha256': doc['meta'].get('source_text_sha256'),
            'source_file': os.path.relpath(Path(doc['meta']['source']) if Path(doc['meta']['source']).is_absolute()
                else sp.parent / doc['meta']['source'], base.parent),
            'segments_sha256': digest(sp), 'segments_file': os.path.relpath(sp, base.parent),
            'provider': doc['meta']['synthesis']['provider'], 'model': doc['meta']['synthesis']['model'],
            'files': {f.name: digest(f) for f in files}, 'segments': entries}
        # Consumers must verify hashes; manifest is replaced last as the commit record.
        for f in files:
            os.replace(f, base.parent / f.name)
        write_json(base.with_suffix('.json'), manifest)
    print(f'Built {base.name}: {len(entries)} segments, {cursor / rate:.3f}s; timing=segment_frames')
    return 0

if __name__ == '__main__':
    try:
        sys.exit(main())
    except (ValueError, OSError, subprocess.CalledProcessError) as e:
        print(f'Error: {e}', file=sys.stderr)
        sys.exit(1)
```

## File: skills/voice-clone-tts/scripts/clone-minimax.py
size: 5519
sha: 4909a7a706a57014d2f91546012b44a64fcf8992
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/clone-minimax.py

```text
#!/usr/bin/env python3
"""Explicit cloud-only registration: upload your recording to MiniMax, return your voice ID."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import urllib.error
import urllib.request
import uuid

def credentials(region=None):
    # Follow the installed mmx CLI: configured API key first. Never mix accounts
    # between upload and clone; MINIMAX_API_KEY is a fallback when no key is saved.
    path = Path(os.environ.get('MMX_CONFIG_DIR', Path.home() / '.mmx')) / 'config.json'
    config = json.loads(path.read_text()) if path.exists() else {}
    key = config.get('api_key') or os.environ.get('MINIMAX_API_KEY')
    region = region or os.environ.get('MINIMAX_REGION') or config.get('region') or 'global'
    if not key:
        raise ValueError('Voice registration needs a MiniMax API key: configure mmx auth login or MINIMAX_API_KEY.')
    if region not in ('cn', 'global'):
        raise ValueError('MiniMax region must be cn or global')
    return key, region

def request_json(url, key, body, content_type):
    req = urllib.request.Request(url, data=body, headers={
        'Authorization': 'Bearer ' + key, 'Content-Type': content_type})
    try:
        with urllib.request.urlopen(req, timeout=120) as response:
            result = json.load(response)
    except urllib.error.HTTPError as e:
        # Never include request headers, credentials or a raw response in errors.
        raise RuntimeError(f'MiniMax HTTP {e.code}; check account permissions and region') from None
    status = result.get('base_resp', {})
    if status.get('status_code') != 0:
        raise RuntimeError(f"MiniMax status {status.get('status_code')}: {status.get('status_msg', '')}")
    return result

def audio_info(path):
    path = Path(path)
    if not path.is_file() or path.suffix.lower() not in ('.mp3', '.m4a', '.wav'):
        raise ValueError('Supply an existing MP3, M4A or WAV recording')
    duration = float(subprocess.check_output(['ffprobe', '-v', 'error', '-show_entries',
        'format=duration', '-of', 'csv=p=0', str(path)], text=True))
    if path.stat().st_size > 20 * 1024 * 1024:
        raise ValueError('Recording exceeds 20 MB')
    return path, duration

def upload(host, key, path, purpose):
    boundary = 'creator-' + uuid.uuid4().hex
    head = (f'--{boundary}\r\nContent-Disposition: form-data; name="purpose"\r\n\r\n{purpose}\r\n'
            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="reference{path.suffix.lower()}"\r\n'
            'Content-Type: application/octet-stream\r\n\r\n').encode()
    body = head + path.read_bytes() + f'\r\n--{boundary}--\r\n'.encode()
    result = request_json(host + '/v1/files/upload', key, body, 'multipart/form-data; boundary=' + boundary)
    return int(result['file']['file_id'])

def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('reference')
    p.add_argument('voice_id')
    p.add_argument('--region', choices=['cn', 'global'])
    p.add_argument('--prompt-audio', help='Optional matching prompt clip shorter than 8 seconds')
    p.add_argument('--prompt-text', help='UTF-8 transcript file matching --prompt-audio exactly')
    p.add_argument('--denoise', action='store_true')
    p.add_argument('--out', help='Optional local voice receipt JSON; never contains credentials')
    args = p.parse_args()
    if not re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{6,254}[A-Za-z0-9]', args.voice_id):
        p.error('Voice ID: 8–256 characters, starts with a letter, ends with a letter/digit')
    if bool(args.prompt_audio) != bool(args.prompt_text):
        p.error('--prompt-audio and --prompt-text must be supplied together')
    reference, duration = audio_info(args.reference)
    if not 10 <= duration <= 300:
        p.error('MiniMax reference must be 10–300 seconds')
    prompt = None
    if args.prompt_audio:
        prompt, seconds = audio_info(args.prompt_audio)
        transcript = Path(args.prompt_text).read_text(encoding='utf-8').strip()
        if not 0 < seconds < 8 or not transcript:
            p.error('Prompt must be shorter than 8 seconds with a non-empty matching transcript')
    key, region = credentials(args.region)
    host = 'https://api.minimaxi.com' if region == 'cn' else 'https://api.minimax.io'
    print(f'Uploading {duration:.2f}s reference to MiniMax ({region}).', flush=True)
    payload = {'file_id': upload(host, key, reference, 'voice_clone'), 'voice_id': args.voice_id,
               'need_volume_normalization': True, 'need_noise_reduction': args.denoise}
    if prompt:
        payload['clone_prompt'] = {'prompt_audio': upload(host, key, prompt, 'prompt_audio'), 'prompt_text': transcript}
    request_json(host + '/v1/voice_clone', key, json.dumps(payload).encode(), 'application/json')
    if args.out:
        receipt = {'provider': 'minimax', 'voice': args.voice_id, 'region': region,
                   'reference_sha256': hashlib.sha256(reference.read_bytes()).hexdigest(),
                   'reference_duration': duration, 'denoise': args.denoise,
                   'prompt_sha256': hashlib.sha256(prompt.read_bytes()).hexdigest() if prompt else None}
        dest = Path(args.out); dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + '\n')
    print(f'Registered voice: {args.voice_id}. Use --provider minimax --voice {args.voice_id}.')

if __name__ == '__main__':
    main()
```

## File: skills/voice-clone-tts/scripts/common.py
size: 3889
sha: 8a5d1cfc0dd9b5ba5ada9a8870d3560aeb875ced
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/common.py

```text
"""Shared file and audio contracts. Core pipeline uses only the Python standard library."""
import array
import hashlib
import json
import os
import subprocess
import wave
from pathlib import Path

def digest(path):
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b''):
            h.update(chunk)
    return h.hexdigest()

def write_json(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(path.name + '.tmp')
    tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    os.replace(tmp, path)

def fingerprint(seg, meta):
    key = {'text': seg['text'], 'synthesis': meta['synthesis']}
    if 'seed_override' in seg:
        key['seed_override'] = seg['seed_override']
    return hashlib.sha256(json.dumps(key, sort_keys=True, ensure_ascii=False).encode()).hexdigest()

def wav_info(path, require_signal=True):
    try:
        with wave.open(str(path), 'rb') as w:
            channels, width, rate, frames = w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes()
            raw = w.readframes(frames)
    except (wave.Error, EOFError) as e:
        raise ValueError(f'Invalid WAV: {path}') from e
    if channels != 1 or width != 2 or rate <= 0 or frames == 0 or len(raw) != frames * channels * width:
        raise ValueError(f'Invalid or truncated mono PCM16 WAV: {path}')
    if require_signal and not any(raw):
        raise ValueError(f'Silent output: {path}')
    return {'sample_rate': rate, 'frames': frames, 'duration': frames / rate}, raw

def normalize_audio(source, dest, sample_rate=24000):
    subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', str(source), '-vn', '-ac', '1',
                    '-ar', str(sample_rate), '-c:a', 'pcm_s16le', '-y', str(dest)], check=True)
    return wav_info(dest)[0]

def checked_segments(doc, base):
    """Never combine stale audio after a text, reference, model or setting change."""
    segments = doc.get('segments', [])
    if not segments or 'synthesis' not in doc.get('meta', {}):
        raise ValueError('No synthesized segments. Run synth.py first.')
    source = Path(doc['meta']['source'])
    if not source.is_absolute():
        source = Path(base) / source
    if digest(source) != doc['meta'].get('source_text_sha256'):
        raise ValueError('Source script changed since segmentation. Run the full pipeline again.')
    ids = [s['id'] for s in segments]
    if len(ids) != len(set(ids)):
        raise ValueError('Duplicate segment ids')
    result = []
    for seg in segments:
        if seg.get('status') != 'ready' or seg.get('fingerprint') != fingerprint(seg, doc['meta']):
            raise ValueError(f"Segment {seg['id']} is missing or stale. Run synth.py again.")
        path = Path(seg['wav'])
        if not path.is_absolute():
            path = Path(base) / path
        info, raw = wav_info(path)
        if digest(path) != seg.get('audio_sha256'):
            raise ValueError(f"Segment {seg['id']} audio has changed. Re-synthesize it.")
        result.append((seg, info, raw))
    rates = {info['sample_rate'] for _, info, _ in result}
    if len(rates) != 1:
        raise ValueError('Segment sample rates differ')
    return result

def trim_bounds(raw, rate, db=-45, margin_ms=15):
    samples = array.array('h', raw)
    if os.sys.byteorder != 'little':
        samples.byteswap()
    peak = max(map(abs, samples), default=0)
    if not peak:
        raise ValueError('Silent output')
    threshold = peak * 10 ** (db / 20)
    first = next(i for i, x in enumerate(samples) if abs(x) > threshold)
    last = len(samples) - next(i for i, x in enumerate(reversed(samples)) if abs(x) > threshold)
    margin = round(rate * margin_ms / 1000)
    return max(0, first - margin), min(len(samples), last + margin)
```

## File: skills/voice-clone-tts/scripts/configure.py
size: 1833
sha: 2efb53e95c16a5aa979d762d1c6a01321bf15fa7
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/configure.py

```text
#!/usr/bin/env python3
"""Save your personal provider/voice outside the skill; no upload or synthesis."""
import argparse
import json
import os
from pathlib import Path
import tempfile
from user_config import PROVIDERS, FIELDS, config_path, load_config

def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--provider', choices=PROVIDERS)
    p.add_argument('--voice', help='Your registered MiniMax voice ID; never a shared preset')
    p.add_argument('--reference', help='Your local 3–30 second MP3/WAV reference clip')
    p.add_argument('--reference-text', help='Transcript matching your reference clip')
    args = p.parse_args()
    data = load_config()
    for key in FIELDS:
        value = getattr(args, key)
        if value is not None:
            if key in ('reference', 'reference_text'):
                path = Path(value).resolve()
                if not path.is_file():
                    p.error(f'{key} must be an existing file')
                value = str(path)
                if key == 'reference' and value != data.get('reference') and args.reference_text is None:
                    data.pop('reference_text', None)
            if not value.strip():
                p.error(f'{key} cannot be empty')
            data[key] = value
    if not data:
        p.error('Supply at least one preference')
    path = config_path(); path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent, delete=False) as f:
        json.dump(data, f, ensure_ascii=False, indent=2); f.write('\n')
        temporary = f.name
    try:
        os.replace(temporary, path)
    finally:
        Path(temporary).unlink(missing_ok=True)
    print(f'Personal voice preferences saved: {path}')

if __name__ == '__main__':
    main()
```

## File: skills/voice-clone-tts/scripts/providers.py
size: 6650
sha: 95203b258b32ad5969d98a6bfe5801c0022e29d3
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/providers.py

```text
"""Optional model backends. Imported lazily; no provider silently falls back to cloud."""
import os
import platform
import subprocess
from pathlib import Path

MODELS = {
    'nano': 'OpenMOSS-Team/MOSS-TTS-Nano-100M-ONNX',
    'mlx': 'mlx-community/Qwen3-TTS-12Hz-0.6B-Base-4bit',
    'qwen': 'Qwen/Qwen3-TTS-12Hz-0.6B-Base',
    'minimax': 'speech-2.8-hd',
}
NANO_COMMIT = '8b7bcc9341b3b4ef3a3a58ba1338a7d85ff133eb'
REVISIONS = {
    'nano': 'f52645cb467506d8e18e746ddd59482685b74e58',
    'mlx': '0d6bb6fe33f92d47a507e23b9148940e8366ab5b',
    'qwen': '5d83992436eae1d760afd27aff78a71d676296fc',
}
NANO_TOKENIZER_REVISION = 'ceff0d0749bfb3fa2d61149794ec6feef0d1e1ae'

def local_provider():
    """Explicit free local route: Qwen3-TTS, with MLX on Apple Silicon."""
    return 'mlx' if platform.system() == 'Darwin' and platform.machine() == 'arm64' else 'qwen'

def auto_provider():
    """Package preference; no failed backend silently selects another one."""
    return 'minimax'

class Nano:
    def __init__(self, settings, reference, ref_text):
        import torch
        from huggingface_hub import snapshot_download
        from onnx_tts_runtime import OnnxTtsRuntime
        torch.set_num_threads(settings['threads'])
        root = Path(os.environ.get('CREATOR_MODEL_DIR', Path.home() / '.cache' / 'creator-pipeline' / 'models'))
        if settings['model'] != MODELS['nano']:
            root = Path(settings['model'])  # Local root containing the two named ONNX model folders.
            if not root.is_dir():
                raise ValueError('nano --model must be a local root containing both ONNX model folders')
        else:
            for repo, rev in [(MODELS['nano'], REVISIONS['nano']),
                             ('OpenMOSS-Team/MOSS-Audio-Tokenizer-Nano-ONNX', NANO_TOKENIZER_REVISION)]:
                snapshot_download(repo, revision=rev, local_dir=root / repo.split('/')[-1],
                    allow_patterns=['*.onnx', '*.data', '*.json', 'tokenizer.model'], max_workers=2)
        class CachedReference(OnnxTtsRuntime):
            def resolve_prompt_audio_codes(self, **kwargs):
                if kwargs.get('prompt_audio_path') == self.reference_path:
                    return self.reference_codes
                return super().resolve_prompt_audio_codes(**kwargs)
        self.runtime = CachedReference(model_dir=root, thread_count=settings['threads'],
            max_new_frames=settings['max_tokens'], execution_provider='cpu', output_dir=reference.parent)
        self.runtime.reference_path = str(reference)
        self.runtime.reference_codes = self.runtime.encode_reference_audio(str(reference))
        self.settings, self.ref_text = settings, ref_text or ''

    def generate(self, text, dest, seed):
        import numpy as np
        r = self.runtime.synthesize(text=text, prompt_audio_path=self.runtime.reference_path,
            output_audio_path=dest, streaming=False,
            max_new_frames=self.settings['max_tokens'], enable_wetext=False,
            enable_normalize_tts_text=False, seed=seed)
        if not np.isfinite(r['waveform']).all() or len(r['audio_token_ids']) >= self.settings['max_tokens']:
            raise ValueError('Invalid or capped generation; shorten segment or inspect and retry')

def save_float(path, data, rate):
    import numpy as np
    import wave
    x = np.asarray(data, dtype=np.float32).reshape(-1)
    if not len(x) or not np.isfinite(x).all():
        raise ValueError('Model returned empty or non-finite samples')
    with wave.open(str(path), 'wb') as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(rate)
        w.writeframes((np.clip(x, -1, 1) * 32767).astype('<i2').tobytes())

class MLX:
    def __init__(self, settings, reference, ref_text):
        from mlx_audio.tts.utils import load_model
        from huggingface_hub import snapshot_download
        model = settings['model']
        if model == MODELS['mlx']:
            model = snapshot_download(model, revision=REVISIONS['mlx'], max_workers=2)
        self.model = load_model(model)
        self.settings, self.reference, self.ref_text = settings, reference, ref_text

    def generate(self, text, dest, seed):
        import mlx.core as mx
        import numpy as np
        mx.random.seed(seed)
        pieces = []
        for result in self.model.generate(text=text, ref_audio=str(self.reference), ref_text=self.ref_text,
                lang_code=self.settings['language'].lower(), temperature=self.settings['temperature'],
                max_tokens=self.settings['max_tokens'], split_pattern=None, verbose=False):
            pieces.append(np.asarray(result.audio, dtype=np.float32))
            rate = result.sample_rate
        if not pieces:
            raise ValueError('No audio returned')
        save_float(dest, np.concatenate(pieces), rate)

class Qwen:
    def __init__(self, settings, reference, ref_text):
        import torch
        from qwen_tts import Qwen3TTSModel
        self.settings = settings
        device = settings['device']
        if device == 'auto':
            device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
        self.model = Qwen3TTSModel.from_pretrained(settings['model'], device_map=device,
            dtype=torch.float32 if device == 'cpu' else torch.float16, attn_implementation='sdpa',
            revision=REVISIONS['qwen'] if settings['model'] == MODELS['qwen'] else None)
        self.prompt = self.model.create_voice_clone_prompt(ref_audio=str(reference),
            ref_text=ref_text, x_vector_only_mode=not bool(ref_text))

    def generate(self, text, dest, seed):
        import torch
        torch.manual_seed(seed)
        waves, rate = self.model.generate_voice_clone(text=text, language=self.settings['language'],
            voice_clone_prompt=self.prompt, temperature=self.settings['temperature'],
            max_new_tokens=self.settings['max_tokens'])
        save_float(dest, waves[0], rate)

class MiniMax:
    def __init__(self, settings, reference, ref_text):
        self.settings = settings

    def generate(self, text, dest, seed):
        # Credentials remain in the caller's environment/mmx keychain, never in a manifest.
        s = self.settings
        subprocess.run(['mmx', 'speech', 'synthesize', '--text', text, '--voice', s['voice'],
            '--model', s['model'], '--format', 'wav', '--sample-rate', str(s['sample_rate']),
            '--channels', '1', '--out', str(dest), '--non-interactive', '--quiet'], check=True,
            timeout=180, stdout=subprocess.DEVNULL)

BACKENDS = {'nano': Nano, 'mlx': MLX, 'qwen': Qwen, 'minimax': MiniMax}
```

## File: skills/voice-clone-tts/scripts/run.py
size: 1373
sha: bc79fcf42408bf0ed3f2212da40730fbcda87309
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/run.py

```text
#!/usr/bin/env python3
"""Script + your reference recording -> voiceover.wav, .mp3, .srt and .json."""
import argparse
import shutil
import subprocess
import sys
from pathlib import Path

def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('script')
    p.add_argument('--outdir', required=True)
    p.add_argument('--max-chars', type=float, default=40)
    p.add_argument('--min-chars', type=float, default=8)
    args, synthesis_args = p.parse_known_args()
    src = Path(args.script).resolve()
    out = Path(args.outdir).resolve()
    if not src.is_file():
        p.error('Script does not exist')
    out.mkdir(parents=True, exist_ok=True)
    target = out / 'script.md'
    if src != target:
        shutil.copyfile(src, target)
    scripts = Path(__file__).resolve().parent
    def run(name, *extra):
        subprocess.run([sys.executable, str(scripts / name), *map(str, extra)], check=True)
    run('segment.py', target, '-o', out/'segments.json', '--max-chars', args.max_chars, '--min-chars', args.min_chars)
    run('synth.py', out/'segments.json', *synthesis_args)
    run('build.py', out/'segments.json')
    run('verify.py', out/'voiceover.json')
    print(f'Handoff: {out / "voiceover.json"}')

if __name__ == '__main__':
    try:
        main()
    except subprocess.CalledProcessError as e:
        sys.exit(e.returncode)
```

## File: skills/voice-clone-tts/scripts/segment.py
size: 13787
sha: 64dcf1739365e8361b576915e607f1366d4dc33c
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/segment.py

```text
#!/usr/bin/env python3
"""把自媒体文案切成「章节 → 自然段 → 分段」，产出 segments.json。

一个分段 = 一次 TTS 调用 = 一条 SRT 字幕。三者一一对应，时间轴才能精确。

用法:
    python3 segment.py script.md -o segments.json [--voice VOICE_ID] [--max-chars 20]

输入可以是纯文本，也可以带明确的 Markdown 章节标题（## 标题）。
若文案已由上层做过语义分章，用 `--chapters chapters.json` 传入骨架，
格式: [{"title": "开场钩子", "text": "……"}, ...]
"""

import argparse
import hashlib
import math
import os
import json
import re
import sys
from pathlib import Path

# 句末标点：切分段的第一优先级
SENT_END = "。！？!?…～~"
# 次级标点：句子过长时的切分点
CLAUSE_END = "，、；：,;:—"
# 右侧成对标点，切分时应跟随前文
CLOSERS = '」』】》）)"\'”’…'

# 章节标记
# Only explicit Markdown headings are metadata. Numbered lists are spoken content.
CH_PATTERNS = [re.compile(r"^\s{0,3}#{1,4}\s+(.+?)\s*$")]

def width(s: str) -> float:
    """视觉宽度：中日韩字符算 1，ASCII 算 0.5。让「20 字」对中英混排也合理。"""
    w = 0.0
    for ch in s:
        w += 0.5 if ord(ch) < 0x2E80 else 1.0
    return w

def detect_chapter(line: str):
    """行是章节标题则返回标题文本，否则 None。"""
    stripped = line.strip()
    if not stripped or width(stripped) > 40:
        return None
    for pat in CH_PATTERNS:
        m = pat.match(line)
        if m:
            title = (m.group(1) or "").strip()
            return title or stripped
    return None

def split_sentences(text: str):
    """按句末标点切句，标点保留在句尾，右引号/右括号跟随。"""
    out, buf = [], ""
    i, n = 0, len(text)
    while i < n:
        ch = text[i]
        buf += ch
        if ch in SENT_END:
            # 吸收连续的句末标点（如 ！！！ 或 ？！）
            while i + 1 < n and text[i + 1] in SENT_END:
                i += 1
                buf += text[i]
            # 吸收右侧成对标点
            while i + 1 < n and text[i + 1] in CLOSERS:
                i += 1
                buf += text[i]
            if buf.strip():
                out.append(buf.strip())
            buf = ""
        i += 1
    if buf.strip():
        out.append(buf.strip())
    return out

def split_clauses(sentence: str):
    """按次级标点切子句，标点保留在子句尾。"""
    out, buf = [], ""
    for i, ch in enumerate(sentence):
        buf += ch
        if ch in CLAUSE_END:
            nxt = sentence[i + 1] if i + 1 < len(sentence) else ""
            if nxt in CLOSERS:
                continue
            if buf.strip():
                out.append(buf.strip())
            buf = ""
    if buf.strip():
        out.append(buf.strip())
    return out

# 英文单词、数字、版本号（GPT-4o、47.3%、1200ms）视为不可切分的原子
ATOM_RE = re.compile(r"[A-Za-z0-9]+(?:[.\-_/][A-Za-z0-9]+)*%?")

def atomize(text: str):
    """切成不可分割的原子：连续英文/数字算一个，中文与标点各算一个。

    空格附着到前一个原子，避免行首出现孤立空格。
    """
    atoms, i, n = [], 0, len(text)
    while i < n:
        if text[i] == " ":
            if atoms:
                atoms[-1] += " "
            i += 1
            continue
        m = ATOM_RE.match(text, i)
        if m and m.end() > i:
            atoms.append(m.group())
            i = m.end()
        else:
            atoms.append(text[i])
            i += 1
    return atoms

def is_ascii_word(s: str) -> bool:
    return bool(s) and all(ord(c) < 0x2E80 for c in s.strip()) and s.strip().isalnum()

def cut_score(left: str, right_atom: str) -> int:
    """在 left 之后、right_atom 之前断开的质量。中文没有词边界，
    所以只能利用「空格」和「中英交界」这两个天然信号。"""
    if not left:
        return 0
    if left.endswith(" "):
        return 3
    tail, head = left.rstrip()[-1:], right_atom[:1]
    if not tail or not head:
        return 0
    # 中英/中数 交界处断开，通常正好是词的边界
    if (ord(tail) < 0x2E80) != (ord(head) < 0x2E80):
        return 2
    return 0

def hard_wrap(text: str, max_chars: float):
    """兜底：无标点的超长串切分。不切开英文单词/数字，
    并优先在空格或中英交界处断，而不是一味填满到上限。"""
    atoms = atomize(text)
    out, i, n = [], 0, len(atoms)
    while i < n:
        buf, j = "", i
        cands = []  # (score, width, j, text)
        while j < n:
            nxt = buf + atoms[j]
            if buf and width(nxt) > max_chars:
                break
            buf, j = nxt, j + 1
            w = width(buf)
            if j < n and w >= max_chars * 0.5:
                cands.append((cut_score(buf, atoms[j]), w, j, buf))
        if j >= n:  # 剩余部分能一次放下
            if buf.strip():
                out.append(buf.strip())
            break
        if cands:
            cands.sort(key=lambda c: (c[0], c[1]))
            _, _, j, buf = cands[-1]
        elif j == i:  # 单个原子就超宽，强制吃掉它
            buf, j = atoms[i], i + 1
        if buf.strip():
            out.append(buf.strip())
        i = j
    return out or [text.strip()]

def pack_sentence(sentence: str, max_chars: float):
    """把一个句子切成 ≤max_chars 的片段列表。"""
    if width(sentence) <= max_chars:
        return [sentence]

    pieces = []
    for clause in split_clauses(sentence):
        if width(clause) <= max_chars:
            pieces.append(clause)
        else:
            pieces.extend(hard_wrap(clause, max_chars))

    # 贪心合并相邻子句，尽量吃满 max_chars
    merged = []
    for p in pieces:
        if merged and width(merged[-1] + p) <= max_chars:
            merged[-1] += p
        else:
            merged.append(p)
    return merged

def merge_short(items, max_chars: float, min_chars: float):
    """把过短的片段并入相邻片段，避免单独合成时语调突兀。

    items: [(text, boundary)]，boundary 取自该片段之后的停顿级别。
    合并时保留后者的 boundary（因为合并后以后者结尾）。
    """
    if not items:
        return []
    out = list(items)
    changed = True
    while changed and len(out) > 1:
        changed = False
        for i, (text, _b) in enumerate(out):
            if width(text) >= min_chars:
                continue
            # 优先并入前一个（更自然），否则并入后一个
            if i > 0 and width(out[i - 1][0] + text) <= max_chars:
                out[i - 1] = (out[i - 1][0] + text, out[i][1])
                del out[i]
                changed = True
                break
            if i + 1 < len(out) and width(text + out[i + 1][0]) <= max_chars:
                out[i + 1] = (text + out[i + 1][0], out[i + 1][1])
                del out[i]
                changed = True
                break
    return out

def parse_chapters(raw: str):
    """纯文本 → [{"title", "paragraphs": [str]}]。"""
    chapters, cur = [], None
    for line in raw.splitlines():
        title = detect_chapter(line)
        if title is not None:
            cur = {"title": title, "paragraphs": [], "_buf": []}
            chapters.append(cur)
            continue
        if cur is None:
            cur = {"title": "", "paragraphs": [], "_buf": []}
            chapters.append(cur)
        if line.strip():
            cur["_buf"].append(line.strip())
        elif cur["_buf"]:
            cur["paragraphs"].append(" ".join(cur["_buf"]))
            cur["_buf"] = []
    for c in chapters:
        if c["_buf"]:
            c["paragraphs"].append(" ".join(c["_buf"]))
        del c["_buf"]
    return [c for c in chapters if c["paragraphs"]]

def build_segments(chapters, max_chars: float, min_chars: float):
    """章节结构 → 扁平分段列表，每段带其后的停顿级别 boundary。"""
    segments = []
    for ci, ch in enumerate(chapters):
        for pi, para in enumerate(ch["paragraphs"]):
            items = []
            sents = split_sentences(para)
            for si, sent in enumerate(sents):
                pieces = pack_sentence(sent, max_chars)
                for k, piece in enumerate(pieces):
                    # 句内子句之间用 clause，句子结束用 sentence
                    b = "sentence" if k == len(pieces) - 1 else "clause"
                    items.append((piece, b))
            items = merge_short(items, max_chars, min_chars)
            if not items:
                continue
            # 该自然段最后一段的停顿升级为 para / chapter
            is_last_para = pi == len(ch["paragraphs"]) - 1
            tail = "chapter" if is_last_para else "para"
            items[-1] = (items[-1][0], tail)
            for text, boundary in items:
                segments.append({
                    "id": len(segments) + 1,
                    "text": text,
                    "chapter": ci,
                    "chapter_title": ch["title"],
                    "para": pi,
                    "boundary": boundary,
                    "duration_ms": None,
                    "wav": None,
                })
    if segments:
        segments[-1]["boundary"] = "end"
    return segments

def main():
    ap = argparse.ArgumentParser(description="文案切分为 segments.json")
    ap.add_argument("input", help="文案文件（.md/.txt）")
    ap.add_argument("-o", "--out", default="segments.json")
    ap.add_argument("--chapters", help="上层已做好语义分章的 JSON: [{title,text}]")
    ap.add_argument("--voice", default=None, help="音色 ID（默认读 skill config.json）")
    ap.add_argument("--model", default=None)
    ap.add_argument("--max-chars", type=float, default=None, help="单条字幕最大视觉宽度")
    ap.add_argument("--min-chars", type=float, default=None, help="低于此宽度尝试合并")
    args = ap.parse_args()

    cfg_path = Path(__file__).resolve().parent.parent / "config.json"
    cfg = json.loads(cfg_path.read_text(encoding="utf-8")) if cfg_path.exists() else {}

    voice = args.voice or cfg.get("voice")
    model = args.model or cfg.get("model")
    max_chars = args.max_chars if args.max_chars is not None else cfg.get("max_chars", 40)
    min_chars = args.min_chars if args.min_chars is not None else cfg.get("min_chars", 8)

    if not all(map(math.isfinite, (min_chars, max_chars))) or not 0 < min_chars <= max_chars:
        ap.error("Require 0 < min-chars <= max-chars")

    raw = Path(args.input).read_text(encoding="utf-8")
    source_chapters = parse_chapters(raw)
    if args.chapters:
        data = json.loads(Path(args.chapters).read_text(encoding="utf-8"))
        chapters = []
        for c in data:
            paras = [p.strip() for p in re.split(r"\n\s*\n", c["text"]) if p.strip()]
            paras = [" ".join(p.splitlines()) for p in paras]
            chapters.append({"title": c.get("title", ""), "paragraphs": paras})
        def spoken_content(items):
            return re.sub(r'\s+', '', ''.join(p for c in items for p in c['paragraphs']))
        if spoken_content(chapters) != spoken_content(source_chapters):
            ap.error('Chapter text must preserve the original spoken content and order')
    else:
        chapters = source_chapters

    if not chapters:
        print("错误：未解析到任何正文内容", file=sys.stderr)
        return 1

    segments = build_segments(chapters, max_chars, min_chars)
    if not segments:
        print("错误：切分结果为空", file=sys.stderr)
        return 1

    # Keep approved targeted retries for unchanged segment IDs and text.
    # A different paragraph never inherits another paragraph's seed.
    output = Path(args.out)
    if output.exists():
        try:
            previous = json.loads(output.read_text(encoding='utf-8'))
        except (ValueError, OSError):
            previous = {}
        saved = {(s.get('id'), s.get('text')): s.get('seed_override')
                 for s in previous.get('segments', []) if isinstance(s, dict)}
        for seg in segments:
            seed = saved.get((seg['id'], seg['text']))
            if isinstance(seed, int) and not isinstance(seed, bool) and seed >= 0:
                seg['seed_override'] = seed

    doc = {
        "meta": {
            "voice": voice,
            "model": model,
            "max_chars": max_chars,
            "min_chars": min_chars,
            "sample_rate": cfg.get("sample_rate", 24000),
            "silence_ms": cfg.get("silence_ms", {
                "clause": 80, "sentence": 180, "para": 400, "chapter": 700, "end": 0,
            }),
            "source": os.path.relpath(Path(args.input).resolve(), Path(args.out).parent.resolve()),
            "source_text_sha256": hashlib.sha256(Path(args.input).read_bytes()).hexdigest(),
        },
        "segments": segments,
    }
    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    Path(args.out).write_text(
        json.dumps(doc, ensure_ascii=False, indent=2), encoding="utf-8"
    )

    n_ch = len({s["chapter"] for s in segments})
    chars = sum(len(s["text"]) for s in segments)
    widths = [width(s["text"]) for s in segments]
    over = sum(1 for w in widths if w > max_chars)
    print(f"✓ {args.out}")
    print(f"  章节 {n_ch} · 分段 {len(segments)} · 正文字符 {chars}")
    print(f"  单条宽度 最大 {max(widths):.1f} / 平均 {sum(widths)/len(widths):.1f} "
          f"（上限 {max_chars}，超限 {over} 条）")
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

## File: skills/voice-clone-tts/scripts/setup.py
size: 2681
sha: 463c736421db11d783d5cdc0608ce6e5e06c8a49
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/setup.py

```text
#!/usr/bin/env python3
"""Install one backend in a separate Python 3.12 environment; models download on first synthesis."""
import argparse
import os
import platform
import shutil
import subprocess
from pathlib import Path
from providers import NANO_COMMIT
from user_config import configured_provider

def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--provider', choices=['auto', 'local', 'nano', 'mlx', 'qwen', 'minimax'], default='auto')
    p.add_argument('--env', help='Environment directory; default .creator-env/<provider> in this project')
    args = p.parse_args()
    args.provider = configured_provider(args.provider)
    print(f'Backend: {args.provider}', flush=True)
    if not shutil.which('uv'):
        p.error('Install uv first: https://docs.astral.sh/uv/getting-started/installation/')
    if not shutil.which('ffmpeg'):
        p.error('Install FFmpeg first; macOS: brew install ffmpeg; Ubuntu: sudo apt install ffmpeg')
    if args.provider == 'mlx' and (platform.system() != 'Darwin' or platform.machine() != 'arm64'):
        p.error('MLX requires Apple Silicon. Use qwen for the official PyTorch backend.')
    env = Path(args.env or f'.creator-env/{args.provider}').resolve()
    python = env / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')
    if not python.exists():
        subprocess.run(['uv', 'venv', '--python', '3.12', str(env)], check=True)
    def install(*packages, extra=()):
        subprocess.run(['uv', 'pip', 'install', '--python', str(python), *extra, *packages], check=True)
    if args.provider == 'nano':
        # Linux/Windows use CPU wheels explicitly; avoid downloading the CUDA stack for this CPU backend.
        extra = () if platform.system() == 'Darwin' else ('--index-url', 'https://download.pytorch.org/whl/cpu')
        install('torch==2.7.0', 'torchaudio==2.7.0', extra=extra)
        install('numpy==2.2.6', 'sentencepiece==0.2.1', 'onnxruntime==1.22.1',
                'huggingface-hub==0.36.2', 'soundfile==0.13.1')
        install(f'moss-tts-nano @ git+https://github.com/OpenMOSS/MOSS-TTS-Nano.git@{NANO_COMMIT}',
                extra=('--no-deps',))
    elif args.provider == 'mlx':
        install('mlx-audio==0.5.1')
    elif args.provider == 'qwen':
        install('qwen-tts==0.1.1')
    else:
        print('MiniMax also needs the official mmx CLI and your own speech-capable account.')
    print(f'Python ready: {python}')
    print('MiniMax uses your configured mmx account and registered voice ID.' if args.provider == 'minimax'
          else 'Model weights are public downloads; local inference needs no API key.')

if __name__ == '__main__':
    main()
```

## File: skills/voice-clone-tts/scripts/synth.py
size: 8891
sha: fb2aa3474224203773ddc0fa19bacd21c4c8c211
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/synth.py

```text
#!/usr/bin/env python3
"""Synthesize with your selected voice; cache inputs and checkpoint successful segments."""
import argparse
import importlib.metadata
import json
import os
import shutil
import sys
import tempfile
import time
from pathlib import Path
from common import digest, fingerprint, normalize_audio, wav_info, write_json
from providers import BACKENDS, MODELS, REVISIONS, NANO_COMMIT, NANO_TOKENIZER_REVISION
from user_config import load_config, configured_provider

def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('segments')
    p.add_argument('--provider', choices=['auto', 'local', *BACKENDS], default='auto')
    p.add_argument('--reference', help='Your reference MP3/WAV; local backends keep it on this computer')
    p.add_argument('--reference-text', help='Optional UTF-8 transcript file matching the reference clip')
    p.add_argument('--voice', help='MiniMax voice ID, required only for the cloud backend')
    p.add_argument('--model', help='Model ID or local model directory')
    p.add_argument('--language', default='Chinese')
    p.add_argument('--device', default='auto', help='qwen: auto, cpu or cuda:0')
    p.add_argument('--temperature', type=float, default=.8)
    p.add_argument('--max-tokens', type=int, default=800)
    p.add_argument('--seed', type=int, default=0)
    p.add_argument('--segment-seed', action='append', default=[], metavar='ID:SEED',
                   help='Override one segment seed; repeat this option for targeted retries')
    p.add_argument('--clear-segment-seeds', action='store_true',
                   help='Explicitly clear saved per-segment seeds before applying new overrides')
    p.add_argument('--threads', type=int, default=4, help='Nano CPU threads')
    p.add_argument('--force', action='store_true')
    args = p.parse_args()
    if not shutil.which('ffmpeg'):
        p.error('ffmpeg is required. See references/SETUP.md.')
    defaults = load_config()
    provider = configured_provider(args.provider, defaults)
    args.voice = args.voice or os.environ.get('MINIMAX_VOICE_ID') or defaults.get('voice')
    explicit_reference = args.reference is not None
    args.reference = args.reference or defaults.get('reference')
    # Never attach an old transcript to a new explicitly supplied recording.
    if not explicit_reference and not args.reference_text:
        args.reference_text = defaults.get('reference_text')
    if provider == 'minimax':
        if not args.voice or not shutil.which('mmx'):
            p.error('MiniMax needs mmx and your voice ID (--voice, MINIMAX_VOICE_ID, or configure.py). Use --provider local for free Qwen cloning. No recording is uploaded automatically.')
        # A registered cloud voice needs no local reference or transcript file.
        # Moving a reference used by Qwen must not break existing MiniMax voices.
        args.reference = args.reference_text = None
    elif not args.reference or not Path(args.reference).is_file():
        p.error('Local cloning requires --reference your-recording.mp3')
    if args.max_tokens <= 0 or args.threads <= 0 or not 0 < args.temperature <= 2:
        p.error('max-tokens must be positive; temperature must be in (0, 2]')
    sp = Path(args.segments).resolve()
    doc = json.loads(sp.read_text(encoding='utf-8'))
    if not doc.get('segments'):
        p.error('No segments')
    overrides = {}
    for value in args.segment_seed:
        try:
            ident, seed = map(int, value.split(':'))
        except ValueError:
            p.error('segment-seed must be ID:INTEGER')
        if ident not in {s['id'] for s in doc['segments']} or seed < 0:
            p.error('segment-seed requires an existing segment ID and a nonnegative seed')
        overrides[ident] = seed
    out = sp.parent / 'wav'
    out.mkdir(exist_ok=True)
    ref_text = Path(args.reference_text).read_text(encoding='utf-8').strip() if args.reference_text else None
    if args.reference_text and not ref_text:
        p.error('Reference transcript is empty')
    package = {'nano': 'moss-tts-nano', 'mlx': 'mlx-audio', 'qwen': 'qwen-tts', 'minimax': None}[provider]
    try:
        version = importlib.metadata.version(package) if package else 'mmx'
    except importlib.metadata.PackageNotFoundError:
        p.error(f'{package} is not installed in this Python environment. Run setup.py --provider {provider}.')
    settings = dict(provider=provider, model=args.model or MODELS[provider], language=args.language,
        device=args.device, temperature=args.temperature, max_tokens=args.max_tokens, seed=args.seed,
        voice=args.voice if provider == 'minimax' else None, sample_rate=24000,
        reference_sha256=digest(args.reference) if provider != 'minimax' else None,
        reference_text=ref_text, runtime_version=version, adapter_version=1, threads=args.threads,
        model_revision=REVISIONS.get(provider) if not args.model or args.model == MODELS[provider] else 'custom',
        nano_source=NANO_COMMIT if provider == 'nano' else None,
        tokenizer_revision=NANO_TOKENIZER_REVISION if provider == 'nano' else None)
    if args.model and Path(args.model).is_dir():
        settings['local_model_files'] = {str(f.relative_to(args.model)): digest(f)
            for f in sorted(Path(args.model).rglob('*')) if f.is_file() and f.suffix in
            ('.json', '.safetensors', '.onnx', '.data', '.bin', '.pt', '.model')}
    doc['meta']['synthesis'] = settings
    pending = []
    for seg in doc['segments']:
        if args.clear_segment_seeds:
            seg.pop('seed_override', None)
        if seg['id'] in overrides:
            seg['seed_override'] = overrides[seg['id']]
        fp = fingerprint(seg, doc['meta'])
        dst = out / f"{seg['id']:04d}_{fp[:20]}.wav"
        marker = dst.with_suffix('.json')
        cached = False
        if not args.force and dst.exists() and marker.exists():
            try:
                record = json.loads(marker.read_text())
                info, _ = wav_info(dst)
                cached = record.get('fingerprint') == fp and record.get('sha256') == digest(dst)
            except (ValueError, OSError, EOFError):
                pass
        seg.update(fingerprint=fp, status='ready' if cached else 'pending',
            wav=str(dst.relative_to(sp.parent)) if cached else None,
            audio_sha256=digest(dst) if cached else None)
        if cached:
            seg['duration_ms'] = info['duration'] * 1000
        else:
            pending.append((seg, dst, marker))
    # Clear stale references before loading a model or starting a paid request.
    write_json(sp, doc)
    if not pending:
        print(f"{len(doc['segments'])}/{len(doc['segments'])} ready (cache); no model loaded")
        return 0
    print(f"Backend: {provider}; {len(pending)} pending." +
          (' Cloud speech uses your MiniMax account.' if provider == 'minimax' else ' First use may download public model weights.'), flush=True)
    started = time.perf_counter()
    with tempfile.TemporaryDirectory(prefix='voice-clone-', dir=sp.parent) as td:
        td = Path(td)
        ref = td / 'reference.wav'
        if provider != 'minimax':
            info = normalize_audio(args.reference, ref)
            if not 3 <= info['duration'] <= 30:
                p.error('Use a clean 3–30 second reference clip. Trim it explicitly first; transcript must match.')
        backend = BACKENDS[provider](settings, ref, ref_text)
        for seg, dst, marker in pending:
            native, normalized = td / 'native.wav', td / 'normalized.wav'
            try:
                backend.generate(seg['text'], native, seg.get('seed_override', args.seed + seg['id']))
                info = normalize_audio(native, normalized)
                if info['duration'] >= args.max_tokens / 12.5 - .5 and provider in ('mlx', 'qwen'):
                    raise ValueError('Generation reached the duration cap; inspect/retry instead of publishing truncated speech')
                os.replace(normalized, dst)
                sha = digest(dst)
                write_json(marker, {'fingerprint': seg['fingerprint'], 'sha256': sha})
                seg.update(status='ready', wav=str(dst.relative_to(sp.parent)), audio_sha256=sha,
                           duration_ms=info['duration'] * 1000)
                write_json(sp, doc)
                print(f"  {seg['id']}: {info['duration']:.3f}s", flush=True)
            except Exception:
                seg.update(status='failed', wav=None, audio_sha256=None)
                write_json(sp, doc)
                raise
    print(f"{len(doc['segments'])}/{len(doc['segments'])} ready; {time.perf_counter()-started:.1f}s elapsed")
    return 0

if __name__ == '__main__':
    try:
        sys.exit(main())
    except (ValueError, OSError, RuntimeError) as e:
        print(f'Error: {e}', file=sys.stderr)
        sys.exit(1)
```

## File: skills/voice-clone-tts/scripts/user_config.py
size: 1574
sha: 1ace2864d1edc7043b074c2331db369535aadf5a
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/user_config.py

```text
"""Personal voice preferences live outside the installed skill and public repository."""
import json
import os
from pathlib import Path
from providers import auto_provider, local_provider

PROVIDERS = ('local', 'minimax', 'mlx', 'qwen', 'nano')
FIELDS = ('provider', 'voice', 'reference', 'reference_text')

def config_path():
    return Path(os.environ.get('CREATOR_TTS_CONFIG', Path.home() / '.config/creator-pipeline/voice.json'))

def load_config():
    path = config_path()
    if not path.exists():
        return {}
    data = json.loads(path.read_text(encoding='utf-8'))
    if not isinstance(data, dict) or any(k not in FIELDS for k in data):
        raise ValueError('Voice preferences support provider, voice, reference and reference_text only; keep API keys in mmx.')
    if any(not isinstance(v, str) or not v.strip() for v in data.values()):
        raise ValueError('Voice preferences must be non-empty strings')
    if data.get('provider') and data['provider'] not in PROVIDERS:
        raise ValueError('Unknown provider in voice preferences')
    return data

def configured_provider(requested=None, config=None):
    config = load_config() if config is None else config
    selected = requested if requested not in (None, 'auto') else os.environ.get('CREATOR_TTS_PROVIDER') or config.get('provider')
    if selected is None or selected == 'auto':
        return auto_provider()
    if selected not in PROVIDERS:
        raise ValueError('Unknown CREATOR_TTS_PROVIDER or voice provider')
    return local_provider() if selected == 'local' else selected
```

## File: skills/voice-clone-tts/scripts/verify.py
size: 3723
sha: a88ec3397f14a700b2af1e1f76fa14814da2af7c
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/scripts/verify.py

```text
#!/usr/bin/env python3
"""Check a completed handoff; this verifies timing/files, not spoken pronunciation or speaker identity."""
import argparse
import json
import math
import re
from pathlib import Path
from common import digest, wav_info

def timecode(t):
    h, m, s, ms = map(int, re.split('[:,]', t))
    if m >= 60 or s >= 60:
        raise ValueError('Invalid SRT time')
    return h * 3600 + m * 60 + s + ms / 1000

def verify(path):
    path = Path(path).resolve()
    doc = json.loads(path.read_text(encoding='utf-8'))
    if doc.get('schema_version') != 1 or doc.get('timing_method') != 'segment_frames':
        raise ValueError('Unsupported manifest schema')
    for name in [doc['audio'], doc['mp3']] + ([doc['srt']] if doc.get('srt') else []):
        if not isinstance(name,str) or name not in doc['files']:
            raise ValueError('Manifest must hash all deliverables')
    for name, sha in doc['files'].items():
        if Path(name).name != name or digest(path.parent / name) != sha:
            raise ValueError(f'Changed or unsafe artifact: {name}')
    info, _ = wav_info(path.parent / doc['audio'])
    if info['frames'] != doc['total_frames'] or info['sample_rate'] != doc['sample_rate']:
        raise ValueError('PCM duration mismatch')
    if not math.isclose(doc['duration'], info['duration'], abs_tol=1e-9):
        raise ValueError('Manifest duration mismatch')
    segments = doc['segments']
    if not segments:
        raise ValueError('No cues')
    for s in segments:
        if not all(isinstance(s.get(k),(int,float)) and math.isfinite(s[k]) for k in ['start','end','subtitle_end']):
            raise ValueError('Non-finite segment time')
        if not 0 <= s['start'] < s['end'] <= s['subtitle_end'] <= doc['duration']+.00051:
            raise ValueError('Invalid segment bounds')
        if abs(s['start']-s['start_frame']/info['sample_rate'])>1e-9 or abs(s['end']-s['end_frame']/info['sample_rate'])>1e-9:
            raise ValueError('Segment differs from sample frames')
    if digest(path.parent / doc['segments_file']) != doc['segments_sha256']:
        raise ValueError('Segments changed since build; regenerate audio and rebuild')
    if digest(path.parent / doc['source_file']) != doc['source_text_sha256']:
        raise ValueError('Source script changed since build; regenerate the handoff')
    if doc.get('srt'):
        blocks = (path.parent / doc['srt']).read_text(encoding='utf-8-sig').strip().split('\n\n')
        if len(blocks) != len(segments):
            raise ValueError('Cue count mismatch')
        previous = 0
        for i, (block, seg) in enumerate(zip(blocks, segments), 1):
            lines = block.splitlines()
            a, b = map(timecode, lines[1].split(' --> '))
            if lines[0] != str(i) or '\n'.join(lines[2:]) != seg['text']:
                raise ValueError('Cue text or order mismatch')
            if not previous <= a < b <= doc['duration'] + .00051:
                raise ValueError('Overlapping or out-of-range cue')
            if abs(a - seg['start']) > .00051 or abs(b - seg['subtitle_end']) > .00051:
                raise ValueError('Cue differs from PCM timeline')
            previous = b
        if abs(previous-doc['duration'])>.00051:
            raise ValueError('Last cue differs from PCM duration')
    return {'status': 'pass', 'segments': len(segments), 'duration': doc['duration'], 'timing_method': doc['timing_method']}

if __name__ == '__main__':
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('manifest')
    args = p.parse_args()
    try:
        print(json.dumps(verify(args.manifest)))
    except (ValueError, KeyError, OSError) as e:
        p.exit(1, f'Error: {e}\n')
```

## File: skills/voice-clone-tts/references/PIPELINE.md
size: 3093
sha: 98b961344c04f052f532fb43e451d91d31cebb1b
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/references/PIPELINE.md

````text
# 分步运行与可靠交接

run.py 等价于以下步骤，全部脚本都位于本 skill 的 scripts/：

```bash
mkdir -p voiceover-demo
cp script.md voiceover-demo/script.md
"$PY" "$SKILL_DIR/scripts/segment.py" voiceover-demo/script.md -o voiceover-demo/segments.json
"$PY" "$SKILL_DIR/scripts/synth.py" voiceover-demo/segments.json
"$PY" "$SKILL_DIR/scripts/build.py" voiceover-demo/segments.json
"$PY" "$SKILL_DIR/scripts/verify.py" voiceover-demo/voiceover.json
```

产物约定：`voiceover.wav` 是统一 24kHz/mono/PCM16 主文件，MP3 是分发副本；SRT 文本来自合成段原文，时间来自写入 PCM 的采样帧。`voiceover.json` 包含 schema_version、duration、total_frames、timing_method、文件哈希、source_text_sha256、段级边界和文本。

段级时轴保证的是“这段合成音频被拼接到哪里”。自动静音修剪基于波形阈值，并非声学对齐模型；不能保证每个首字精确到某一毫秒。最终 MP3 的封装 duration 可含编码 padding；验证的是解码帧数，不要求封装时长与 PCM 文本输出完全相等。

修改分段、暂停、声音或模型后，重跑 synth/build/verify。`build.py` 会先确认每段状态、缓存指纹、文件完整性及哈希；失败时不会用旧段补齐。产物在临时目录完成后替换，manifest 最后写入；消费者必须核对哈希，不能只看文件是否存在。

常用参数：

- 分段：`--max-chars 40 --min-chars 8`；不是固定字数配额。超长英文标识符不拆断。
- 合成：默认 MiniMax，先配置 mmx 和自己的 voice ID。`--provider local` 显式选免费 Qwen（Apple Silicon 为 mlx，其他平台为 qwen），另传本人录音与准确参考文本。Nano 需 `--provider nano`，可用 `--threads 4`。本地串行复用模型和参考编码；MiniMax 逐段在线请求。`--force` 会重做所有段，包括云端请求。
- Qwen：`--reference-text reference.txt`、`--temperature 0.8`、`--max-tokens 800`。Nano 使用其固定上游采样配置，max-tokens 控制音频帧上限；language 根据输入自动处理。
- 拼接：`--gap-hold 600`、`--no-trim`、`--trim-margin 15`。段间暂停在 segments.json/meta/silence_ms 中。默认出 SRT；纯音频用途可显式 `--no-srt`。

本地模型也会漏字、重复、错误读专名；SRT 文件正确不能替代听审。需要字词级时间时，对最终 WAV 与已确认原文运行实际强制对齐模型，再验证异常时间。不要用原稿字符占比分摊音频秒数。

## 单句重试与持久化

以下 seed 控制适用于本地模型；MiniMax CLI 不提供可控 seed，不能用它承诺在线生成可复现。

`run.py` 或 `synth.py` 可添加 `--segment-seed 2:3`，仅第 2 段使用新 seed。相同 ID 与正文会继承保存在 segments.json 的选择，普通续跑仍保留；新增其他段覆盖不会撤销之前的选择。需要恢复默认时显式传 `--clear-segment-seeds`。原句文本变化后不继承旧覆盖；换参考或模型仍会使音频缓存失效并需要重新检查。
````

## File: skills/voice-clone-tts/references/SETUP.md
size: 5389
sha: b49b1a36f6c7bb032a76822415f6f1329a4c830d
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/references/SETUP.md

````text
# 环境与后端

需要 Python 3.12、[uv](https://docs.astral.sh/uv/getting-started/installation/)、FFmpeg。Node/npm 用于安装 skills、网页端和 MiniMax 的 mmx。Windows 建议先使用 WSL2；本项目的实机验证环境是 Apple Silicon macOS，不能据此保证所有 Windows/Linux 驱动组合。

```bash
# macOS 示例；已有依赖可跳过
brew install uv ffmpeg
python3 "$SKILL_DIR/scripts/setup.py"
```

setup 与 run 缺省读取个人偏好；未配置时使用 MiniMax。显式 `--provider local` 时，Apple Silicon 选 Qwen MLX，其他平台选 Qwen PyTorch。CPU 执行 Qwen 可能较慢，先做短样；Nano 必须明确 `--provider nano` 才使用。

setup 为每个后端建立独立 `.creator-env/<provider>/`；使用它打印的 Python 路径执行 run.py。可用 `--env <目录>` 指定位置。它不会修改系统 Python，也不在安装 skill 时自动下载模型。

| 后端 | 默认模型/执行方式 | 输入与使用边界 |
|---|---|---|
| nano | MOSS-TTS-Nano-100M ONNX，CPU 4 线程 | 显式选择，参考 MP3/WAV；无需参考文本。代码和权重固定 revision；实际完整入口含 PyTorch 音频预处理 |
| mlx | Qwen3-TTS 0.6B Base 4bit，MLX | Apple Silicon 本地选项；本机实际合成测试。额外参考转写可走 ICL；无转写使用 speaker embedding |
| qwen | Qwen3-TTS 0.6B Base，官方 PyTorch | 其他平台本地选项；`--device auto/cpu/cuda:0`；未在 CUDA 实机测试。没有强制安装 FlashAttention；有显卡也先测短段 |
| minimax | mmx + speech-2.8-hd | 用户自己的服务账号和音色。默认路线，可能计费；本项目不包含额度 |

切换后端时分别运行 `setup.py --provider mlx/qwen/nano/minimax`，使用对应 Python。Nano 的固定依赖与 Qwen/MLX 的 Transformers 版本不应混装。Nano CPU 在 Linux/Windows 使用 CPU PyTorch wheel，避免自动下载 CUDA 依赖。

本地后端首次推理下载公开模型；MiniMax 不需要本地 TTS 权重。Nano 默认目录为 `~/.cache/creator-pipeline/models/`，可设置 `CREATOR_MODEL_DIR`；HF 缓存与网络行为遵循 huggingface-hub。支持提前下载后使用本地目录；`--model` 自定义模型需自行保证模型类型兼容。模型缓存齐全后可用 `HF_HUB_OFFLINE=1` 检验离线运行。不要把“本地推理”理解为首次安装完全不联网。

Qwen 只能使用 Base 模型做参考音色克隆。CustomVoice 是预置音色，不是相同接口。MLX 量化模型是社区转换，不属于本项目重新训练的模型。

## MiniMax 默认路径

安装和配置 [官方 mmx CLI](https://github.com/MiniMax-AI/cli)，使用你自己的 API 凭据。套餐名称和多模态额度会变化，是否有可用 speech/clone 权限以账号实际情况和官方文档为准；不能把 Coding Plan 的有无当作唯一判断。

已有音色先保存个人偏好，再运行：

```bash
python3 "$SKILL_DIR/scripts/configure.py" --provider minimax --voice YOUR_VOICE_ID
"$PY" "$SKILL_DIR/scripts/run.py" script.md --outdir voiceover-demo
```

个人偏好保存在 `~/.config/creator-pipeline/voice.json`，与安装目录分开，不含 API key。可用 `CREATOR_TTS_CONFIG` 指定位置。后端优先级为命令行、`CREATOR_TTS_PROVIDER`、个人配置、MiniMax 默认；音色优先级为 `--voice`、`MINIMAX_VOICE_ID`、个人配置。

首次登记自己的录音：下面命令会上传录音到 MiniMax。参考文件须为 MP3/M4A/WAV，10–300 秒且不超过 20 MB；建议先截取 10–30 秒干净完整片段。

```bash
python3 "$SKILL_DIR/scripts/clone-minimax.py" my-voice.mp3 MyVoiceName01
python3 "$SKILL_DIR/scripts/configure.py" --provider minimax --voice MyVoiceName01
```

可附加 `--prompt-audio prompt.wav --prompt-text prompt.txt`：prompt 必须不足 8 秒且转写精确匹配，脚本先检查输入再上传。已有试验用 12.05 秒参考与 4.05 秒匹配 prompt 成功登记并实际合成。默认保留原声，不降噪；确有噪声时显式 `--denoise`。`--out receipt.json` 可保存本地登记凭据，不含 API key。

克隆脚本与已检查的 mmx 版本保持一致：优先读取 `~/.mmx/config.json`（或 `MMX_CONFIG_DIR`）中的 API key，无配置 key 时用 `MINIMAX_API_KEY`。一次上传与登记始终使用同一 key、同一 API 域名。区域优先级为 `--region`、`MINIMAX_REGION`、mmx 配置、global；`cn` 对应国内 API。语音合成使用 mmx 自身的认证，请先完成 `mmx auth login`，不要依赖另一个账号的环境变量。套餐名称不证明 speech/clone 权限。

参考限制、prompt 与音色保留策略见 [MiniMax 官方复刻接口](https://platform.minimax.io/docs/api-reference/voice-cloning-clone)。登记后及时合成并检查，不能把音色 ID 当永久可用的保证。

## 无云账号：显式免费本地路线

```bash
python3 "$SKILL_DIR/scripts/setup.py" --provider local
# PY 改为这次 setup 输出的 Python 路径
"$PY" "$SKILL_DIR/scripts/run.py" script.md --provider local \
  --reference my-voice.mp3 --reference-text reference.txt --outdir voiceover-local
```

Qwen 优先提供与参考短段精确对应的文本，启用完整 ICL。想以后都用本地时运行 `configure.py --provider local`，setup 与 run 都会遵循它。缺依赖或额度时给出错误，不静默改用其他供应商。
````

## File: skills/voice-clone-tts/references/VOICE-REVIEW.md
size: 1690
sha: f8b8e365c1a286f2a58e08215d514dd2cb418126
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/references/VOICE-REVIEW.md

```text
# 比较克隆音色

选型目标是让这位用户的配音像本人、读得对、适合其作品，不是证明某供应商普遍最好。

1. 从用户原声选干净、完整的参考短段，所有供应商用同一段。参考转写必须精确对应；Qwen 优先使用音频加转写的 ICL，MiniMax 可增加不足 8 秒的匹配 prompt。分别记录这些条件，不能假称模型接口完全相同。
2. 另选至少三段未参与克隆的原声，覆盖技术专名、口语问句、结尾节奏。保留原声并用同一文案在各后端合成；记录模型与版本。至少再生成一轮，保留全部结果，避免只挑最好的一次。
3. 试听副本仅调恒定增益并限制峰值，避免响度偏好；不改速度、音高，不加压缩。提供隐藏供应商名称的试听入口，记录用户选择与是否已揭晓标签。不能把单人偏好测试写成双盲实验。
4. 检查每段实际读音、漏读、重复、停顿和中英混排。ASR 只辅助排查，原声也要跑同一 ASR 作为对照；不要按 ASR 猜测覆盖原稿。
5. 如用声纹模型，优先与相同文案的未见原声比较，至少两种独立编码器，并报告原声之间的基准。与克隆输入本身的接近程度单独列出。余弦不是校准概率，分数接近不能强行宣称胜负。
6. 用户听感与模型分数不一致时如实保留，两者衡量的内容不同。个人默认以用户确认的声音为准；公共默认说明这只是有限样本选择，保留替代方案。

音频、私人音色 ID、参考路径、账号凭据留在用户项目与个人配置中；公开报告只保留脱敏方法、数字和限制。
```

## File: skills/voice-clone-tts/LICENSE
size: 1084
sha: 3ece782c7c1834395963ff61d3ef444281723f11
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/skills/voice-clone-tts/LICENSE

```text
MIT License

Copyright (c) 2026 NanmiCoder and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: README.md
upstream: https://github.com/nanmicoder/creator-pipeline/blob/main/README.md

````text
<p align="center"><img src="assets/hero.svg" alt="Creator Pipeline — 从一段话，到一部作品" width="100%"></p>

<p align="center">
  <a href="https://github.com/NanmiCoder/creator-pipeline/actions/workflows/check.yml"><img src="https://github.com/NanmiCoder/creator-pipeline/actions/workflows/check.yml/badge.svg" alt="Checks"></a>
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-171714.svg" alt="MIT license"></a>
  <a href="https://github.com/vercel-labs/skills"><img src="https://img.shields.io/badge/install-npx%20skills-E65332.svg" alt="Install with npx skills"></a>
</p>

<p align="center"><b>文案 + 你的声音 → 配音与 SRT → 会自动播放的网页 PPT</b><br>
中文 · <a href="README.en.md">English</a></p>

<p align="center"><a href="https://nanmicoder.github.io/creator-pipeline/"><b>▶ 在线体验有声演示</b></a> · <a href="https://nanmicoder.github.io/creator-pipeline/?review=1&amp;t=0&amp;steps=1">逐拍查看 21 个动作</a></p>

无需安装即可预览：点击页面开始播放，体验 **25 秒 MiniMax 克隆配音 + 真实 SRT 时间轴 + 16:9 连续动画**。在线样片使用作者授权的示例配音。主入口使用 GitHub Pages，也可访问 [Vercel 备用入口](https://creator-pipeline-alpha.vercel.app/)。

想修改或本地演示？完整源码和成品配音已纳入本仓库的 [examples/live-demo](examples/live-demo/README.md)，全新 clone 后即可运行，无需配置 TTS 账号：

```bash
cd examples/live-demo/presentation
npm ci
npm run dev
```

使用 Node.js 22 LTS。修改源码后需要重新构建并发布；GitHub Pages 与 Vercel 的发布方式见 [Demo 维护说明](examples/live-demo/README.md)。

Creator Pipeline 是一组可以配合使用的 AI Agent skills。先用自己的录音克隆配音，得到真实音频时间轴；再让 Agent 把内容做成卡片、图解与连续 MG 场景，让画面跟着声音展开。

默认使用 **MiniMax speech-2.8-hd** 与你自己的克隆音色，需要可用的 MiniMax 凭据和额度。无云账号时可显式选 `--provider local`，用免费的 **Qwen3-TTS**：Apple Silicon 走 MLX，其他平台走官方 PyTorch。**安装的是脚本、模板与制作方法；本地模型在首次使用时下载，个人声音不会随技能分发。**

## 安装两个 skills

```bash
npx skills add NanmiCoder/creator-pipeline \
  --skill voice-clone-tts \
  --skill web-video-presentation
```

安装器会让你选择 Agent 和安装范围。想先看看内容：

```bash
npx skills add NanmiCoder/creator-pipeline --list
```

支持 Vercel [skills CLI](https://github.com/vercel-labs/skills) 的 `skills/<name>/SKILL.md` 目录发现方式，无需另装本项目的 npm 包。已实测 Codex 与 Claude Code 的项目级复制安装。

## 给 Agent 的第一条任务

准备 `script.md` 和一段干净、单人、无配乐的本人录音 `my-voice.mp3`，MiniMax 参考片段建议 10–30 秒（接口接受 10–300 秒），本地模型通常选 3–30 秒。然后发送：

> 使用 voice-clone-tts 和 web-video-presentation。文案在 script.md，参考声音在 my-voice.mp3。先使用我的 MiniMax 音色；没有音色时用这段本人录音在 MiniMax 登记。制作代表性配音样片，检查读音和音色；再生成完整 WAV、MP3、SRT。基于最终时间轴制作 16:9 自动播放网页演示：少放整段文字，用连续图解、卡片状态变化和 MG 解释内容。完成后运行校验，并在浏览器实际播放、检查转场，交付运行方式。

配音脚本需要 Python 3.12、[uv](https://docs.astral.sh/uv/getting-started/installation/) 和 FFmpeg；网页需要 Node.js/npm。skill 内的 `setup.py` 会创建独立 Python 环境。完整命令见 [配音环境](skills/voice-clone-tts/references/SETUP.md)；想直接跑固定样例，见 [first-video](examples/first-video/README.md)。

## 两个 skills，各有清楚的交付

| Skill | 输入 | 输出 |
|---|---|---|
| [voice-clone-tts](skills/voice-clone-tts/SKILL.md) | 文案 + 本人/已授权参考录音 | WAV、MP3、SRT、可验证的 `voiceover.json` |
| [web-video-presentation](skills/web-video-presentation/SKILL.md) | 最终配音、SRT 与内容素材 | Vite + React + TypeScript 16:9 网页演示，可自动播放、点击推进 |

音频先定下来，画面才有可靠的节奏。`voiceover.json` 连接两步：导入时核验音频采样帧、字幕和文件哈希，改稿或缺段后不会继续拼接旧结果。SRT 按实际合成段的采样帧计时，**属于句段级时间轴，不是字级强制对齐**。

网页中的 step 表示口播焦点，scene 表示连续空间。几个句子可以共用一个场景：卡片转成窗口，连线显示关系，游标推进时间；每句口播无需重新换一张文字页。

<p><a href="https://nanmicoder.github.io/creator-pipeline/"><img src="assets/demo.png" alt="点击体验有声演示；截图展示 21 个动作拍中的声轨与字幕对齐" width="100%"></a></p>

<p><img src="assets/preview-stage.png" alt="16:9 舞台预览：口播时间轴、波形与卡片随声音推进" width="100%"></p>

**这版现已成为默认模板**，随 `npx skills add` 一起安装。新建项目首页即可逐拍体验，无需生成配音；自动播放提供明确标注的无声演示。它在六段口播内设计了 **21 个动作拍**，支持逐步播放、回退与重播；从波形拆分、时间标记到卡片关系持续推进。见[默认模板用法](skills/web-video-presentation/templates/STARTER.md)、[真实配音示例](examples/first-video/README.md)和[同配音对照记录](docs/VALIDATION.md)。

<sub>截图来自六句文案的实际运行，保留预览外框。振幅概览取自最终配音，窗口是制作流程示意。已公开的成品配音随 Demo 提供，原始参考录音和私人音色 ID 不包含在仓库中。</sub>

预览、自动播放与验帧都保留清晰的 **16:9 舞台**。验收兼容用户指定或本机可用的 `ego-browser`、`agent-browser` 及其他真实浏览器 skill，不要求安装某个品牌的浏览器。

输出是 **HTML 网页演示，不是 `.pptx`**。安装 skills 不会自动替你生成或上传视频。审核通过后再导出，见下方「导出成片」。

## MiniMax 默认，保留免费本地方案

| 后端 | 适合谁 | 本项目验证状态 |
|---|---|---|
| **Nano · 可选** | 明确希望尝试较轻的 CPU 路线 | MOSS-TTS-Nano 100M ONNX，macOS CPU 实际合成与全流程验证 |
| **Qwen MLX · 本地选项** | Apple Silicon Mac 用户 | Qwen3-TTS 0.6B Base 4bit，实际完成同稿六句配音 |
| **Qwen PyTorch · 本地选项** | CUDA / CPU 用户 | 提供官方模型适配器，尚未做 CUDA 实机验证 |
| **MiniMax · 默认** | 使用在线服务和自己的音色 | 已实际登记音色，并完成三段、两轮同稿对照；用户三段试听均选 MiniMax |

这次默认取自用户对本人声音的三段试听选择。声纹模型对 MiniMax 与 Qwen 的分数接近，并未证明普遍胜负；[对照方法与结果](docs/VALIDATION.md#三家音色对照与-minimax-默认)保留这些限制。缺少账号或音色时会提示配置，不静默切换供应商。

本地模型代码和权重分别遵循上游许可。Nano、Qwen Base 及所选 MLX 权重的公开许可、固定版本与取舍见 [TTS 选型](docs/TTS-BACKENDS.md)。MiniMax 的权限和费用以账号实际额度为准，不按套餐名字推断。

“免费本地”仍然需要首次联网下载、磁盘与运行内存。历史 Nano 短样本在这台 Mac 上进程峰值约 **3.5–3.9 GiB**，不能据此承诺所有低配电脑都可用。完整 Nano Python 入口仍用到 PyTorch 音频预处理，ONNX 并不意味着整个依赖链都没有 PyTorch。

## 做过什么验证

- **真实配音与交接**：同一份六句文案分别通过 Nano 和 Qwen MLX 生成，再由实际 WAV/SRT 驱动网页演示。
- **内容核对**：Nano 首轮出现局部 ASR 转写偏差，保留失败记录并只重试对应句子；不把“能播放”当作“读对了”。
- **故障恢复**：改一段、换参考、损坏缓存、真实进程中断、搬迁目录，都做过独立前向测试；导入器会拒绝损坏或过期清单。
- **网页质量**：真实 TypeScript 检查、时间轴校验、构建与浏览器播放；文案密度、构图和动作含义仍需要视觉审查。

数字、范围、失败与修复记录见 [验证报告](docs/VALIDATION.md)。目前有单人三段试听选择与两轮声纹辅助对照，没有跨机器速度基准、受控双盲研究或大样本返工率结论。

## 导出成片

画面审核没问题后，在预览页右上角点 **导出**，选 1K / 2K / 4K，下载 MP4。按同一时间轴逐帧生成 16:9 舞台与配音，进度条、角标和外框不进成片，无需分享标签页。导出耗时取决于设备和画面复杂度；处理慢不会通过跳帧来追赶。请保持页面打开。

<p><img src="assets/export-modal.png" alt="导出弹窗：选择 1K、2K 或 4K 分辨率" width="100%"></p>

| 选项 | 分辨率 |
|---|---|
| 1K | 1920×1080 |
| 2K | 2560×1440 |
| 4K | 3840×2160 |

音轨来自导入的配音文件，不依赖系统回环。旧浏览器或画面包含不支持的实时媒体时，仍可用 OBS 等录屏软件框选舞台，见 [导出说明](skills/web-video-presentation/references/RECORDING.md)。

## 开发与贡献

```text
skills/
  voice-clone-tts/          # 本地/云配音适配器、缓存、SRT 和验证
  web-video-presentation/   # 场景制作方法、主题、网页运行时与导入器
examples/first-video/       # 不含私人声音的可复现端到端样例
examples/live-demo/         # 线上有声 Demo 的源码、计划、配音、字幕与部署入口
tests/                     # 无需模型或云账号的故障与交接测试
docs/                      # 模型取舍、实测结果与验证边界
```

```bash
python3 -m unittest discover -s tests -v
python3 scripts/check-package.py
```

欢迎带着复现文案、后端版本和脱敏日志提交 issue；不要附上密钥、未授权的录音或模型权重。对于新后端，优先补齐输入契约、许可、真实短样本和失败恢复证据。

## 致谢与许可

项目代码使用 [MIT](LICENSE)。网页技能基于 [ConardLi/garden-skills](https://github.com/ConardLi/garden-skills) 的 Web Video Presentation 持续改进，保留原许可；配音运行依赖 OpenMOSS、Qwen、MLX Audio 等开源项目。第三方代码、模型与字体不因被本项目使用而变更许可，见 [THIRD_PARTY_NOTICES](THIRD_PARTY_NOTICES.md)。
````
