# audio-subtitle-roughcut

Adopt this skill: https://proskills.md/skills/other/njrhts2kvv-star-fredtalk-skills-audio-subtitle-roughcut

Page: https://proskills.md/skills/other/njrhts2kvv-star-fredtalk-skills-audio-subtitle-roughcut
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/audio-subtitle-roughcut/SKILL.md
size: 12167
sha: f1952f0e7bfa692165687357cd095b2329f59685
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/SKILL.md

````text
---
name: audio-subtitle-roughcut
description: 原音经自然人声处理和1.1倍速后调用千问Audio 3.1获得词级字幕，结合逐字稿纠错、语义分段与口误粗剪，最后+8dB并交付可手调审片台和同步WAV/SRT；也可续做已有音频与字幕。用户要求原音处理、字幕识别、删除重说或按稿校正字幕时使用。
---

# 音频和字幕粗剪

公开版不附带作者的自然人声运行环境与录音。原音流程先配置并验证使用者自己的预处理器，再按本节顺序处理；已有人声音频和字幕可直接使用审片台。API上传与付费只依据当前使用者的授权，不能继承作者过去的授权。

输入是实际录音及可用的本期逐字稿；已有字幕可直接续做。目标是保留Fred实际表达，只删失败重说、口误起句和明确重复，校正识别错误，交付可试听、可调整的完整结果。不是重新写稿或逐字照稿重建录音。

## 原音入口

只有原音频时，严格按 **原音 → 自然人声处理 → 1.1倍速 → 字幕识别 → 粗剪 → +8dB** 执行。按 [references/original-audio-api.md](references/original-audio-api.md) 用 `scripts/qwen_asr.py` 对已自然处理且已加速的音频调用 `qwen-audio-3.1-asr-flash-filetrans`。使用者明确授权当前录音上传与API付费调用后，私人Key仅从本机0700目录/0600文件读取，不写进Skill、项目、日志或同步包。不默认打开剪映、不用Paraformer；任务续查不重复提交。稿件提取热词与短上下文，保留原始ASR和词/子词时间，识别结果仍需后续校正。

自然人声沿用项目本地 `audio-master-natural.mjs --no-deepfilter`。1.1倍速在识别前应用，+8dB在粗剪后应用，均只做一次；ASR、cuts和字幕共享加速后的源坐标，导出使用 `--speed 1 --gain-db 8 --trim-start 0`，片头剪切写入cuts。保护限幅并报告实际响度，不因自然链归一化而省略+8dB。已处理版和字幕单改不重复叠加。详细顺序、边界与API命令见上述参考。

## 声音证据与整条复查

新处理、补录替换和局部返修都按 [音频证据、残留与响度](references/audio-evidence-and-loudness.md) 执行：**识别多字只改字幕；句内短词不能凭ASR重复或波形二峰直接启用剪切**。用户确认声音正常时，检查旧导出是否已误剪并恢复，保留手改字幕。真实重说删后复核字头/尾音和残留起音，词时码不直接当下刀位置。

整条最终音轨检查综合指标和连续局部响度；正文、补录、插入旁白按职责比较，并检查插入内部首句突响。`verify_delivery.py`会生成只读响度轨迹及分段/字幕窗口摘要，阈值只提示候选，不自动剪音、归一化或证明听感。纯配音与含SFX的动画混音先核准确源；响度匹配只调当前不合适区间，不重复已完成的处理。

## 判断边界

- 保留“啊、嗯”、笑声、自然停顿、自行增加的评价和措辞。未要求时不批量删静音、去语气词。
- 先说错后重说：删前面失败部分，保留后面完整版本。检查句内残尾，如“工作场景Pro套 / Pro套餐…”，不能只找重复整句。
- 音频剪切与字幕纠错分开。DevDay→Update、Jev→Harness是本期识别错误，不是删对应音频的理由；专名用稿件、可信材料或Fred明确纠正核对，不猜不确定词。
- SRT通常只有句级时间。句内切点不能冒充逐字精度或已听审；用音频/波形定位，无法听审时说明估算，给接缝试听和微调。不能反复保留用户已经明确指出的重复。
- 跨句断字两边一起修：上一句尾“但”接回“是…”成为“但是”，同时维护字幕边界与音频切点。只改字不算剪掉重复。
- 按实际口播和稿件句意断句，别拆开200/美金、Claude/Code、执行能力和/电脑操作；合并沿用首尾时码，不跨候选切点合并失败段与正确段。
- 长字幕检查覆盖整份最终SRT，不只看用户截图那句。特别长的句子在合适语义位置拆成前后两条、按口播依次显示；不是只在同一条里换行，也不是缩字号。完整句意不要求同屏放完，合并后必须重新检查长度；具体方法见工作流的“长字幕与句内漏检”。
- 口误检查必须细到一句里的几个字：错词后立即重说、短词重复、半截起句、句尾残字和跨cue断字都检查，不只找整句重录。用户指出同类漏检后检查全文同类问题；字幕识别错只改文字，实际失败重说才剪声音，不把临场改词强行改回稿件。
- 用户说“字幕太长”时仅处理分段和时间，不擅自调整音频接缝。字幕单改复用原音频并核对hash，保留既有剪切、语速、音量和旧交付；新字幕、前端与下载必须同版。
- 不覆盖原音、剪映原SRT、用户手动文字/剪切选择和旧交付版。
- 展示字幕按语义分段后去掉普通逗号，尤其“一、第二、第三”后不留逗号；保留原始识别证据、小数、百分比、型号等有意义符号。数字按原稿/用户确认写法，如“3件事情”“10多轮”“两小时”，序号“第一、第二、第三”保留，不机械全局替换汉字数字。
- 用户明确要求按原逐字稿校正时，修复指定范围的错词、单位、专名和重复文字，不把全文临场表达强行改回稿件；声音是否需剪单独判断。比较表区分原始识别与当前校正，已修正文不继续标待核对；语气词漏识别不能凭空补时间。

## 停顿、吞咽声与局部返修

- 检查整段实际音频，不能只看SRT条目之间的空白。句级字幕可能覆盖句内停顿、吞咽、口腔声和重说后的过渡；结合波形与前后句意定位。
- Fred可接受约0.5秒的自然停顿，这是参考尺度，不是逐个压到0.5秒的硬阈值。句内或同一意思之间明显拖长时收紧；长段、章节切换和独立演示可稍长，保留表达节奏。低电平不等于没有语音，不能按单一阈值批量删除。
- 每次删重说后复查接点及其前后：不能只删重复字，留下旁边吞咽声或长空隙。先保住前句尾音和后句起音，再缩短无内容的过渡。
- 用户说“其他都好”时，只改指定问题及其直接关联的字幕/时序；相对上一版核对未修改片段的PCM。全篇同类检查不等于重新清洗全音轨。
- 原音、语速、音量已处理过且本次只要剪辑时使用`--passthrough`：保留PCM采样，不变速、不增益、不限幅、不自动裁片头。需要剪掉的片头写入cuts.json。字幕单改继续复用原WAV并验证hash。

## 本期复查与导出检查

- 普通处理导出同时测采样峰值、真峰值、综合响度和覆盖全片的局部响度变化；超标时有限次调整限幅，仍失败则不发布。公共脚本已加入过采样保护和独立真峰值复测；passthrough保持PCM。具体参数与证据见[工作流](references/workflow.md#真峰值与对比交付)。
- 句内删词可通过`cutId + cutRange + removeInfix`绑定声音与字幕，恢复/撤销剪切时联动恢复字词，导出同一cue只显示一次；手调切点后重核删词范围。配置与适用边界见[句内联动](references/workflow.md#句内剪切与字幕联动)。
- 词级ASR切点仍须核对字头/尾音，不凭新识别里的重复词自动剪音。重处理原音迁移旧剪点前，分布检查新旧时间偏移与漂移，方法见[时间对齐](references/workflow.md#词时间与旧剪点迁移)。
- 新旧对照按同一句切换并提供同响度试听，分别报告文字、分段、时间和声音变化；沿用旧分段时直接说明，保留实际版本身份。

## 执行

找本期唯一目录、最新稿件、录音与SRT，核对时长/格式/字幕覆盖。已有审片台时续做，不重建。公共前端已固定在assets/review-app，后续只换输入；可用主视频Skill的[公共模板启动器](../fred-remotion-output/references/segment-review.md#公共模板默认)同时打开音频/关键帧/视频模块。公开版可用合成测试素材验证联动模块，不分发作者个人录音或历史审片数据。首次创建：

```bash
python3 scripts/init_review.py --episode "/absolute/episode" --audio "/absolute/audio.wav" --subtitles "/absolute/subtitles.srt" --script "/absolute/script.md" --title "本期标题"
```

命令从本仓库的 `skills/audio-subtitle-roughcut/` 执行。阅读 [references/workflow.md](references/workflow.md)，把本期候选、词语、边界、分句写入本期 `03_制作过程/audio-review/` 的配置，模板不携带第107期切点/名词。

```bash
python3 scripts/deliver.py --review "/absolute/episode/03_制作过程/audio-review" --version v1
python3 "/absolute/episode/03_制作过程/audio-review/server.py" --port 8107
```

端口冲突用空闲端口，不杀其他服务。绑定127.0.0.1，HTTP准备好再发URL，持久运行用独立进程。原音API入口仅上传用户交付本任务处理的录音，不上传无关素材；已有字幕不无故重复收费转写。与用户沟通简短直接，不为流程新增审批。

## 审片和交付

灰色删除、待试听、原片段/接缝试听、波形与数字边界、启用/恢复、手动剪切、撤销/重做、本地保存、逐句文字编辑必须可用。每行编辑和剪切旁提供“恢复”：一次恢复所有覆盖该句的启用剪切，跨句剪切只恢复当前句，其他句删除及其cutId字幕联动保留。已完全删除的范围不重复新增剪切；恢复后刷新字幕，保留用户文字覆盖，支持撤销/重做与保存。完整成片页读取真实导出文件：完整播放、大字当前句、全部字幕高亮/跟随、点击跳转、倍速、下载、版本信息。局部PCM返修显示继承的既有处理参数，不把本轮passthrough的gainDb=0当作原音没有增益。未导出的修改不冒充最新成片。

待核对的短词重说须列出准确句子、时间、当前是否保留及不确定点；不能以“技术校验通过”宣称全文口误已清零。能继续用本地对齐/波形核验时先做，不把检查工作直接推回用户。

用户给出方向后继续完整导出；要求“直接给最终音频字幕”时交付本期 `02_最终输出/` WAV/SRT并放前端。未处理项须说明，“完整文件”不等于“所有口误已经清除”。

原音新入口先加速再识别，粗剪后仅加增益：

```bash
python3 scripts/deliver.py --review "/absolute/review" --version v1 --speed 1 --trim-start 0 --gain-db 8
```

此处片头空隙由cuts.json显式删除。以下旧命令仅适用于确认尚未加速的已有音频/SRT路径，不用于已按新入口加速的源；用户当次参数优先：

```bash
python3 scripts/deliver.py --review "/absolute/review" --version v2 --speed 1.1 --trim-start 1 --gain-db 8
```

已处理录音的只剪切导出：

```bash
python3 scripts/deliver.py --review "/absolute/review" --version v2 --passthrough
```

`--speed 1 --gain-db 0`本身仍走常规限幅链，不能当作透明保留原音；只剪切请用`--passthrough`，不与非零增益、变速或额外片头裁切组合。

这些是相对原音粗剪结果的总参数，不在已处理版上重复叠加。默认1.1倍速、+8dB；片头按实际空隙去掉，不机械删1秒。脚本用波形阈值提出片头切点，须试听确认，必要时用--trim-start覆盖；其秒数属于加速后的时间。加速保音高、字幕除倍率；裁片头字幕前移；增益不改时间。测峰值，可能超满幅时保护限幅、补偿延迟并报告实际平均变化，不声称限幅后每个样本仍精确增益。

运行 `scripts/verify_delivery.py --review /absolute/review`，再做实际浏览器的播放/寻址/高亮/编辑保存/撤销/下载和桌面手机检查。技术验证、听审和用户认可分开记录。无法接收音频时不假称听过。
````

## File: skills/audio-subtitle-roughcut/scripts/audio_qc.py
size: 3015
sha: 7d02ae6357fa4bd478ba7ab25c5c193046417e13
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/audio_qc.py

```text
"""Measured loudness and bounded true-peak correction for processed exports."""
import array
import json
import math
from pathlib import Path
import re
import subprocess
import wave

def measure(path):
    result = subprocess.run(['ffmpeg', '-nostdin', '-hide_banner', '-i', str(path),
        '-af', 'loudnorm=I=-14:TP=-1:LRA=7:print_format=json', '-f', 'null', '-'],
        capture_output=True, text=True, check=True)
    matches = re.findall(r'\{[^{}]*\}', result.stderr)
    data = next((json.loads(s) for s in reversed(matches) if 'input_tp' in s), None)
    if data is None:
        raise ValueError('No loudness measurement returned')
    def value(key):
        v = float(data[key])
        if math.isnan(v) or v == math.inf:
            raise ValueError('Invalid loudness measurement')
        return None if v == -math.inf else v
    with wave.open(str(path)) as w:
        if w.getsampwidth() != 2:
            raise ValueError('QC expects PCM16 WAV')
        samples = array.array('h', w.readframes(w.getnframes()))
    peak = max(map(abs, samples), default=0) / 32768
    return dict(integratedLufs=value('input_i'), truePeakDbtp=value('input_tp'),
                loudnessRangeLu=value('input_lra'), samplePeakDbfs=20*math.log10(peak) if peak else None)

def render_processed(source, target, speed, trim, gain, ceiling=-1.0):
    """Retry only local limiting; keep gain/speed fixed and fail if TP remains unsafe."""
    with wave.open(str(source)) as w:
        rate, frames = w.getframerate(), w.getnframes()
    ceiling_work = ceiling - .5
    attempts = []
    for attempt in range(3):
        filters = []
        if speed != 1:
            filters.append(f'atempo={speed}')
        if trim:
            filters.append(f'atrim=start={trim}')
        filters += ['asetpts=PTS-STARTPTS', f'volume={gain}dB', 'aresample=192000',
                    f'alimiter=limit={10**(ceiling_work/20)}:level=false:latency=true', f'aresample={rate}']
        if speed == 1:
            # No-op atempo can change frame count. Preserve the exact unity-speed clock.
            expected = frames - round(trim*rate)
            filters += [f'apad=whole_len={expected}', f'atrim=end_sample={expected}']
        subprocess.run(['ffmpeg', '-nostdin', '-v', 'error', '-y', '-i', str(source),
                        '-af', ','.join(filters), '-c:a', 'pcm_s16le', str(target)], check=True)
        qc = measure(target)
        passed = qc['truePeakDbtp'] is None or qc['truePeakDbtp'] <= ceiling + .05
        attempts.append(dict(limiterCeilingDb=ceiling_work, measurement=qc, passed=passed))
        if passed:
            return dict(passed=True, targetDbtp=ceiling, toleranceDb=.05,
                        limiterCeilingDb=ceiling_work, oversampleRate=192000,
                        latencyCompensated=True, filters=filters, attempts=attempts), qc
        ceiling_work -= max(.2, qc['truePeakDbtp']-ceiling+.2)
    raise ValueError('True peak remains above target after 3 local attempts; delivery not published')
```

## File: skills/audio-subtitle-roughcut/scripts/deliver.py
size: 6193
sha: 6206c3f459ca804a9d83a99c7e3db07fabd1278d
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/deliver.py

```text
import argparse
import hashlib
import importlib.util
import json
import math
import os
import re
import shutil
import subprocess
import wave
from pathlib import Path
from audio_qc import measure, render_processed

def load_server(root):
    spec = importlib.util.spec_from_file_location('review_server', root / 'server.py')
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

def hash_file(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()

def main():
    p = argparse.ArgumentParser()
    p.add_argument('--review', required=True)
    p.add_argument('--version', required=True)
    p.add_argument('--speed', type=float, help='Default 1.1; 1 with --passthrough')
    p.add_argument('--trim-start', type=float, help='Seconds in accelerated rough cut; otherwise detect initial silence')
    p.add_argument('--gain-db', type=float, help='Default 8; 0 with --passthrough')
    p.add_argument('--passthrough', action='store_true', help='Only concatenate selected PCM spans; no speed, gain, limiter or automatic head trim')
    args = p.parse_args()
    if args.passthrough:
        if args.speed not in (None, 1) or args.gain_db not in (None, 0) or args.trim_start not in (None, 0):
            p.error('--passthrough requires speed 1, gain 0, trim 0; put head cuts in cuts.json')
        args.speed, args.gain_db, args.trim_start = 1, 0, 0
    else:
        args.speed = 1.1 if args.speed is None else args.speed
        args.gain_db = 8 if args.gain_db is None else args.gain_db
    if not re.fullmatch(r'[A-Za-z0-9_-]+', args.version) or not .5 <= args.speed <= 2 or not math.isfinite(args.gain_db):
        p.error('Invalid processing parameters')
    root = Path(args.review).resolve()
    server = load_server(root)
    cuts = server.validate(json.loads(server.STATE.read_text()))
    result = server.export(cuts)
    base = Path(result['path'])
    output = server.EPISODE / '02_最终输出'
    output.mkdir(exist_ok=True)
    stem = server.CONFIG['filenameStem']
    audio = output / f'{stem}-final-audio-{args.version}.wav'
    subtitle = output / f'{stem}-final-subtitles-{args.version}.srt'
    if audio.exists() or subtitle.exists():
        p.error('Version exists; choose a new version')
    # Conservative waveform threshold proposes only the initial silent span.
    with wave.open(str(base / 'review-cut.wav')) as w:
        samples = server.array.array('h', w.readframes(w.getnframes()))
        channels, rate = w.getnchannels(), w.getframerate()
    onset = next((i // channels / rate for i in range(0, len(samples), channels) if max(abs(v) for v in samples[i:i+channels]) > 32768 * .01), 0)
    trim = args.trim_start if args.trim_start is not None else max(0, onset - .05) / args.speed
    if trim < 0 or trim >= result['duration'] / args.speed:
        p.error('Trim outside rough cut')
    loudness_before = measure(base / 'review-cut.wav')
    true_peak_check = None
    if args.passthrough:
        shutil.copyfile(base / 'review-cut.wav', audio)
    else:
        true_peak_check, _ = render_processed(base / 'review-cut.wav', audio, args.speed, trim, args.gain_db)
    loudness_after = measure(audio)
    with wave.open(str(audio)) as w:
        duration = w.getnframes() / w.getframerate()
        frames = w.getnframes()
    lines, mapped = [], []
    for block in re.split(r'\n\s*\n', (base / 'review-cut.srt').read_text().strip()):
        values = block.splitlines()
        a, b = values[1].split(' --> ')
        a, b = max(0, server.seconds(a) / args.speed - trim), min(duration, server.seconds(b) / args.speed - trim)
        if b - a < .015:
            continue
        text = '\n'.join(values[2:])
        mapped.append(dict(start=a, end=b, text=text))
        lines.append(f'{len(lines)+1}\n{server.timestamp(a)} --> {server.timestamp(b)}\n{text}\n')
    subtitle.write_text('\n'.join(lines))
    measurements = subprocess.run(['ffmpeg', '-nostdin', '-i', str(audio), '-af', 'volumedetect', '-f', 'null', '-'], capture_output=True, text=True, check=True).stderr
    before = subprocess.run(['ffmpeg', '-nostdin', '-i', str(base / 'review-cut.wav'), '-af', f'atempo={args.speed},atrim=start={trim},volumedetect', '-f', 'null', '-'], capture_output=True, text=True, check=True).stderr
    manifest = dict(version=args.version, filenameStem=stem, speed=args.speed, trimStart=trim, trimMode='manual' if args.trim_start is not None else 'threshold-proposal-needs-audition', gainDb=args.gain_db, passthrough=args.passthrough, peakLimitDb=None if args.passthrough else true_peak_check['limiterCeilingDb'], duration=duration, frames=frames, audioPath=os.path.relpath(audio, root), subtitlePath=os.path.relpath(subtitle, root), audioHash=hash_file(audio), subtitleHash=hash_file(subtitle), baseExport=os.path.relpath(base, root), expectedCues=mapped, subtitleWarnings=result['subtitleWarnings'], measurementLines=[line.strip() for line in measurements.splitlines() if 'mean_volume:' in line or 'max_volume:' in line], listeningReviewed=False)
    means = [re.search(r'mean_volume: ([-\d.]+) dB', value) for value in (before, measurements)]
    manifest['loudnessBefore'] = loudness_before
    manifest['loudnessAfter'] = loudness_after
    manifest['truePeakCheck'] = true_peak_check
    manifest['preprocessingSpeed'] = server.CONFIG.get('preprocessing', {}).get('speedApplied')
    manifest['actualLoudnessChangeLu'] = round(loudness_after['integratedLufs'] - loudness_before['integratedLufs'], 2) if all(v['integratedLufs'] is not None for v in (loudness_before, loudness_after)) else None
    manifest['actualMeanGainDb'] = round(float(means[1][1]) - float(means[0][1]), 2) if all(means) else None
    base_manifest = dict(manifest, baseExport='.', audioPath=os.path.relpath(audio, base), subtitlePath=os.path.relpath(subtitle, base))
    (base / 'delivery.json').write_text(json.dumps(base_manifest, ensure_ascii=False, indent=2))
    temp = root / 'final-delivery.tmp'
    temp.write_text(json.dumps(manifest, ensure_ascii=False, indent=2))
    temp.replace(root / 'final-delivery.json')
    print(json.dumps(manifest, ensure_ascii=False, indent=2))

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

## File: skills/audio-subtitle-roughcut/scripts/init_review.py
size: 2675
sha: a85a5a925a8d2f8483a2864dcbca3d63ff6e95a4
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/init_review.py

```text
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import wave
from pathlib import Path

def digest(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()

def main():
    p = argparse.ArgumentParser()
    for name in ('episode', 'audio', 'subtitles', 'script', 'title'):
        p.add_argument('--' + name, required=True)
    p.add_argument('--copy-inputs', action='store_true', help='Copy supplied inputs into the review folder for portability')
    p.add_argument('--media-review-url')
    args = p.parse_args()
    episode = Path(args.episode).resolve()
    root = episode / '03_制作过程/audio-review'
    if root.exists():
        p.error('Review already exists; resume it rather than overwrite')
    inputs = {key: Path(getattr(args, key)).resolve() for key in ('audio', 'subtitles', 'script')}
    for path in inputs.values():
        if not path.is_file():
            p.error(f'Missing input: {path}')
    shutil.copytree(Path(__file__).resolve().parent.parent / 'assets/review-app', root)
    if args.copy_inputs:
        originals = inputs.copy()
        folder = root / 'inputs'
        folder.mkdir()
        for key, file in originals.items():
            inputs[key] = folder / (key + file.suffix)
            shutil.copyfile(file, inputs[key])
    source = inputs['audio']
    try:
        with wave.open(str(source)) as w:
            normalized = (w.getframerate(), w.getnchannels(), w.getsampwidth(), w.getcomptype()) == (48000, 2, 2, 'NONE')
    except (wave.Error, EOFError):
        normalized = False
    if not normalized:
        source = root / 'source-normalized.wav'
        subprocess.run(['ffmpeg', '-nostdin', '-v', 'error', '-i', str(inputs['audio']), '-ar', '48000', '-ac', '2', '-c:a', 'pcm_s16le', str(source)], check=True)
    rel = lambda path: os.path.relpath(path, root)
    stem = re.sub(r'[^\w-]+', '-', episode.name).strip('-') or 'episode'
    config = dict(episode=rel(episode), episodeKey=episode.name, title=args.title, filenameStem=stem, sourceAudio=rel(source), sourceSubtitles=rel(inputs['subtitles']), script=rel(inputs['script']), originalInputs={rel(path): digest(path) for path in inputs.values()}, mediaReviewUrl=args.media_review_url)
    (root / 'project.json').write_text(json.dumps(config, ensure_ascii=False, indent=2))
    for name in ('cuts', 'subtitle-corrections', 'subtitle-boundaries', 'subtitle-sentences'):
        (root / (name + '.json')).write_text('[]')
    for name in ('subtitle-edits', 'subtitle-sentence-edits', 'subtitle-joins'):
        (root / (name + '.json')).write_text('{}')
    print(root)

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

## File: skills/audio-subtitle-roughcut/scripts/loudness_profile.py
size: 8171
sha: 662c38e6fff7680fa6b7c88c3a6a1b4f4ed5c21f
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/loudness_profile.py

```text
"""Read-only EBU R128 timeline and segment/cue comparisons; never edit audio or cuts."""
import argparse
import hashlib
import json
import math
from pathlib import Path
import re
import statistics
import subprocess
import wave
from audio_qc import measure

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

def valid_loudness(value):
    return value if value is not None and math.isfinite(value) and value>-70 else None

def validate_segments(segments,duration):
    result=[]
    for i,entry in enumerate(segments):
        a,b=float(entry['start']),float(entry['end'])
        if not math.isfinite(a) or not math.isfinite(b) or not 0<=a<b<=duration+.001:
            raise ValueError('Invalid segment range')
        result.append(dict(entry,id=entry.get('id',str(i+1)),role=entry.get('role','narration'),start=a,end=min(b,duration)))
    result.sort(key=lambda x:x['start'])
    if any(left['end']>right['start']+.001 for left,right in zip(result,result[1:])):
        raise ValueError('Loudness role segments must not overlap; use cues separately')
    return result

def segments_for_delivery(data):
    if data.get('loudnessSegments') is not None:return data['loudnessSegments']
    spans=[]
    for key,role in [('transition','insert'),('replacement','replacement')]:
        entry=data.get(key) or {}; a=entry.get('start',entry.get('outputStart')); b=entry.get('end',entry.get('outputEnd'))
        if a is not None and b is not None and a<b:spans.append((float(a),float(b),role))
    duration=float(data['duration']);edges=sorted({0.,duration}|{t for a,b,_ in spans for t in (a,b) if 0<t<duration})
    result=[]
    for a,b in zip(edges,edges[1:]):
        roles=[role for left,right,role in spans if left<=(a+b)/2<right]
        role='insert' if 'insert' in roles else 'replacement' if roles else 'narration'
        result.append(dict(id=str(len(result)+1),start=a,end=b,role=role))
    return result

def collect_timeline(path,duration):
    run=subprocess.run(['ffmpeg','-nostdin','-hide_banner','-i',str(path),'-map','0:a:0',
        '-af','ebur128=metadata=1,ametadata=print','-f','null','-'],capture_output=True,text=True,check=True)
    points=[];current=None
    for line in run.stderr.splitlines():
        match=re.search(r'\bframe:\d+\s+pts:\S+\s+pts_time:([\d.eE+-]+)',line)
        if match:
            if current is not None:points.append(current)
            current={'end':min(duration,float(match[1])+.1)}
        match=re.search(r'lavfi\.r128\.([MS])=(-?[\d.eE+]+)',line)
        if match and current is not None:
            key='momentaryLufs' if match[1]=='M' else 'shortTermLufs'
            current[key]=valid_loudness(float(match[2]))
    if current is not None:points.append(current)
    for p in points:
        for key,window in [('momentaryLufs',.4),('shortTermLufs',3.)]:
            if p['end']<window-1e-6:p[key]=None
            else:p.setdefault(key,None)
        p['end']=round(p['end'],6)
    if not points:raise ValueError('No R128 timeline returned')
    return points

def range_summary(points,start,end):
    out={}
    for key,prefix,window in [('momentaryLufs','momentary',.4),('shortTermLufs','shortTerm',3.)]:
        # Only use complete windows inside the range; nearby narration must not leak into an insert/cue.
        values=[p[key] for p in points if p[key] is not None and p['end']-window>=start-1e-6 and p['end']<=end+1e-6]
        out[prefix+'Samples']=len(values)
        out[prefix+'MedianLufs']=round(statistics.median(values),3) if values else None
        out[prefix+'MinLufs']=min(values) if values else None
        out[prefix+'MaxLufs']=max(values) if values else None
    return out

def build_profile(path,segments=None,cues=None,threshold_lu=2.):
    path=Path(path).resolve()
    with wave.open(str(path)) as w:
        duration=w.getnframes()/w.getframerate();frames=w.getnframes()
        if w.getsampwidth()!=2:raise ValueError('Profile expects normalized PCM16 WAV')
    if not math.isfinite(threshold_lu) or threshold_lu<=0:raise ValueError('Threshold must be positive')
    segments=validate_segments(segments if segments is not None else [dict(start=0,end=duration,role='narration')],duration)
    cues=cues or []
    for cue in cues:
        if not 0<=float(cue['start'])<float(cue['end'])<=duration+.001:raise ValueError('Invalid cue range')
    before=digest(path);points=collect_timeline(path,duration)
    summaries=[dict(s,**range_summary(points,s['start'],s['end'])) for s in segments]
    reference_values=[p['momentaryLufs'] for p in points if p['momentaryLufs'] is not None and
        any(s['role']=='narration' and s['start']<=p['end']-.4+1e-6 and p['end']<=s['end']+1e-6 for s in segments)]
    reference=statistics.median(reference_values) if reference_values else None
    for s in summaries:
        s['momentaryDeltaFromNarrationLu']=round(s['momentaryMedianLufs']-reference,3) if reference is not None and s['momentaryMedianLufs'] is not None else None
    candidates=[]
    for p in points:
        if reference is None or p['momentaryLufs'] is None:continue
        delta=p['momentaryLufs']-reference
        if abs(delta)<threshold_lu:continue
        a,b=max(0,p['end']-.4),p['end'];direction='louder' if delta>0 else 'quieter'
        if candidates and candidates[-1]['direction']==direction and a<=candidates[-1]['end']+.001:
            c=candidates[-1];c['end']=b;c['maxAbsDeltaLu']=max(c['maxAbsDeltaLu'],round(abs(delta),3))
        else:candidates.append(dict(start=round(a,6),end=b,direction=direction,maxAbsDeltaLu=round(abs(delta),3),needsContextReview=True))
    integrated=measure(path)
    if digest(path)!=before:raise ValueError('Audio changed during read-only analysis')
    return dict(schemaVersion=1,analysisOnly=True,audio=dict(path=str(path),sha256=before,duration=duration,frames=frames),
        integrated=integrated,reference=dict(role='narration',momentaryMedianLufs=round(reference,3) if reference is not None else None,sampleCount=len(reference_values)),
        windows=dict(momentarySeconds=.4,shortTermSeconds=3.,stepSeconds=.1),
        coverage=dict(decodedDurationSeconds=duration,lastTimelineEndSeconds=points[-1]['end'],unreportedTailSeconds=round(max(0,duration-points[-1]['end']),6),tailCoveredByWholeFilePeakAndIntegrated=True),
        timeline=points,segments=summaries,
        cues=[dict(c,**range_summary(points,float(c['start']),float(c['end']))) for c in cues],candidates=candidates,
        thresholdLu=threshold_lu,listeningReviewed=False,limitations=[
            'Candidates are prompts for contextual review, not failure labels or gain/cut commands.',
            'Silence/below-gate and incomplete windows are null, not zero LUFS.',
            'Short cues may lack 400ms/3s windows; momentary, short-term and integrated values are distinct.',
            'Loudness does not classify speech, repeats, mouth noise, SFX or source identity.'])

def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--audio',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
    p.add_argument('--segments',type=Path,help='JSON list of non-overlapping role ranges in final audio seconds')
    p.add_argument('--cues',type=Path,help='JSON list of subtitle cue ranges; may be shorter than analysis windows')
    p.add_argument('--threshold-lu',type=float,default=2.,help='Review-candidate threshold, not an automatic normalization target')
    args=p.parse_args()
    if args.output.exists():p.error('Output exists; choose another report path')
    result=build_profile(args.audio,json.loads(args.segments.read_text()) if args.segments else None,json.loads(args.cues.read_text()) if args.cues else None,args.threshold_lu)
    args.output.parent.mkdir(parents=True,exist_ok=True);args.output.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
    print(json.dumps(dict(output=str(args.output.resolve()),duration=result['audio']['duration'],candidateCount=len(result['candidates']),analysisOnly=True)))

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

## File: skills/audio-subtitle-roughcut/scripts/package_template.py
size: 6558
sha: 5e03c7d7ad2a448e82e1efc697f2ffa0b6866610
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/package_template.py

```text
#!/usr/bin/env python3
"""Package reusable review code and optionally an explicitly authorized example."""
import argparse
import hashlib
import json
import re
import zipfile
from pathlib import Path

def package(output, example=None):
    skills = Path(__file__).resolve().parents[2]
    audio = skills / 'audio-subtitle-roughcut'
    media = skills / 'fred-remotion-output'
    files = []
    for folder in [audio / 'assets/review-app', media / 'templates/review-app']:
        files.extend(p for p in folder.rglob('*') if p.is_file() and p.suffix in {'.py', '.mjs', '.js', '.html', '.css'} and '__pycache__' not in p.parts)
    for folder, names in [(audio, ['init_review.py', 'deliver.py', 'verify_delivery.py', 'audio_qc.py', 'loudness_profile.py', 'package_template.py']),
                          (media, ['init_review_app.py', 'prepare_review_segments.py', 'serve_review_app.py', 'build_segment_review.py'])]:
        files.extend(folder / 'scripts' / name for name in names)
    entries = {}
    for file in files:
        payload = file.read_bytes()
        patterns = [rb'/(?:Users|home)/[A-Za-z0-9._-]+/', rb'\.codex/(?:archived_)?sessions/', rb'\b(?:ep|EP)[0-9]{2,}-keyframes', r'第[0-9]+期'.encode()]
        if any(re.search(pattern, payload) for pattern in patterns):
            raise ValueError('Private or episode-specific content found: ' + file.name)
        entries[str(file.relative_to(skills))] = payload
    guide = re.sub(r'第[0-9]+期', '现有生产前端', (media / 'references/segment-review.md').read_text())
    entries['fred-remotion-output/references/segment-review.md'] = guide.encode()
    example_info = None
    if example:
        example = Path(example).resolve()
        provenance = json.loads((example / 'source-provenance.json').read_text())
        if provenance.get('example', {}).get('purpose') != 'review-template-example' or not provenance['example'].get('authorization'):
            raise ValueError('Example requires explicit provenance and authorization')
        if not (example / 'START.py').is_file():
            raise ValueError('Example must contain its portable launcher')
        for file in example.rglob('*'):
            if not file.is_file() or any(p in {'__pycache__', 'images'} for p in file.relative_to(example).parts):
                continue
            if file.name in {'feedback.json', '.DS_Store', 'review-package.zip'} or file.suffix in {'.log', '.tmp', '.pyc'}:
                continue
            if file.suffix not in {'.json', '.md', '.py', '.mjs', '.js', '.html', '.css', '.mp4', '.wav', '.srt', '.jpg', '.png'}:
                raise ValueError('Unexpected example file: ' + file.name)
            payload = file.read_bytes()
            if file.suffix not in {'.mp4', '.wav', '.jpg', '.png'} and any(re.search(p, payload) for p in [rb'/(?:Users|home)/[A-Za-z0-9._-]+/', rb'\.codex/(?:archived_)?sessions/']):
                raise ValueError('Private path in example: ' + file.name)
            entries['example/' + str(file.relative_to(example))] = payload
        example_info = {k: provenance[k] for k in ['example', 'durationSeconds', 'frames', 'subtitleCues']}
    output = Path(output).resolve()
    output.parent.mkdir(parents=True, exist_ok=True)
    if output.exists():
        raise ValueError('Package exists; choose a new output filename')
    manifest = dict(schemaVersion=1, packageType='review-template-update',
                    requiresExistingSkills=['fred-remotion-output', 'audio-subtitle-roughcut'],
                    runtimes=['Python 3.9+', 'Node.js 18+', 'FFmpeg/FFprobe for media preparation'],
                    episodeDataIncluded=bool(example), example=example_info, credentialsIncluded=False,
                    files={k: hashlib.sha256(v).hexdigest() for k, v in sorted(entries.items())})
    temp = output.with_suffix('.zip.tmp')
    with zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) as archive:
        for name, payload in sorted(entries.items()):
            archive.writestr(name, payload)
        archive.writestr('template-package.json', json.dumps(manifest, ensure_ascii=False, indent=2))
        archive.writestr('USAGE.md', '# Review template update\n\nExtract these files into an existing skills directory containing both required skills. This is a template update, not a standalone media-production Skill. It relies on the existing workflow/library gate modules and catalog. The reusable code contains no episode state, private configuration or chat history. When explicitly selected, authorized media is kept separately under example/.\n\nInitialize audio with audio-subtitle-roughcut/scripts/init_review.py. Initialize media views with fred-remotion-output/scripts/init_review_app.py. Start linked modules with serve_review_app.py --review <episode>/03_制作过程/review-app --audio-review <episode>/03_制作过程/audio-review. Read the installed reference segment-review.md for the data contract and final delivery registration.\n')
        if example:
            archive.writestr('EXAMPLE-USAGE.md', '# 真实前端示例\n\n本包另含用户授权的真实片段及对应口播、字幕、关键帧和视频。解压后执行 `python3 example/START.py`，浏览器打开 http://127.0.0.1:8168/ 和 http://127.0.0.1:8169/ 。已有示例只需Python和Node，不需API或npm安装。停止时Ctrl-C。默认端口可用 --port 和 --audio-port 更改。示例是源成片的派生片段，来源/规格见example/source-provenance.json；不包含旧用户意见、凭证或聊天。\n\n新一期沿用公共模板，只更换Manifest和本期素材。生成新数据仍需安装上面两个Skill，不把示例的画面顺序当成固定创作模板。\n')
    with zipfile.ZipFile(temp) as archive:
        if archive.testzip():
            raise ValueError('ZIP integrity check failed')
        for name, expected in manifest['files'].items():
            if hashlib.sha256(archive.read(name)).hexdigest() != expected:
                raise ValueError('ZIP content hash mismatch')
    temp.replace(output)
    return dict(output=str(output), files=len(entries), sha256=hashlib.sha256(output.read_bytes()).hexdigest(), **{k: v for k, v in manifest.items() if k != 'files'})

if __name__ == '__main__':
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--output', required=True)
    p.add_argument('--example', help='Explicitly authorized portable example directory')
    args = p.parse_args()
    print(json.dumps(package(args.output, args.example), ensure_ascii=False, indent=2))
```

## File: skills/audio-subtitle-roughcut/scripts/qwen_asr.py
size: 9955
sha: 16010a7e562e1543e1baa6d44baefeb59dc9c89b
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/qwen_asr.py

```text
"""Alibaba file transcription with private credentials and resumable task receipts."""
import argparse
import getpass
import hashlib
import json
import os
import re
from pathlib import Path
import stat
import subprocess
import tempfile
import time

MODEL = 'qwen-audio-3.1-asr-flash-filetrans'
BASE = 'https://dashscope.aliyuncs.com/api/v1'
KEY_PATH = Path.home() / '.config/fredtalk/private/dashscope-api-key'

def write_json(path, data):
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix='.pending-')
    try:
        with os.fdopen(fd, 'w') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        os.replace(tmp, path)
    finally:
        if os.path.exists(tmp): os.unlink(tmp)

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

def configure():
    key = getpass.getpass('API key (hidden): ').strip()
    if not key or any(c.isspace() for c in key):
        raise ValueError('Invalid key format')
    KEY_PATH.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    os.chmod(KEY_PATH.parent, 0o700)
    fd, tmp = tempfile.mkstemp(dir=KEY_PATH.parent, prefix='.key-')
    try:
        with os.fdopen(fd, 'w') as f: f.write(key+'\n')
        os.chmod(tmp, 0o600)
        os.replace(tmp, KEY_PATH)
    finally:
        if os.path.exists(tmp): os.unlink(tmp)
    print('Saved private local credential (0600); value not displayed.')

def credential():
    if KEY_PATH.is_symlink(): raise ValueError('Credential must not be a symlink')
    if stat.S_IMODE(KEY_PATH.stat().st_mode) != 0o600:
        raise ValueError('Credential permissions must be 0600')
    key = KEY_PATH.read_text().strip()
    if not key: raise ValueError('Empty credential')
    return key

def timestamp(ms):
    ms = round(ms)
    return '{:02}:{:02}:{:02},{:03}'.format(ms//3600000, ms//60000%60, ms//1000%60, ms%1000)

def export_result(raw, root):
    sentences = [s for t in raw.get('transcripts', []) for s in t.get('sentences', [])]
    if not sentences: raise ValueError('No transcription sentences returned')
    words = []
    blocks = []
    previous = -1
    for i, s in enumerate(sentences, 1):
        a, b = s['begin_time'], s['end_time']
        if not 0 <= a < b or a < previous: raise ValueError('Invalid sentence timestamps')
        previous = b
        blocks.append(f'{i}\n{timestamp(a)} --> {timestamp(b)}\n{s["text"]}')
        for w in s.get('words', []):
            if not a <= w['begin_time'] <= w['end_time'] <= b:
                raise ValueError('Invalid word timestamps')
            words.append(dict(w, sentence_id=i))
    if not words: raise ValueError('Word timestamps missing; do not claim word alignment')
    (root/'source-asr.srt').write_text('\n\n'.join(blocks)+'\n')
    write_json(root/'word-timestamps.json', words)
    write_json(root/'asr-validation.json', dict(sentences=len(sentences),wordRecords=len(words),
        includesWhitespaceTokens=True,listeningReviewed=False,finalSubtitles=False))

def checked(response):
    # Do not print response bodies, URLs, headers or exception strings containing signed URLs.
    if not response.ok: raise RuntimeError('Alibaba HTTP status '+str(response.status_code))
    return response.json()

def execute(args):
    import requests
    root = args.output.resolve()
    root.mkdir(parents=True, exist_ok=True)
    state_path = root/'asr-state.json'
    source = args.audio.resolve()
    identity = dict(model=MODEL, sourceHash=digest(source))
    if state_path.exists():
        state = json.loads(state_path.read_text())
        if any(state.get(k) != v for k,v in identity.items()):
            raise ValueError('Output belongs to another audio/model; use a separate directory')
        if state.get('status') == 'complete':
            export_result(json.loads((root/'raw-asr.json').read_text()),root)
            print('Reused completed result; no API request.')
            return
        if not state.get('task_id'):
            raise ValueError('Prior submit outcome unknown. Resolve task in console; do not resubmit automatically.')
    else:
        state = identity.copy()
        if (root/'raw-asr.json').exists(): raise ValueError('Existing unmanaged result; use another directory')
    session = requests.Session()
    session.trust_env = False
    headers = {'Authorization':'Bearer '+credential()}
    if not state.get('task_id'):
        context = args.context.read_text().strip() if args.context else ''
        if len(context)>400: raise ValueError('Context must be <=400 characters; use names, not the entire script')
        terms = json.loads(args.terms.read_text()) if args.terms else []
        if not isinstance(terms,list) or any(not isinstance(t,str) or not t.strip() for t in terms):
            raise ValueError('Terms must be a JSON list of nonempty strings')
        flac = root/'source-asr-mono.flac'
        # Measure float WAV headroom before integer FLAC conversion; preserve quiet inputs.
        measurement=subprocess.run(['ffmpeg','-nostdin','-v','info','-i',str(source),'-map','0:a:0',
            '-af','astats=metadata=0:reset=0','-f','null','-'],capture_output=True,text=True,check=True)
        peaks=[float(v) for v in re.findall(r'Peak level dB:\s*(-?[\d.]+)',measurement.stderr)]
        if not peaks: raise ValueError('Cannot measure source peak; inspect audio before upload')
        gain=min(0.0,-1.0-max(peaks))
        write_json(root/'asr-conversion.json',dict(gainDb=gain,sourcePeakDb=max(peaks),speed=1,sourceHash=identity['sourceHash']))
        subprocess.run(['ffmpeg','-nostdin','-v','error','-y','-i',str(source),'-map','0:a:0',
            '-af',f'volume={gain}dB','-ac','1','-ar','48000','-sample_fmt','s32','-c:a','flac',str(flac)],check=True)
        policy=checked(session.get(BASE+'/uploads',params={'action':'getPolicy','model':MODEL},headers=headers,timeout=30))['data']
        object_key=policy['upload_dir']+'/'+flac.name
        form={'OSSAccessKeyId':policy['oss_access_key_id'],'Signature':policy['signature'],
              'policy':policy['policy'],'key':object_key,'x-oss-object-acl':policy['x_oss_object_acl'],
              'x-oss-forbid-overwrite':policy['x_oss_forbid_overwrite'],'success_action_status':'200'}
        with flac.open('rb') as f:
            response=session.post(policy['upload_host'],data=form,files={'file':f},timeout=240)
        if response.status_code!=200: raise RuntimeError('Temporary upload failed; no ASR submitted')
        body={'model':MODEL,'input':{'file_urls':['oss://'+object_key]},
              'parameters':{'channel_id':[0],'language_hints':['zh','en'],'keep_dialect':True,
                            'vocabulary':{term:2 for term in terms}}}
        if context:body['input']['context']=[{'role':'user','content':[{'type':'input_text','text':context}]}]
        write_json(root/'request-redacted.json',dict(body,input=dict(body['input'],file_urls=['[temporary Alibaba object]'])))
        state.update(status='submitting',createdAt=time.time())
        write_json(state_path,state)
        submitted=checked(session.post(BASE+'/services/audio/asr/transcription',
            headers=dict(headers,**{'X-DashScope-Async':'enable','X-DashScope-OssResourceResolve':'enable'}),json=body,timeout=60))
        state.update(task_id=submitted['output']['task_id'],status='submitted')
        write_json(state_path,state)
    print('Model:',MODEL,'task:',state['task_id'],flush=True)
    for _ in range(args.polls):
        result=checked(session.get(BASE+'/tasks/'+state['task_id'],headers=headers,timeout=30))
        output=result['output'];status=output['task_status']
        state.update(status=status,usage=result.get('usage'))
        write_json(state_path,state)
        if status=='SUCCEEDED':
            results=output.get('results',[])
            if len(results)!=1 or results[0].get('subtask_status')!='SUCCEEDED':
                raise RuntimeError('ASR subtask failed; saved task ID can be inspected')
            url=results[0]['transcription_url']
            if not url.startswith(('https://','http://')):raise ValueError('Unexpected result URL')
            response=session.get(url,timeout=60)
            raw=checked(response)
            raw.pop('file_url',None)
            write_json(root/'raw-asr.json',raw)
            export_result(raw,root)
            state.update(status='complete');write_json(state_path,state)
            print('Saved raw ASR, sentence SRT and word timestamps. Editorial review still required.')
            return
        if status in ('FAILED','CANCELED','UNKNOWN'):raise RuntimeError('ASR status '+status)
        time.sleep(args.interval)
    raise RuntimeError('Polling window ended. Repeat the same command to resume, not resubmit.')

def main():
    p=argparse.ArgumentParser()
    sub=p.add_subparsers(dest='command',required=True)
    sub.add_parser('configure')
    t=sub.add_parser('transcribe')
    t.add_argument('--audio',type=Path,required=True)
    t.add_argument('--output',type=Path,required=True)
    t.add_argument('--context',type=Path)
    t.add_argument('--terms',type=Path)
    t.add_argument('--polls',type=int,default=120)
    t.add_argument('--interval',type=float,default=10)
    e=sub.add_parser('export')
    e.add_argument('--json',type=Path,required=True)
    e.add_argument('--output',type=Path,required=True)
    args=p.parse_args()
    try:
        if args.command=='configure':configure()
        elif args.command=='export':
            args.output.mkdir(parents=True,exist_ok=True)
            export_result(json.loads(args.json.read_text()),args.output)
        else:execute(args)
    except Exception as exc:
        # Network errors may contain temporary credentials in URLs.
        message=str(exc) if isinstance(exc,(ValueError,RuntimeError)) else type(exc).__name__
        p.exit(1,'Error: '+message+'\n')

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

## File: skills/audio-subtitle-roughcut/scripts/test_loudness_profile.py
size: 2980
sha: 9c1635bd1c161886335e44935cf50db075c9af18
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/test_loudness_profile.py

```text
"""Behavior checks for read-only full-audio profiling, using isolated synthetic audio."""
import hashlib
import math
from pathlib import Path
import struct
import tempfile
import unittest
import wave
from loudness_profile import build_profile

class LoudnessProfileTest(unittest.TestCase):
    def setUp(self):
        self.tmp=tempfile.TemporaryDirectory(prefix='loudness-profile-test-')
        self.path=Path(self.tmp.name)/'input.wav'
    def tearDown(self):self.tmp.cleanup()
    def audio(self,duration,amplitude):
        rate=48000
        frames=bytearray()
        for i in range(round(duration*rate)):
            t=i/rate;v=round(32767*amplitude(t)*math.sin(2*math.pi*997*t))
            frames.extend(struct.pack('<hh',v,v))
        with wave.open(str(self.path),'wb') as w:
            w.setparams((2,2,rate,0,'NONE','not compressed'));w.writeframes(frames)
    def test_local_jump_is_found_despite_close_integrated_average(self):
        self.audio(20,lambda t:.16 if 8<=t<9 else .08)
        before=hashlib.sha256(self.path.read_bytes()).hexdigest()
        result=build_profile(self.path,segments=[dict(id='intro',role='narration',start=0,end=8),dict(id='insert',role='insert',start=8,end=9),dict(id='body',role='narration',start=9,end=20)])
        self.assertTrue(result['analysisOnly'])
        self.assertEqual(hashlib.sha256(self.path.read_bytes()).hexdigest(),before)
        self.assertLess(abs(result['integrated']['integratedLufs']-result['reference']['momentaryMedianLufs']),2)
        self.assertGreater(max(p['momentaryLufs'] for p in result['timeline'] if p['momentaryLufs'] is not None)-result['reference']['momentaryMedianLufs'],4)
        self.assertTrue(any(p['start']<9 and p['end']>8 for p in result['candidates']))
        self.assertIsNone(result['segments'][1]['shortTermMedianLufs'])
    def test_silence_is_unavailable_not_zero_lufs(self):
        self.audio(2,lambda t:0)
        result=build_profile(self.path)
        self.assertIsNone(result['reference']['momentaryMedianLufs'])
        self.assertEqual(result['candidates'],[])
        self.assertTrue(all(p['momentaryLufs'] is None for p in result['timeline']))
    def test_short_cue_does_not_inherit_another_segments_window(self):
        self.audio(4,lambda t:.1)
        result=build_profile(self.path,cues=[dict(start=.1,end=.3,text='short'),dict(start=1,end=2,text='longer')])
        self.assertEqual(result['cues'][0]['momentarySamples'],0)
        self.assertIsNone(result['cues'][0]['momentaryMedianLufs'])
        self.assertGreater(result['cues'][1]['momentarySamples'],0)
        self.assertIsNone(result['cues'][1]['shortTermMedianLufs'])
    def test_invalid_ranges_fail_before_processing(self):
        self.audio(2,lambda t:.1)
        for segments in [[dict(start=0,end=3,role='insert')],[dict(start=0,end=1.5),dict(start=1,end=2)]]:
            with self.assertRaises(ValueError):build_profile(self.path,segments=segments)

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

## File: skills/audio-subtitle-roughcut/scripts/test_quality.py
size: 4477
sha: 431517952af491f7be075b214a85ce5fc8d36c8e
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/test_quality.py

```text
import copy
import json
import math
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import unittest
import wave
from deliver import load_server

SCRIPTS = Path(__file__).resolve().parent

class QualityTest(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory(prefix='roughcut-quality-')
        self.episode = Path(self.tmp.name) / 'Test'
        self.episode.mkdir()
        self.audio = self.episode / 'input.wav'
        # The phase produces intersample peaks after hard limiting.
        with wave.open(str(self.audio), 'wb') as w:
            w.setparams((2, 2, 48000, 0, 'NONE', 'not compressed'))
            w.writeframes(b''.join(struct.pack('<hh', *([int(29000*math.sin(2*math.pi*9973*i/48000+.7))]*2)) for i in range(96000)))
        (self.episode/'input.srt').write_text('1\n00:00:00,000 --> 00:00:02,000\n一共一秒只需要6积分一秒啊\n')
        (self.episode/'script.md').write_text('测试')
        subprocess.run([sys.executable,str(SCRIPTS/'init_review.py'),'--episode',str(self.episode),'--audio',str(self.audio),'--subtitles',str(self.episode/'input.srt'),'--script',str(self.episode/'script.md'),'--title','Test'],check=True,capture_output=True)
        self.root=self.episode/'03_制作过程/audio-review'
        self.cuts=[dict(id='repeat',start=.4,end=.7,enabled=True)]
        self.write('cuts.json', self.cuts)
        self.write('subtitle-boundaries.json',[dict(cue=1,cutId='repeat',cutRange=[.4,.7],removeInfix=dict(text='一秒',occurrence=1),note='word and waveform reviewed')])
        self.server=load_server(self.root)
    def tearDown(self):
        self.tmp.cleanup()
    def write(self,name,data):
        (self.root/name).write_text(json.dumps(data,ensure_ascii=False))
    def test_infix_export_and_restore(self):
        self.assertEqual(self.server.corrected_project()['cues'][0]['text'],'一共只需要6积分一秒啊')
        result=self.server.export(self.cuts)
        blocks=(Path(result['path'])/'review-cut.srt').read_text().strip().split('\n\n')
        self.assertEqual(len(blocks),1)
        self.assertIn('一共只需要6积分一秒啊',blocks[0])
        self.assertEqual(result['subtitleWarnings'],0)
        restored=copy.deepcopy(self.cuts);restored[0]['enabled']=False
        # Export must respect the passed decision, even before saving the JSON.
        result=self.server.export(restored)
        self.assertIn('一共一秒只需要6积分一秒啊',(Path(result['path'])/'review-cut.srt').read_text())
        self.write('cuts.json',restored)
        self.assertEqual(self.server.corrected_project()['cues'][0]['text'],'一共一秒只需要6积分一秒啊')
    def test_moved_cut_requires_new_text_review(self):
        self.cuts[0]['end']=.9;self.write('cuts.json',self.cuts)
        with self.assertRaisesRegex(ValueError,'range'):
            self.server.corrected_project()
    def test_unreviewed_extra_cut_still_warns(self):
        cuts=self.cuts+[dict(id='unknown',start=1.2,end=1.3,enabled=True)]
        self.write('cuts.json',cuts)
        result=self.server.export(cuts)
        self.assertGreater(result['subtitleWarnings'],0)
    def test_occurrence_and_manual_override(self):
        plan=json.loads((self.root/'subtitle-boundaries.json').read_text());plan[0]['removeInfix']['occurrence']=2
        self.write('subtitle-boundaries.json',plan)
        self.assertEqual(self.server.corrected_project()['cues'][0]['text'],'一共一秒只需要6积分啊')
        self.server.save_subtitle(dict(cue=1,text='用户手改'))
        self.assertEqual(self.server.corrected_project()['cues'][0]['text'],'用户手改')
    def test_true_peak_and_unity_speed_duration(self):
        self.write('cuts.json',[]);self.write('subtitle-boundaries.json',[])
        subprocess.run([sys.executable,str(SCRIPTS/'deliver.py'),'--review',str(self.root),'--version','v1','--speed','1','--trim-start','0','--gain-db','8'],check=True,capture_output=True)
        m=json.loads((self.root/'final-delivery.json').read_text())
        # Independent measurement, not the manifest's self-reported pass.
        from audio_qc import measure
        measured=measure(self.root / m['audioPath'])
        self.assertLessEqual(measured['truePeakDbtp'],-1+.05)
        self.assertEqual(m['frames'],96000)
        self.assertIn('loudnessBefore',m)
        self.assertTrue(m['truePeakCheck']['passed'])

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

## File: skills/audio-subtitle-roughcut/scripts/test_qwen_asr.py
size: 3464
sha: d506475d7dc377163ef5e49f3d1215a2e7cd126d
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/test_qwen_asr.py

```text
import argparse
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch, MagicMock
import qwen_asr as q

RAW={'transcripts':[{'sentences':[{'begin_time':100,'end_time':900,'text':'第二，这里啊',
    'words':[{'begin_time':100,'end_time':300,'text':'第二'},{'begin_time':300,'end_time':900,'text':'这里啊'}]}]}]}

class QwenTests(unittest.TestCase):
    def test_export_preserves_raw_text(self):
        with tempfile.TemporaryDirectory() as d:
            root=Path(d);q.export_result(RAW,root)
            self.assertIn('第二，这里啊',(root/'source-asr.srt').read_text())
            self.assertEqual(len(json.loads((root/'word-timestamps.json').read_text())),2)
    def test_invalid_word_bounds(self):
        raw=json.loads(json.dumps(RAW));raw['transcripts'][0]['sentences'][0]['words'][0]['begin_time']=0
        with tempfile.TemporaryDirectory() as d:
            with self.assertRaises(ValueError):q.export_result(raw,Path(d))
    def test_key_permissions(self):
        with tempfile.TemporaryDirectory() as d:
            p=Path(d)/'private/key'
            with patch.object(q,'KEY_PATH',p),patch.object(q.getpass,'getpass',return_value='test-only-placeholder'):
                q.configure();self.assertEqual(q.credential(),'test-only-placeholder')
                self.assertEqual(p.stat().st_mode&0o777,0o600)
                self.assertEqual(p.parent.stat().st_mode&0o777,0o700)
    def setup_job(self,root,status,task=None):
        src=root/'input.wav';src.write_bytes(b'test-source')
        state=dict(model=q.MODEL,sourceHash=q.digest(src),status=status)
        if task:state['task_id']=task
        q.write_json(root/'asr-state.json',state)
        return argparse.Namespace(audio=src,output=root,polls=1,interval=0)
    def test_ambiguous_submit_stops(self):
        with tempfile.TemporaryDirectory() as d:
            args=self.setup_job(Path(d),'submitting')
            with patch.object(q,'credential',side_effect=AssertionError('must not read key')):
                with self.assertRaisesRegex(ValueError,'unknown'):q.execute(args)
    def test_completed_is_offline(self):
        with tempfile.TemporaryDirectory() as d:
            root=Path(d);args=self.setup_job(root,'complete');q.write_json(root/'raw-asr.json',RAW)
            with patch.object(q,'credential',side_effect=AssertionError('must not read key')):q.execute(args)
    def test_resume_never_posts(self):
        with tempfile.TemporaryDirectory() as d:
            root=Path(d);args=self.setup_job(root,'RUNNING','saved-task')
            session=MagicMock()
            result={'output':{'task_status':'SUCCEEDED','results':[{'subtask_status':'SUCCEEDED','transcription_url':'https://example.test/result'}]}}
            responses=[]
            for data in [result,dict(RAW,file_url='temporary-signed-url')]:
                response=MagicMock();response.ok=True;response.json.return_value=data;responses.append(response)
            session.get.side_effect=responses
            with patch('requests.Session',return_value=session),patch.object(q,'credential',return_value='test-only-placeholder'):
                q.execute(args)
            session.post.assert_not_called()
            self.assertNotIn('file_url',json.loads((root/'raw-asr.json').read_text()))
            self.assertEqual(json.loads((root/'asr-state.json').read_text())['status'],'complete')

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

## File: skills/audio-subtitle-roughcut/scripts/test_restore_bindings.py
size: 6738
sha: 82eeb998840d9d09c3b65a630f0e73f47ee779ff
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/test_restore_bindings.py

```text
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
import wave
from http.server import ThreadingHTTPServer
from threading import Thread
from urllib.request import Request, urlopen

from deliver import load_server

SCRIPTS = Path(__file__).resolve().parent

class RestoreBindingsTest(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory(prefix='roughcut-restore-')
        self.episode = Path(self.tmp.name) / 'Test'
        self.episode.mkdir()
        audio = self.episode / 'input.wav'
        with wave.open(str(audio), 'wb') as output:
            output.setparams((2, 2, 48000, 0, 'NONE', 'not compressed'))
            output.writeframes(b'\0' * 3 * 48000 * 4)
        subs = self.episode / 'input.srt'
        subs.write_text('1\n00:00:00,000 --> 00:00:01,000\n但是前句\n\n'
                        '2\n00:00:01,000 --> 00:00:02,000\n但是中句\n\n'
                        '3\n00:00:02,000 --> 00:00:03,000\n但是后句\n')
        script = self.episode / 'script.md'
        script.write_text('测试')
        subprocess.run([sys.executable, str(SCRIPTS / 'init_review.py'), '--episode', str(self.episode),
                        '--audio', str(audio), '--subtitles', str(subs), '--script', str(script),
                        '--title', 'Restore test'], check=True, capture_output=True)
        self.root = self.episode / '03_制作过程/audio-review'
        self.write('subtitle-boundaries.json', [dict(cue=i, cutId='wide', removePrefix='但是', note='fixture') for i in (1, 2, 3)])
        self.server = load_server(self.root)

    def tearDown(self):
        self.tmp.cleanup()

    def write(self, name, data):
        (self.root / name).write_text(json.dumps(data, ensure_ascii=False))

    def test_split_restoration_preserves_other_cue_bindings(self):
        cuts = [dict(id='wide', start=.2, end=2.8, enabled=False),
                dict(id='left', originCutId='wide', start=.2, end=1, enabled=True),
                dict(id='right', originCutId='wide', start=2, end=2.8, enabled=True)]
        self.write('cuts.json', cuts)
        texts = [cue['text'] for cue in self.server.corrected_project()['cues']]
        self.assertEqual(texts, ['前句', '但是中句', '后句'])
        # Export and a reload use the persisted fragments, not frontend-only state.
        result = self.server.export(cuts)
        self.assertIn('但是中句', (Path(result['path']) / 'review-cut.srt').read_text())
        reloaded = load_server(self.root)
        self.assertEqual([c['text'] for c in reloaded.corrected_project()['cues']], texts)

    def test_bound_prefix_and_time_restore_when_this_cue_loses_overlap(self):
        self.write('subtitle-boundaries.json', [dict(cue=2, cutId='wide', start=1.2, removePrefix='但是', note='fixture')])
        cuts = [dict(id='wide', start=.2, end=2.8, enabled=False),
                dict(id='left', originCutId='wide', start=.2, end=1, enabled=True),
                dict(id='right', originCutId='wide', start=2, end=2.8, enabled=True)]
        cue = self.server.corrected_project(cuts=cuts)['cues'][1]
        self.assertEqual((cue['start'], cue['text']), (1, '但是中句'))
        cuts[0]['enabled'] = True
        cue = self.server.corrected_project(cuts=cuts)['cues'][1]
        self.assertEqual((cue['start'], cue['text']), (1.2, '中句'))

    def test_manual_text_override_survives_bound_cut_restore(self):
        self.write('cuts.json', [dict(id='wide', start=.2, end=2.8, enabled=False)])
        self.server.save_subtitle(dict(cue=2, text='用户修改'))
        cue = self.server.corrected_project()['cues'][1]
        self.assertEqual(cue['text'], '用户修改')
        self.assertEqual(cue['correctedText'], '但是中句')

    def test_original_cut_preserves_legal_cross_cue_word_binding(self):
        self.write('subtitle-boundaries.json', [dict(cue=2, cutId='trigger', removePrefix='但是', note='adjacent cue word ownership')])
        cue = self.server.corrected_project(cuts=[dict(id='trigger', start=.2, end=.8, enabled=True)])['cues'][1]
        self.assertEqual(cue['text'], '中句')
        cue = self.server.corrected_project(cuts=[dict(id='trigger', start=.2, end=.8, enabled=False)])['cues'][1]
        self.assertEqual(cue['text'], '但是中句')

    def test_save_restore_undo_redo_preserves_fragments_and_bound_text(self):
        original = [dict(id='wide', start=.2, end=2.8, enabled=True)]
        restored = [dict(id='wide', start=.2, end=2.8, enabled=False),
                    dict(id='left', originCutId='wide', start=.2, end=1, enabled=True),
                    dict(id='right', originCutId='wide', start=2, end=2.8, enabled=True)]
        http = ThreadingHTTPServer(('127.0.0.1', 0), self.server.Handler)
        thread = Thread(target=http.serve_forever, daemon=True)
        thread.start()
        try:
            base = f'http://127.0.0.1:{http.server_port}'
            for cuts, expected in [(restored, ['前句', '但是中句', '后句']),
                                   (original, ['前句', '中句', '后句']),
                                   (restored, ['前句', '但是中句', '后句'])]:
                request = Request(base + '/api/save', json.dumps(dict(cuts=cuts)).encode(),
                                  {'Content-Type': 'application/json'})
                with urlopen(request) as response:
                    self.assertTrue(json.load(response)['saved'])
                with urlopen(base + '/api/project') as response:
                    self.assertEqual([cue['text'] for cue in json.load(response)['cues']], expected)
                self.assertEqual(json.loads((self.root / 'cuts.json').read_text()), cuts)
        finally:
            http.shutdown()
            http.server_close()
            thread.join()

    def test_static_code_revalidates_without_changing_audio_cache_policy(self):
        http = ThreadingHTTPServer(('127.0.0.1', 0), self.server.Handler)
        thread = Thread(target=http.serve_forever, daemon=True)
        thread.start()
        try:
            base = f'http://127.0.0.1:{http.server_port}'
            for route in ['/', '/app.js?v=current', '/styles.css?v=current']:
                with urlopen(base + route) as response:
                    self.assertEqual(response.headers.get('Cache-Control'), 'no-cache')
            with urlopen(base + '/source.wav') as response:
                self.assertIsNone(response.headers.get('Cache-Control'))
                self.assertEqual(response.read()[:4], b'RIFF')
        finally:
            http.shutdown()
            http.server_close()
            thread.join()

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

## File: skills/audio-subtitle-roughcut/scripts/test_review_actions.js
size: 7513
sha: dae6f87194378c474eb9db8b8ba7b4e1ffd7f4e8
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/test_review_actions.js

```text
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');

const template = path.resolve(__dirname, '../assets/review-app');
function review() {
  const elements = new Map();
  const backups = [];
  const element = id => {
    if (!elements.has(id)) elements.set(id, {
      value: id === 'zoom' ? '1' : id === 'filter' ? 'all' : '', checked: false,
      style: {}, innerHTML: '', textContent: '', disabled: false, clientWidth: 640,
      classList: {toggle() {}, add() {}, remove() {}, contains() {return false;}},
      setAttribute() {}, pause() {}, focus() {}, showModal() {}, close() {},
      getContext() {return {setTransform() {}, clearRect() {}, fillText() {}, fillRect() {}, strokeRect() {}};},
    });
    return elements.get(id);
  };
  const sandbox = {
    document: {getElementById: element, querySelector: element, querySelectorAll: () => [],
      body: element('body'), addEventListener() {}}, window: {}, lucide: {createIcons() {}},
    localStorage: {setItem(key, value) {backups.push(JSON.parse(value));}}, requestAnimationFrame() {},
    fetch: () => new Promise(() => {}), setTimeout() {}, clearTimeout() {},
    devicePixelRatio: 1, Date, console,
  };
  vm.createContext(sandbox);
  const actions = path.join(template, 'cut-actions.js');
  if (fs.existsSync(actions)) vm.runInContext(fs.readFileSync(actions, 'utf8'), sandbox);
  vm.runInContext(fs.readFileSync(path.join(template, 'app.js'), 'utf8'), sandbox);
  const run = source => vm.runInContext(source, sandbox);
  run(`project={duration:3,episodeKey:'test',sourceHash:'test',peaks:[],script:'',cues:[
    {id:1,start:0,end:1,originalStart:0,originalEnd:1,text:'第一句'},
    {id:2,start:1,end:2,originalStart:1,originalEnd:2,text:'第二句'},
    {id:3,start:2,end:3,originalStart:2,originalEnd:3,text:'第三句'}]}; cuts=[];`);
  return {run, elements, backups};
}

let passed = 0, failed = 0;
function test(name, fn) {
  try {fn(); passed++; console.log(`PASS ${name}`);}
  catch (error) {failed++; console.error(`FAIL ${name}: ${error.message}`);}
}
test('repeated sentence deletion does not stack cuts or undo checkpoints', () => {
  const {run} = review();
  run(`addCut(1,2,'手动删除整句'); addCut(1,2,'手动删除整句');`);
  assert.equal(run('cuts.length'), 1);
  assert.equal(run('history.length'), 1);
});
test('already covered selection does not create a duplicate broad cut', () => {
  const {run} = review();
  run(`cuts=[{id:'a',start:1,end:1.5,enabled:true},{id:'b',start:1.5,end:2,enabled:true}];addCut(1,2);`);
  assert.equal(run('cuts.length'), 2);
  assert.equal(run('history.length'), 0);
});
test('each row offers restore and disables it only without active overlap', () => {
  const {run, elements} = review();
  run(`cuts=[{id:'a',start:1.1,end:1.3,enabled:true}];renderTranscript();`);
  const html = elements.get('transcript').innerHTML;
  assert.match(html, /data-restore="2"(?! disabled)/);
  assert.match(html, /data-restore="1" disabled/);
});
test('one restore clears all repeated deletions and undo redo round trips', () => {
  const {run, backups} = review();
  run(`cuts=[{id:'a',start:1,end:2,enabled:true},{id:'b',start:1,end:2,enabled:true}];restoreCue(2);`);
  assert.equal(run('cuts.filter(c=>c.enabled).length'), 0);
  assert.equal(backups.at(-1).cuts.filter(c => c.enabled).length, 0);
  assert.equal(run('history.length'), 1);
  run(`$('undo').onclick();`);
  assert.equal(run('cuts.filter(c=>c.enabled).length'), 2);
  assert.equal(backups.at(-1).cuts.filter(c => c.enabled).length, 2);
  run(`$('redo').onclick();`);
  assert.equal(run('cuts.filter(c=>c.enabled).length'), 0);
  assert.equal(backups.at(-1).cuts.filter(c => c.enabled).length, 0);
});
test('restore only one cue of a broad cut and retains origin identities', () => {
  const {run} = review();
  run(`cuts=[{id:'wide',start:.2,end:2.8,enabled:true}];restoreCue(2);`);
  assert.equal(run(`JSON.stringify(intervals())`), '[[0.2,1],[2,2.8]]');
  assert.equal(run(`cuts.find(c=>c.id==='wide').enabled`), false);
  assert.equal(run(`cuts.filter(c=>c.enabled&&c.originCutId==='wide').length`), 2);
  run(`$('undo').onclick();`);
  assert.equal(run(`JSON.stringify(intervals())`), '[[0.2,2.8]]');
  run(`$('redo').onclick();`);
  assert.equal(run(`JSON.stringify(intervals())`), '[[0.2,1],[2,2.8]]');
});
test('restoration uses original row bounds after cut-bound subtitle shortening', () => {
  const {run} = review();
  run(`project.cues[1].start=1.2;project.cues[1].end=1.8;cuts=[{id:'bound',start:1.05,end:1.2,enabled:true}];restoreCue(2);`);
  assert.equal(run('cuts.filter(c=>c.enabled).length'), 0);
});
test('bound prefix cut starts before estimated cue and leaves no stray deleted onset', () => {
  const {run} = review();
  run(`project.cues[1].originalStart=1.05;project.cues[1].start=1.2;
    project.subtitleBoundaries=[{cue:2,cutId:'prefix',removePrefix:'但是',start:1.2}];
    cuts=[{id:'prefix',start:1.02,end:1.2,enabled:true}];restoreCue(2);`);
  assert.equal(run('cuts.filter(c=>c.enabled).length'), 0);
});
test('bound prefix restoration never restores the preceding cue content', () => {
  const {run} = review();
  run(`project.cues[1].originalStart=1.05;project.cues[1].start=1.2;
    project.subtitleBoundaries=[{cue:2,cutId:'prefix',removePrefix:'但是',start:1.2}];
    cuts=[{id:'prefix',start:.9,end:1.2,enabled:true}];restoreCue(2);`);
  assert.equal(run('JSON.stringify(intervals())'), '[[0.9,1]]');
});
test('bound suffix restoration reaches the actual tail but protects the next cue', () => {
  const {run} = review();
  run(`project.cues[2].start=2.1;project.cues[2].originalStart=2.1;
    project.subtitleBoundaries=[{cue:2,cutId:'suffix',removeSuffix:'尾字'}];
    cuts=[{id:'suffix',start:1.8,end:2.2,enabled:true}];restoreCue(2);`);
  assert.equal(run('JSON.stringify(intervals())'), '[[2.1,2.2]]');
});
test('restoring a row again is a no-op and does not disturb unrelated cuts', () => {
  const {run} = review();
  run(`cuts=[{id:'a',start:1,end:2,enabled:true},{id:'other',start:2.2,end:2.6,enabled:true}];restoreCue(2);restoreCue(2);`);
  assert.equal(run('history.length'), 1);
  assert.equal(run(`cuts.find(c=>c.id==='other').enabled`), true);
});
test('bounded revision displays inherited gain without applying new processing', () => {
  const {run} = review();
  const info = run(`finalProcessingInfo({processingMode:'bounded-pcm-revision',preprocessingSpeed:1.1,
    speed:1,gainDb:0,passthrough:true,inheritedProcessing:{gainDb:8,peakLimitDb:-1.5},listeningReviewed:false})`);
  assert.match(info, /预处理 1\.1 倍语速/);
  assert.match(info, /音量 \+8 dB/);
  assert.match(info, /本次局部返修，沿用已有音频处理/);
  assert.doesNotMatch(info, /音量 \+0|接缝已听审/);
});
test('ordinary passthrough has no invented inherited gain', () => {
  const {run} = review();
  const info = run(`finalProcessingInfo({speed:1,gainDb:0,passthrough:true,listeningReviewed:false})`);
  assert.doesNotMatch(info, /音量 \+/);
  assert.match(info, /保持源语速与音量/);
});
test('HTML versions app and styles so existing browser caches cannot serve stale controls', () => {
  const html = fs.readFileSync(path.join(template, 'index.html'), 'utf8');
  assert.match(html, /src="app\.js\?v=[a-zA-Z0-9-]+"/);
  assert.match(html, /href="styles\.css\?v=[a-zA-Z0-9-]+"/);
});
console.log(`${passed} passed, ${failed} failed`);
process.exitCode = failed ? 1 : 0;
```

## File: skills/audio-subtitle-roughcut/scripts/test_workflow.py
size: 6321
sha: fb852608deead178512ad70d0af7b27ab3a93ce3
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/test_workflow.py

```text
import json
import math
import shutil
import struct
import subprocess
import sys
import tempfile
import unittest
import wave
from threading import Thread
from urllib.request import urlopen
from http.server import ThreadingHTTPServer
from pathlib import Path
from deliver import load_server
from verify_delivery import verify

class WorkflowTest(unittest.TestCase):
    def test_passthrough_retains_exact_samples(self):
        scripts = Path(__file__).resolve().parent
        with tempfile.TemporaryDirectory(prefix='roughcut-passthrough-') as folder:
            episode = Path(folder) / 'Test_Passthrough'
            episode.mkdir()
            audio, subtitle, script = [episode / name for name in ('input.wav', 'input.srt', 'script.md')]
            samples = b''.join(struct.pack('<hh', value, -value) for value in
                               (0 if i < 4800 else int(31000 * math.sin(i * .057)) for i in range(48000)))
            with wave.open(str(audio), 'wb') as w:
                w.setparams((2, 2, 48000, 0, 'NONE', 'not compressed'))
                w.writeframes(samples)
            subtitle.write_text('1\n00:00:00,100 --> 00:00:00,250\n保留啊\n\n2\n00:00:00,250 --> 00:00:00,500\n重说\n\n3\n00:00:00,500 --> 00:00:01,000\n完整表达\n')
            script.write_text('保留啊，完整表达。')
            subprocess.run([sys.executable, str(scripts / 'init_review.py'), '--episode', str(episode), '--audio', str(audio), '--subtitles', str(subtitle), '--script', str(script), '--title', 'Passthrough'], check=True, capture_output=True)
            root = episode / '03_制作过程/audio-review'
            (root / 'cuts.json').write_text(json.dumps([dict(id='cut-1', start=.25, end=.5, enabled=True)]))
            command = [sys.executable, str(scripts / 'deliver.py'), '--review', str(root), '--version', 'v1', '--passthrough']
            subprocess.run(command, check=True, capture_output=True)
            data = json.loads((root / 'final-delivery.json').read_text())
            with wave.open(str(root / data['audioPath'])) as w:
                self.assertEqual(w.readframes(w.getnframes()), samples[:12000 * 4] + samples[24000 * 4:])
            self.assertEqual((data['speed'], data['gainDb'], data['trimStart']), (1, 0, 0))
            self.assertIsNone(data['peakLimitDb'])
            self.assertTrue(data['passthrough'])
            self.assertTrue(verify(root)['technicalPass'])
            moved = Path(folder) / 'Moved_Passthrough'
            shutil.move(str(episode), moved)
            root = moved / '03_制作过程/audio-review'
            self.assertTrue(verify(root)['technicalPass'])
            relocated = load_server(root)
            self.assertEqual(relocated.EPISODE, moved.resolve())
            command[command.index('--review')+1] = str(root)
            bad = subprocess.run(command + ['--gain-db', '8'], capture_output=True, text=True)
            self.assertNotEqual(bad.returncode, 0)
            self.assertIn('passthrough', bad.stderr)

    def test_isolated_workflow(self):
        scripts = Path(__file__).resolve().parent
        with tempfile.TemporaryDirectory(prefix='roughcut-test-') as folder:
            episode = Path(folder) / '108_Test'
            episode.mkdir()
            audio, subtitle, script = [episode / name for name in ('input.wav', 'input.srt', 'script.md')]
            with wave.open(str(audio), 'wb') as w:
                w.setnchannels(2)
                w.setsampwidth(2)
                w.setframerate(48000)
                w.writeframes(b''.join(struct.pack('<hh', *(2 * [0 if i < 24000 else int(16000 * math.sin(i * .057))])) for i in range(192000)))
            subtitle.write_text('1\n00:00:00,500 --> 00:00:01,500\nUpdate\n\n2\n00:00:01,500 --> 00:00:02,500\n重说\n\n3\n00:00:02,500 --> 00:00:04,000\n完整表达啊\n')
            script.write_text('Dev Day，完整表达啊。')
            cmd = [sys.executable, str(scripts / 'init_review.py'), '--episode', str(episode), '--audio', str(audio), '--subtitles', str(subtitle), '--script', str(script), '--title', 'Synthetic review']
            subprocess.run(cmd, check=True, capture_output=True)
            self.assertNotEqual(subprocess.run(cmd, capture_output=True).returncode, 0)
            root = episode / '03_制作过程/audio-review'
            (root / 'subtitle-corrections.json').write_text(json.dumps([dict(cue=1, **{'from': 'Update', 'to': 'Dev Day'})]))
            cuts = [dict(id='cut-1', start=1.5, end=2.5, title='restart', reason='retain later take', enabled=True, reviewed=True)]
            (root / 'cuts.json').write_text(json.dumps(cuts))
            server = load_server(root)
            self.assertEqual(server.corrected_project()['cues'][0]['text'], 'Dev Day')
            server.save_subtitle(dict(cue=3, text='完整表达啊嗯'))
            subprocess.run([sys.executable, str(scripts / 'deliver.py'), '--review', str(root), '--version', 'v1'], check=True, capture_output=True)
            report = verify(root)
            self.assertTrue(report['technicalPass'])
            self.assertEqual(report['cueCount'], 2)
            final = json.loads((root / 'final-delivery.json').read_text())
            self.assertEqual(final['speed'], 1.1)
            self.assertEqual(final['gainDb'], 8)
            self.assertGreater(final['trimStart'], .35)
            self.assertIn('啊嗯', (root / final['subtitlePath']).read_text())
            self.assertEqual(final['subtitleWarnings'], 0)
            http = ThreadingHTTPServer(('127.0.0.1', 0), server.Handler)
            thread = Thread(target=http.serve_forever, daemon=True)
            thread.start()
            try:
                url = f'http://127.0.0.1:{http.server_port}'
                with urlopen(url + '/api/final') as response:
                    self.assertEqual(json.load(response)['version'], 'v1')
                with urlopen(url + '/final/subtitles.srt') as response:
                    self.assertIn('啊嗯', response.read().decode())
                with urlopen(url + '/final/audio.wav') as response:
                    self.assertEqual(response.read()[:4], b'RIFF')
            finally:
                http.shutdown()
                http.server_close()
                thread.join()

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

## File: skills/audio-subtitle-roughcut/scripts/verify_delivery.py
size: 3198
sha: 9979f1df3f7a1b531ad84c182706a3a45d8ab0a3
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/scripts/verify_delivery.py

```text
import argparse
import json
import re
import subprocess
import wave
from pathlib import Path
from deliver import hash_file, load_server
from audio_qc import measure
from loudness_profile import build_profile, segments_for_delivery
import hashlib

def verify(root):
    server = load_server(root)
    data = json.loads((root / 'final-delivery.json').read_text())
    for path, digest in server.CONFIG['originalInputs'].items():
        assert hash_file(root / path) == digest, f'Input changed: {path}'
    audio, subs = root / data['audioPath'], root / data['subtitlePath']
    assert hash_file(audio) == data['audioHash']
    assert hash_file(subs) == data['subtitleHash']
    with wave.open(str(audio)) as w:
        assert w.getnframes() == data['frames']
        assert abs(w.getnframes() / w.getframerate() - data['duration']) < .0001
    subprocess.run(['ffmpeg', '-nostdin', '-v', 'error', '-i', str(audio), '-f', 'null', '-'], check=True)
    blocks = re.split(r'\n\s*\n', subs.read_text().strip())
    assert len(blocks) == len(data['expectedCues'])
    previous = 0
    for i, (block, expected) in enumerate(zip(blocks, data['expectedCues']), 1):
        lines = block.splitlines()
        assert int(lines[0]) == i
        a, b = map(server.seconds, lines[1].split(' --> '))
        assert 0 <= a < b <= data['duration'] + .001 and a >= previous - .001
        assert abs(a - expected['start']) <= .001 and abs(b - expected['end']) <= .001
        assert '\n'.join(lines[2:]) == expected['text']
        previous = b
    if data.get('truePeakCheck') and not data.get('passthrough'):
        measured = measure(audio)
        check = data['truePeakCheck']
        assert measured['truePeakDbtp'] is None or measured['truePeakDbtp'] <= check['targetDbtp'] + check['toleranceDb'], 'True peak exceeds delivery target'
    roles = segments_for_delivery(data)
    analyzer_hashes = {name: hash_file(Path(__file__).with_name(name)) for name in ('loudness_profile.py', 'audio_qc.py')}
    config_hash = hashlib.sha256(json.dumps(dict(segments=roles, cues=data['expectedCues'], analyzers=analyzer_hashes), sort_keys=True).encode()).hexdigest()[:8]
    profile_path = root / f"loudness-profile-{data['audioHash'][:12]}-{config_hash}.json"
    if profile_path.exists():
        profile = json.loads(profile_path.read_text())
        assert profile['audio']['sha256'] == data['audioHash'], 'Loudness profile audio mismatch'
    else:
        profile = build_profile(audio, segments=roles, cues=data['expectedCues'])
        profile_path.write_text(json.dumps(profile, ensure_ascii=False, indent=2) + '\n')
    report = dict(technicalPass=True, cueCount=len(blocks), duration=data['duration'], subtitleWarnings=data['subtitleWarnings'], listeningReviewed=data['listeningReviewed'], loudnessProfile=profile_path.name, loudnessCandidateCount=len(profile['candidates']), loudnessCandidatesRequireContextReview=True)
    (root / 'delivery-verification.json').write_text(json.dumps(report, indent=2))
    return report

if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument('--review', required=True)
    print(json.dumps(verify(Path(p.parse_args().review).resolve()), indent=2))
```

## File: skills/audio-subtitle-roughcut/references/audio-evidence-and-loudness.md
size: 7097
sha: ee8f54a7b071cbfe9fe513fbba19b4d5a8cafccb
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/references/audio-evidence-and-loudness.md

````text
# 音频剪切证据、残留与整条响度

音频正确、字幕识别有误时，只改文字。ASR给出的词和时码是定位线索，不能单独证明声音里的重复或精确字头。以下要求用于新处理和当前返修，不追溯重做旧交付。

## 先判定问题，再决定是否剪声音

| 当前证据 | 默认处理 |
| --- | --- |
| ASR多字/重复，声音正常；用户也确认是识别错误 | 只校字幕，保留音频；已经误剪时撤回相关刀、恢复被删PCM及必要邻域，保留用户手改文字 |
| 用户指出实际声音有重说、残尾；或已听到两个真实发音 | 定位实际声音，删失败一遍，保护完整后一遍和字头/尾音 |
| ASR写了短词重复，但尚未证明两个真实发音 | 作为禁用候选，先保留音频；核对短段和上下文，不直接启用句内刀 |
| 单一波形二峰、低电平、confidence=1、两次ASR同样写法 | 都不单独证明真实重说；发音可能跨多峰，识别也可能重复出错 |

句内短词删除前，把“删哪遍、保留哪遍、声音证据来自用户反馈还是实际听审、切点是否估算”写进当前cuts的reason/confidence或本期已有决策记录。`reviewed`只表示真实听审/确认状态；写了理由、技术校验或静音播放不改变它。不要为此新增Fred逐刀审批。

用户手改字幕不等于授权剪音频。先读实际subtitle-edits、句子覆盖和禁用刀，不能从旧ASR重新生成状态把手改覆盖掉。若用户已确认是识别多字，不再以“待听审”保留那条误剪；在旧导出里检查该刀是否仍生效并修复声音、字幕和映射。

## 删除重说后查前后残留

- 从原源到剪后接缝检查整个发音单元：失败起句、短词、半个辅音/尾音、吞咽、旁边空隙和后一次完整表达。不要只看整句字幕是否消失。
- ASR常把前一词结束算晚，或把后一词起音算晚。删点先核对实际发音包络，再在保护有效字音的空隙落刀；不固定向前减某个秒数。
- 用户指出残留后，检查删点是否已切进“还/是”等起音。必要时对同一短段重新识别、对齐和观察波形，保留原识别记录；不能只删除字幕或不核声音地把旧时码抄一遍。
- 全篇检查同类问题，给每个候选准确位置和保留/删除理由。局部返修不因此重洗整轨；未改PCM逐样比较，淡化范围另外记录。波形能辅助定位，不能识别词意、吞咽或证明听感。

## 插入声音先核角色和准确源

纯旁白、带动作音效的动画混音、BGM、录屏源声分别登记。字幕同文、文件名相似、帧数接近或hash相同，都不能证明它是纯旁白。先核对用户选中的实际文件/链接目标、hash、采样数和已处理状态，并记录有没有原声/SFX；hash只证明身份，不证明无音效。

用户只要求配音时，优先其明确指定的纯旁白；不从动画MP4、后期混音或同名“过渡动画.WAV”代替，也不靠降噪去除已经混入的动作声。没有可确认的纯旁白时报告准确缺口。Fred固定配音的当前依赖由主Skill `references/fixed-skill-library-insert.md` 和其manifest查询，不固定旧秒数。

## 整条响度不能只看一个LUFS

1. 以实际当前最终音轨分析全片：综合LUFS、LRA、采样/真峰值，以及覆盖全时段的400ms瞬时/3s短时响度。给补录、插入旁白、录屏原声/演示、音效/BGM等实际职责标区间，不能把设计上有意变化的源声统一当成异常。
2. 对同职责声音比较正文、插入前后和插入内部的每句话。几秒素材平均值接近，第一句仍可能突响。短句、含停顿整段、400ms、3s和全片综合LUFS是不同统计量，不混作同一个目标；不足窗口的条目记录无可用测量，不能填0 LUFS。
3. 自动阈值只提出复查位置，结合语义、波形和真实听审决定。正文的自然重音/呼吸、章节演示和用户认可的源声不机械压平；不把某一期的LUFS、音量衰减、秒数或窗口候选数量变成固定配额。
4. 只调整明确不匹配的插入/补录区间，先选同职责的本期正文参考。已处理配音不重复自然链、1.1倍速或+8dB。整段增益足够则用整段，内部句子确实不均匀时再做小幅、平滑的局部音量变化；不默认每一句归一化。不改语速和时长，不硬切音量。必要的峰值保护只在需要的范围做，并复测。
5. 调整后复测实际最终文件，给带前后文的短试听；记录相对原音的实际衰减/增益、局部峰值保护、时钟/字幕hash及未改PCM。保留原配音资产，按本期要求匹配的派生版不覆盖跨期原件。当前声音、字幕、审片台和下载指向同一版本。

### 只读分析工具

`verify_delivery.py`现会生成完整响度轨迹报告，默认从final-delivery的transition/replacement推导职责，其他源声职责由`loudnessSegments`显式提供。报告按音频hash、分段/字幕身份及分析脚本hash命名，不修改音频、字幕、cuts或手改状态。`technicalPass`不代表响度候选已听审或已处理。

也可独立运行：

```bash
python3 scripts/loudness_profile.py --audio /absolute/final.wav \
  --segments /absolute/loudness-segments.json \
  --cues /absolute/cues.json --output /absolute/loudness-profile.json
```

输入为规范PCM16 WAV；segments为不重叠的最终音频秒区间列表，例如`[{"id":"intro","role":"narration","start":0,"end":20},{"id":"insert","role":"insert","start":20,"end":25}]`。不相关区间可不列出；工具不猜声音角色。cues为`[{"start":0.1,"end":1.5,"text":"实际字幕"}]`，可与segment重叠。可调`--threshold-lu`只改变候选阈值；不表示输出目标音量。

报告包括timeline、整条峰值/综合指标、同职责reference、segments/cues的局部窗口摘要及候选。统计只使用完整落在区间内的窗口，不借前后正文填充短插入/短cue；静音、门限以下和未填满窗口为null。FFmpeg最后不足100ms的尾部可能没有独立轨迹点，coverage记录该差值，整条真峰值/综合指标仍包含完整文件；不虚构最后一个窗口。它不会自动听审、识别重说/口腔声、剪切或调音，也不自动认定声源干净。

## 本次错误形成的通用规则

- “接着往下下移”在ASR里多了字，实际只说一个“下”：字幕改“接着往下移”，不能把正常发音剪掉；若误剪则恢复声音。
- “还是…”整句已删除但前面残了起音：查词时码前后的声音，保护“打字”尾音，不能只复用句级起点。
- 插入素材整体LUFS接近正文，但首句偏响：检查内部各句和前后文，必要时平滑局部衰减，不叠加全片处理。
- 同四句字幕也可能对应纯配音和动画/SFX混音：身份及职责分别核对。本期具体切点、衰减和反馈状态留在本期记录，不作为下一期参数。
````

## File: skills/audio-subtitle-roughcut/references/original-audio-api.md
size: 8703
sha: ea9c8e793ea8088325cc59823fdb367dcede4dff
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/references/original-audio-api.md

````text
# 原音频到粗剪：千问 API 入口

Fred 在 2026-10-03 明确授权：后续把原音频交给本 Skill 处理时，默认使用已配置的阿里云千问 API，再按既有流程处理。授权范围是该任务提供的录音，不批量上传无关本地文件。不再默认操作剪映，也不使用 Paraformer；模型不可用时报告，不能静默换模型。

## 本地凭证与调用

- 固定模型 `qwen-audio-3.1-asr-flash-filetrans`。识别输入必须已完成自然人声处理和1.1倍速，返回的句级和词/子词时间属于这个加速后的源，不是最初原音坐标。不要换成没有词级时间的聊天转写接口。
- 私人凭证文件 `~/.config/fredtalk/private/dashscope-api-key`，目录 0700、文件 0600。不放进项目、Skill、Git、分发包、日志或截图；同步 Skill 不复制私人目录。使用者需要自行配置自己的密钥。
- 首次配置或更换密钥：`python3 skills/audio-subtitle-roughcut/scripts/qwen_asr.py configure`。隐藏输入，不把密钥放在命令行参数、shell history、普通配置或文档里。
- 前置依赖：本机 `python3`、`requests`、`ffmpeg`。缺失时报告，不自动改变全局环境。

由助手从本期最新稿件提取专名，生成本期 `asr-context.txt` 与 `asr-terms.json`（字符串数组）。上下文最多 400 字符，明确要求只按实际录音识别、保留语气词、重复、重说和半截起句。稿件用于专名与语义参考，不灌入整篇稿件让模型照抄，不以参考稿抹掉临场表达。示例命令的路径由本期实际目录替换：

```bash
python3 skills/audio-subtitle-roughcut/scripts/qwen_asr.py transcribe \
  --audio "/absolute/episode/03_制作过程/audio-preparation/voice-1.1x.wav" \
  --output "/absolute/episode/03_制作过程/qwen-asr" \
  --context "/absolute/episode/03_制作过程/asr-context.txt" \
  --terms "/absolute/episode/03_制作过程/asr-terms.json"
```

脚本不会替调用者自然处理或加速，须先完成下方准备步骤。脚本测峰值，必要时为整数FLAC转换降低固定增益，不再改变输入速度/时间轴；上传单声道避免重复声道计费。转换仅用于识别，粗剪声音使用同时间轴的voice-1.1x.wav而非上传FLAC。临时存储使用阿里云上传策略，不另建公开网盘。

同一命令、同一输出目录再次执行：已完成时复用结果；有任务 ID 时续查，不重复付费提交。提交超时且未拿到 ID 时保留 `submitting` 记录并停止，先查控制台，不能自动再次提交。网络错误不打印包含临时签名的完整 URL。更换音频或模型须新目录；需要重识别时先说明原因，不把重试当作免费动作。

输出 `raw-asr.json`、`source-asr.srt`、`word-timestamps.json`、`asr-state.json` 和 `asr-validation.json`。这些是原始识别证据，不能当作已经粗剪的最终字幕。API usage、整段时长、耗时和真实账单分开，不凭 token 数猜费用。保留的词记录可能含空格、英文子词，confidence=1 不代表正确率 100%。

## 接续处理顺序

1. 校对原音、最新稿件和原始识别覆盖；记录哈希、时长、声道。已有结果优先续做，别因 Skill 更新重跑旧工程。
2. 严格顺序：**原音 → 自然人声处理 → 1.1倍速 → 字幕识别 → 粗剪 → +8dB**。先用 `node skills/_runtime/remotion/codex-episode-1-xhs/scripts/audio-master-natural.mjs --no-deepfilter --input ... --output ... --report ...` 从原音产生本期自然人声文件，再用 `ffmpeg -i natural-voice.m4a -af atempo=1.1 -ar 48000 -ac 2 -c:a pcm_s16le voice-1.1x.wav` 输出识别与粗剪共用源，已存在文件不覆盖。随后才调用上方ASR命令。记录原音/自然处理/加速源的hash、时长、speedApplied=1.1和gainApplied=0（这里指最终+8dB尚未应用，不代表自然链无增益）。此自然链不含DeepFilterNet，也不是旧的afftdn/adeclick链；核对时长/延迟，不把自然处理夸称为新模型降噪。识别与自然处理不是并行支路。
3. 结合词级时间、波形、前后语义和稿件做完整口误初检：整段/整句重录、句内几个字重说、失败起句、残尾、跨 cue 断字及无关打断都检查；删前留后，保留后一次完整表达。不能只靠重复字符串自动剪。
4. 字幕校正与音频剪切分开。原稿中的明确专名、单位和识别错词可校正；Fred 明确说“按原逐字稿调整”时，以稿件解决该范围的争议文本，但不把全文改写成稿件，不因此再动声音。当前要求和手动修改优先。文本修好不代表声音里的重说已去掉，也不代表已经听过。
5. 全文按语义拆成长短适宜的顺序 cue；特别长的句子拆两条或更多条，利用词级时间核对断点，不拆专名、数字单位和固定词组。不只换行、缩字号；避免为追求短字幕造成碎片/短闪。空格子词、跨句词归属和真实发音仍需检查。
6. 展示字幕默认不保留中文逗号或普通英文逗号，尤其“一、第二、第三”后不加逗号；原始识别记录不改。小数点、百分号、数字千位分隔、型号和英文名称等有意义符号保留，不用全标点删除正则破坏它们。断句与显示去逗号分层，先确定语义边界再规范文字。
7. 数字沿用 Fred 的原稿/确认写法，如“3 件事情”“10 多轮”“两小时”；不把全部数字改成汉字，不把“第一、第二、第三”机械改成阿拉伯数字。按具体词组和稿件校对，禁止无条件全局替换“三”“十”。
8. 检查整条音频，不只看字幕间隔。约 0.5 秒自然停顿可保留，长段/章节转换可以稍长；句内明显拖长才收紧。多档低电平扫描结合上下文，阈值不能判断吞咽声或证明听感；删重说后同时检查旁边长空隙、口腔声和断字。
9. 粗剪后必须+8dB，即使自然链已归一化也不省略。新入口导出明确传 `python3 scripts/deliver.py --review ... --version v1 --speed 1 --trim-start 0 --gain-db 8`，不能沿用deliver默认1.1再次加速。片头按实际空隙写进cuts；ASR、cuts、分段全在voice-1.1x.wav坐标，不再把字幕除以1.1。按[工作流的真峰值检查](workflow.md#真峰值与对比交付)测真峰值、采样峰值和响度，超标有限次修正并补偿限幅延迟，记录最终gainDb=8、预处理speedApplied=1.1与实际测量，限幅后不声称每个采样精确提升8dB。已完成这两个步骤后返修才用passthrough，字幕单改严格复用音频hash。第108期旧试验版先识别原音且未追加+8dB，是历史试验，不是后续默认；规则更新不擅自重导旧版。
10. 输出可手调审片台、实际 WAV/SRT、切点/时间映射/修订记录。比较时保持旧版，另建独立结果和播放入口；比较时长、分段、文本、响度及待听项目，提供同句切换/同响度试听；旧剪点迁移先分布检查偏移与漂移。新ASR复核与显示分段重排分开说明。标点/空格归一化后的文本相似度不称识别准确率。网页播放文字、下载文件与 manifest 必须同版；旧识别差异表保留证据并另列“当前校正结果”，不要把已修字幕仍标待核对。

## 能力边界与验证

脚本自动完成上传、提交、续查、原始 SRT/词时间导出；不是全自动语义剪辑器。助手仍须按工作流生成本期 cuts、文字纠错、明确分段和成片导出。公共审片台的合并配置不自动实现词级拆分；需要本期导出脚本时保留实际分段配置，别写了规则就宣称公共脚本已有该功能。

自然链输出使用 AAC M4A 时，后续 WAV 不是全链路无损；需要无损母版须明确实现并验证，不能仅改扩展名。不要把第108期 41 刀、235 cue、专名或具体时码固化成后续配额。

验证原输入和旧交付未变；全音频解码、字幕时序和覆盖、长字幕/短闪检查、原音与处理版延迟、音量峰值/响度；网页播放、跳句、高亮、编辑保存、下载及版本一致。实际听审、技术通过和用户确认分别记录，无音频听审能力时如实标注。

## 剪辑与响度判定

ASR不是剪切授权或听审。识别多字/句内重复先按 [音频证据、残留与整条响度](audio-evidence-and-loudness.md) 分类，声音正确就只改字幕；已误剪时恢复真实声音，保留用户文字。导出既测整条指标，也查全时段局部响度和外部配音/补录内部变化，不因平均LUFS接近就跳过复查。
````

## File: skills/audio-subtitle-roughcut/references/verification.md
size: 1735
sha: 2e69ff8cc3487cbcc650e00f629682c90ac45ecb
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/references/verification.md

```text
# 本轮验证

2026-09-30：Skill结构检查与JavaScript语法检查通过。scripts/test_workflow.py在临时独立episode上验证初始化防覆盖、原输入hash不变、识别校正、手改字幕保留、删除失败重说、1.1倍速、自动片头空隙提案、+8dB限幅、WAV完整解码、字幕文字与时码映射以及最终文件HTTP接口。

初次接口测试仅读音频文件头后提前关闭连接，出现BrokenPipeError；改为完整读取后复测通过。全局目标目录首次检查不存在，随后新建同步；不是已有Skill被覆盖。

复用已有本期审片台，模板去除本期固定路径和候选。当前新模板未单独完成浏览器视觉或接缝听审，技术通过不等于听感通过；实际新一期须按主Skill执行前端检查和试听。第107期现有源码与已认可输出未修改。

2026-10-03：第102期复盘补入公共导出与模板。新增5项质量用例，连同原工作流/原音API测试共13项通过；包含真峰值独立测量、speed=1精确采样数、删指定第几次短词、禁用剪切恢复文字、传入未保存剪辑决定、手改文字优先、切点范围变化拒绝旧删词规则、额外未知切点仍提示复核。首次运行新用例有3项失败/1项错误，修复后全部通过。JavaScript语法检查通过。

公共模板在独立合成音频审片台验证启用/恢复、撤销/重做后字词立即同步。临时测试路径首次受macOS /private别名影响导致服务未启动，修正测试配置后通过；未改任何本期交付。测试不证明真实口播接缝听感，也未调用付费ASR。详细报告在项目`30_工具输出与实验记录/roughcut-quality-update-20261003/`。
```

## File: skills/audio-subtitle-roughcut/references/workflow.md
size: 18225
sha: 0d513f19e059578c16723d724b3abe03fe6ff8bf
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/references/workflow.md

````text
# 本地执行与数据合同

只有原音频时先按 [original-audio-api.md](original-audio-api.md) 执行原音→自然人声处理→1.1倍速→千问字幕识别→粗剪→+8dB。识别输入与粗剪源均为已加速音频，cuts与字幕也在该坐标；导出明确`--speed 1 --trim-start 0 --gain-db 8`，不再加速，片头空隙写进cuts。该入口含API授权、私人Key、去逗号、数字写法、按稿校正及版本保护规则。

init_review.py复制独立审片台，不覆盖既有实例。project.json保存本期标题、输入路径和hash；非48kHz双声道PCM16的媒体用本地FFmpeg规范化，原文件不改。

## 配置

- cuts.json：`[{id,start,end,title,reason,enabled,confidence,reviewed,originCutId?}]`，project.json的sourceAudio秒坐标。新入口是自然处理且1.1倍速后的源，不是最初录音坐标；已有工程沿用自己的源。说明删哪段、保留哪遍、判断依据；reviewed不等于enabled。行级恢复分拆跨句剪切时，禁用原记录，其他句仍需删除的区间保存为独立片段，`originCutId`追溯原剪切的字幕绑定。
- subtitle-corrections.json：`[{cue,from,to}]`，精准匹配原文，不匹配停止。
- subtitle-edits.json：用户单句文字覆盖，优先于自动校正。
- subtitle-boundaries.json：`[{cue,start?,end?,removePrefix?,removeSuffix?,prefix?,cutId?,cutRange?,removeInfix?,note}]`。同时维护字词和时间，记录估算/听审。例如上一句删尾“但”、下一句补“但”且起止接于同一时点，不能复制两遍或切掉发音。
- subtitle-sentences.json：相邻源cue ID合并组，不乱序/重叠，不跨任何候选起止，包括禁用候选。
- subtitle-joins.json：后一cue ID到逗号/顿号的映射；不把数字、模型名拆开。
- subtitle-sentence-edits.json：合并句文字覆盖，key是cue ID逗号串；sourceCueIds防止组改变后误写旧句。

保留originalText/originalStart/originalEnd和sourceCueIds。恢复校正版撤回手动文字覆盖；顶部撤销只管理剪切。外部修改原输入或server代码需重启，JSON调整后刷新。本期只有一套事实源。

### 行级恢复与重复剪切

- 字幕行的“恢复”恢复该行原始时间范围内的音频，不是清除手改字幕。一次处理全部重叠启用剪切，包括同句被重复删除的情况；已经完整覆盖的范围再次删除为无操作，不叠加刀或撤销记录。
- 使用originalStart/originalEnd，不能因为cutId绑定修订缩短了当前字幕边界，就漏恢复被删除的字头、字尾或整句。
- 某句cutId绑定剪切的声学字头可能略早于估算cue.start，或字尾稍晚。行级恢复可沿绑定剪切扩到相邻cue之间的空隙；前界不得早于上一cue的originalEnd，后界不得晚于下一cue的originalStart，既清掉该句字头的残刀，也不恢复相邻句内容。恢复范围不改变原字幕显示时码。
- 跨句剪切恢复当前句时保留两侧删除区间；其他句不会跟着恢复。分拆片段用originCutId沿用原绑定，server只在片段仍覆盖对应原始cue时应用其字幕修订。恢复当前句后该句绑定修订撤回，其他句的removePrefix/start等修订保持。
- 恢复、撤销、重做均按一轮操作更新cuts，保存后重新读取实际字幕；用户subtitle-edits和subtitle-sentence-edits不被音频恢复覆盖。恢复字幕手改仍使用编辑窗里的“恢复校正版”。
- 回归测试使用独立合成项目，覆盖重复刀、跨句恢复、绑定修订、HTTP保存/重载与撤销/重做；不得为了验证按钮改动正在制作的cuts、文字覆盖或成片。

## 先区分识别错误、声音错误与响度

所有音频处理和返修先读 [音频证据、残留与整条响度](audio-evidence-and-loudness.md)。句内短词只有ASR重复时先保留声音；用户确认是识别多字时只改字幕并撤回误剪。响度由整条连续窗口和实际角色分段核对，不能只凭全片综合值或某一张截图。

## 全篇停顿检查与返修保护

1. 以当前最终WAV和它的时间映射检查全篇，原音/现有剪切区间同时保留；SRT空白仅作线索，不代表真实静音。
2. 用短窗RMS/波形、多档阈值筛出候选，再逐个读前后字幕判断语义。记录当前成片时间、对应源音区间、可能的低声尾音、保留或缩短的理由。阈值检测不识别吞咽声，也不证明听感通过。
3. 约0.5秒的自然停顿通常可保留；句内明显停得过久需收紧，章节交接/演示可以稍长。不要把某期0.4/0.9秒或固定dB阈值当作全部录音的硬值。试听插入点、长段呼吸和语气词按内容保留。
4. 删除重复后复查接点前后是否残留吞咽、口腔声、半截发音或突兀空隙。微调时保护有效辅音/尾音；波形最低点不等于词边界。无法听审的边界标明估算。
5. 新切点仍记在原音坐标；重算后续字幕，不在已剪版本上重复变速。相对上一版证明只删了指定区间，其余保留PCM一致；有意淡化/交叉渐变时明确记录范围，不能再声称这些样本完全一致。
6. 只有字幕分段变化时复用音频路径及hash；如果需要同时删音频中的真实重说，单独列出新增音频剪切。旧版本、用户的手调覆盖及禁用候选保持。

## 导出

### 已处理音频与补录替换

先锁当前完整master、字幕、采样率与处理状态。用户说已做过加速/增益时按该输入只粗剪，明确speed=1、gainDb=0并使用passthrough；不重复自然链、变速或限幅。新补录是原音时仅对补录执行当前原音链，再与旧master替换邻域比较响度，必要时单独匹配；报告补录的+8dB、限幅及最终匹配衰减，不把匹配当作再次处理整条master。

替换清单写明旧master半开范围、新补录保留源范围、失败take和明确不替换的尾句；按采样边界拼接，保护此前已完成的替换。逐段记录源→成片映射与时长delta，字幕及下游画面/音效重新绑定受影响时间，不能按整段总时长比例挪cue。未替换的前后PCM独立比较；淡化或交叉渐变范围单列，不能声称该范围字节相同。接点需核对字头、尾音和前后语气，技术通过/波形估算不冒充听审。当前公共脚本不自动编排多次补录替换，实际拼接和映射保存在本期。

### 长字幕与句内漏检

导出前分开检查两类问题，不用“字幕时间合法”代替内容审查：

1. 全文检查长字幕，尤其是把多个源cue合并后的条目。按目标字幕区实际宽度、字体及阅读时间判断；中英混排考虑英文占宽，不能只数原始字符。明显过长时优先拆两条，在转折、递进、主从分句或列举项边界断开，避免拆开专名、数字单位和词组。不要为了语法整句而继续拼成长条，也不机械把所有字幕切碎。
2. 优先沿用原SRT中合理的语义时间边界。需要句内拆分时核对音频/波形或已有词级对齐；只能估算时记录估算，不宣称逐字同步。拆分后的串联文字与原条目一致，首尾时间覆盖不变，时序不重叠，无空条或不合理短闪。字幕单改时音频文件hash必须不变，不重新应用加速、增益或限幅。
3. 逐条检查句内短词和相邻cue首尾，结合稿件找错词后重说、局部重复、起句残片、句尾多字和跨句错归属。稿件用于识别语义，不覆盖实际临场表达。明确是识别错字时只校正字幕；实际说错后重说则删前留后，声音、字词与边界一起修。证据不足的词不得猜改，但用户已经明确指出的重复不能继续以“待试听”原样留在导出中。
4. 保存本期分段决定及源cue/时间映射，后续再导出应复用，不能被自动合并还原为长字幕。当前模板的subtitle-sentences.json仅支持合并；需要句内拆分时在本期导出流程保存明确的分段配置/脚本，不伪称公共模板已支持自动语义拆分。
5. 全文复查不得止于拆分前：重新计算合并/拆分后的占宽、阅读时长和邻接关系，字幕条目中不能靠\n或缩字号伪装成先后两条。拆分前后串联字符一致；人工确认的错字校正单独列例外。不把某期字符上限或拆分数量固化为所有字幕的配额。
6. “跟、把、和、就、这些”等连接成分按语义放到对应分句；调整前条末尾、后条开头和时间边界，避免漏字/重字/断开词组。句级时间估算不称词级对齐。若文字修订依赖某条剪切，恢复该剪切时必须连同文字归属恢复；公共模板现支持cutId条件生效：禁用/恢复剪切时同步恢复原字词，前端保存后重新载入文字；具体句内删词配置见下文。
7. 核对实际最终SRT、final-delivery.json和网页播放显示一致，并检查拆分前后两条按时间先后切换。技术校验、听审和用户认可分别记录。

例：将“但是大家如果本身用不了Claude Code用的是Codex或者国内的Agent或者模型”拆为“但是大家如果本身用不了Claude Code”与“用的是Codex或者国内的Agent或者模型”。例子只说明语义断点，不作为未来固定文案或时码。

deliver.py复用审片台合并区间、保留片段与文字逻辑。按Fred最新要求，默认speed=1.1、gain-db=8、片头波形阈值提出空隙裁点（需试听，不固定1秒）；--trim-start手动覆盖。需要保持现有处理结果时用`--passthrough`，从审片台粗剪WAV直接复制PCM；这与仅传`--speed 1 --trim-start 0 --gain-db 0`不同，后者仍会限幅。只剪切模式的片头编辑写进cuts.json，禁止额外变速/增益/自动片头裁切。已存在版本拒绝覆盖。输出WAV/SRT到02_最终输出，decision/验证到制作过程，final-delivery.json指向实际最新成片。

时间公式 `newTime = roughCutTime / speed - trimStart`，不重复对已加速版加速。音量不改时间，限幅补偿延迟。剪掉的字幕不导出，跨句内裁点的文字需校对；export的subtitleReview不为空时不能宣布字幕已经最终正确。

verify_delivery.py核对解码、采样数/时长、SRT连续编号/非负/不越界、字词与时间映射、原输入hash。实际浏览器另查两个播放器不叠播、版本/下载/缓存不读旧文件、1.1倍已应用时播放器默认1×。技术验证不等于接缝听感。

历史粗剪任务曾因音频工具不能接收音频而未听审。当前默认原音识别已按Fred授权改为千问Audio 3.1，不调用Paraformer；音频听审能力按本次工具实际判断，不把历史失败固化成永久限制，也不把词级时间冒充听审。

## 版本与检查结果

- 前端完整播放、字幕、下载链接和版本信息必须指向当前导出；保存审查修改不等于已经更新成片。展示未导出状态，导出后刷新实际文件；只有新版本内容或具体剩余风险需要复检时才扩大检查。
- 术语优先使用Fred本期明确纠正的写法，同步字幕及待核对说明；项目名、模型名、价格只保留本期记录，不硬编码到公共替换词典。
- 保留`technicalPass`、`listeningReviewed`和用户认可各自的真实状态；重说候选/价格文字无法精确定位时列出待处理范围，不伪称全部清除。

## 句内剪切与字幕联动

`subtitle-boundaries.json` 可把文字修订绑定 `cutId`。该剪切启用时应用，禁用或移除时恢复；用户手改文字仍有最高优先级。删句中间的短词使用以下结构，例中的词与时间须替换为本期核实的内容：

```json
{"cue": 1, "cutId": "repeat", "cutRange": [0.4, 0.7], "removeInfix": {"text": "重复短词", "occurrence": 1}, "note": "本期词级记录、波形与听审状态"}
```

- `occurrence` 从1开始，针对该条修订应用前的文字。重复词必须指定删第几次，不能全局替换；多条修订按数组顺序应用。
- `cutRange` 与实际剪切区间须在1个采样内一致，且位于该cue内部。手调切点后必须重新核对并更新范围；范围不匹配时保存/导出报错，避免旧删词决定继续生效。禁止为了消除报错机械复制未经核对的切点。
- 导出对经过明确删词核对的同一cue，把切点两边剩余文字合成一次连续显示，避免重复整句或短闪。遇到未绑定的新剪切仍报`subtitleWarnings`，不能被已核对的另一刀掩盖。
- 恢复这刀、撤销、重做时同时检查字幕恢复。手动文字覆盖不会被撤销剪切自动丢弃，需按当前用户意图核对。
- 行级恢复产生的originCutId片段只对仍覆盖的cue延续绑定。removeInfix仍要求实际启用片段与cutRange在一个采样内一致；恢复后范围若不一致继续报错，不能借分拆绕过词边界复核。已匹配的infixCutIds使用实际片段ID，保持导出中的字幕审查准确。
- 原始cutId仍启用时保持既有条件语义，允许前后相邻cue的字词归属修订及声学边界落在ASR空隙。仅originCutId分拆片段限制到仍删除音频的cue。手调绑定前缀/后缀刀后仍须重核该句文字与start/end；当前精确cutRange校验只覆盖removeInfix，不能将前后缀的旧边界当作已重新对齐。
- 这项功能处理明确的句内删词，不自动完成语义分句或声学逐词定位。完整导出后仍检查长字幕和短闪。

## 词时间与旧剪点迁移

词级ASR提供位置候选。结合发音包络和前后文复核字头/尾音；模型把停顿算进词、把字头放晚或多识别一个重复词时，不能直接照时间切。波形能辅助找低能量接点，不能单独证明说了哪个字。实际重复和识别重复分开记录；无法确定时列准确短段、保留/删除状态与不确定原因，不假称听过。

从原音重新处理但沿用旧剪辑时，在开头、中间、结尾及关键剪点附近比较新旧源的同一内容。记录各位置的偏移及检查方法，区分固定延迟与累积漂移；明显漂移要按内容重新映射，不能只用总时长比例或一个起点平移全部剪点。迁移后检查声音边界、字幕与源→成片映射；旧版不覆盖。本期10ms等数值留在本期，不作为Skill默认。

## 真峰值与对比交付

普通处理导出由`audio_qc.py`测综合响度、真峰值和采样峰值；`verify_delivery.py`另用`loudness_profile.py`生成全片连续响度、角色分段和字幕窗口摘要，具体候选判断/局部匹配见[声音与响度参考](audio-evidence-and-loudness.md#整条响度不能只看一个lufs)。`deliver.py`跳过speed=1的atempo，使用带延迟补偿的过采样限幅；不变速时保持精确采样数。默认真峰值目标-1dBTP、测量容差0.05dB，先预留0.5dB余量，若超标最多本地调整3次。失败不发布新final-delivery；根据实际录音与交付规格改参数并核验，不重复ASR。元数据保留每轮参数与测量；`verify_delivery.py`独立重测目标。`--passthrough`只测量、记录，不限幅或改变PCM。

+8dB是增益设置；报告实测LUFS变化和动态范围，限幅会改变实际增幅。延迟补偿配置不代表听审，变更处理链时用波形/脉冲核对同步；字幕单改继续复用原音频hash。

用户要求新旧比较时，前端按对应语句或源时间映射切换，提供同响度试听（仅衰减较响版本，不改下载文件），并可切回原始响度。明确对比固定的两个版本，或在重新导出时同步更新音频、字幕、指标、映射和下载；不能播放新版却沿用旧指标。

交付分别说明四类变化：文字纠错/删词、显示分段与每屏长度、字幕时间、声音处理。新ASR用于复核而保留旧分段时如实写明；不把词级识别成功说成字幕呈现已升级。A/B页面仍由本期按需要实现，公共模板尚不自动生成对照页。

## 公共审片模板与视频台连接

音频前端固定复用assets/review-app，init_review.py只复制代码和空状态，再绑定当前音频/SRT/稿件。project.json及新导出的最终WAV/SRT索引使用相对review目录路径；既有绝对路径配置继续可读，不改冻结旧期。输入在期外且需要独立携带时显式加--copy-inputs，复制到审片台inputs；这不包含付费API、重处理录音或复制私人配置。新目录/输入先核hash，不能把107/108旧切点、反馈或聊天当默认数据。

主视频Skill的serve_review_app.py可同时启动音频和视频模块，用--audio-review指向这里，两页互相链接；已有单独音频服务继续按原server.py启动。音频完整页显示真实已导出版本、语速/音量处理和接缝听审状态，字幕点击跳转与倍速不改最终文件。未导出的编辑只显示在字幕审查，不冒充完整页已更新。制作中继续保持同一台，不用模板更新覆盖cuts或手改字幕。

局部PCM返修的final-delivery可保留`processingMode: bounded-pcm-revision`及`inheritedProcessing`，记录此前已完成的gainDb等处理。完整页显示实际继承增益及一句局部返修说明；本轮speed=1/gainDb=0/passthrough表示不重复处理整轨，不能显示成原音没有加过速或增益。

公共index.html的app.js/styles.css资源URL带当前内容hash版本，静态HTML/JS/CSS响应使用Cache-Control:no-cache，防止同一审片端口继续显示旧按钮或旧处理说明。版本参数只影响前端代码，音频hash URL及媒体缓存策略保持。同步代码时一并更新index.html，不覆盖本期配置。

108真实示例位于主Skill的 `assets/review-example-ep108/`，用同一公共音频台展示61.47秒、已处理PCM及对应字幕；整期粗剪已完成，示例初始cuts为空，不重新加速/增益，不冒充重新听审。用START.py同时启动两个模块。完整可复用功能在公共模板源码维护，示例仅承载数据。
````

## File: skills/audio-subtitle-roughcut/assets/review-app/app.js
size: 22896
sha: d3a53da768975c3fb7437ed579bdd6ebd1216d61
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/assets/review-app/app.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/assets/review-app/app.js

## File: skills/audio-subtitle-roughcut/assets/review-app/index.html
size: 4722
sha: 046e00cc572278b8987485cda431c80d6c4812be
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/assets/review-app/index.html

```text
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>音频和字幕粗剪</title><link rel="icon" href="data:,"><link rel="stylesheet" href="styles.css?v=43f2df97339a"></head>
<body>
<header><div class="identity"><i data-lucide="audio-lines"></i><div><strong>音频和字幕粗剪</strong><small>口误初检 · 原始录音保留</small></div></div><div class="actions"><a id="media-review-link" hidden>关键帧与视频 →</a><span id="saveStatus">正在载入</span><button id="undo" title="撤销" aria-label="撤销"><i data-lucide="undo-2"></i></button><button id="redo" title="重做" aria-label="重做"><i data-lucide="redo-2"></i></button><button id="export" class="primary"><i data-lucide="download"></i>导出初剪</button></div></header>
<div class="workspace"><main><div class="sectionbar"><div class="tabs"><button id="finalTab">完整成片</button><button id="transcriptTab" class="active">字幕审查</button><button id="scriptTab">参考逐字稿</button></div><input id="search" type="search" placeholder="搜索字幕" aria-label="搜索字幕"><label><input id="onlyCuts" type="checkbox">只看候选</label></div><div class="summary"><span id="stats"></span><span class="legend"><b class="gray"></b>拟删除 <b class="amber"></b>待试听</span></div><div id="transcript" class="transcript"></div><pre id="script" hidden></pre><section id="finalPreview" hidden><div class="final-player"><div class="final-heading"><div><h1>完整音频</h1><p id="finalInfo">正在载入导出文件</p></div><div class="final-downloads"><a href="/final/audio.wav" download="review-final-audio-v1.wav"><i data-lucide="download"></i>音频</a><a href="/final/subtitles.srt" download="review-final-subtitles-v1.srt"><i data-lucide="file-text"></i>字幕</a></div></div><div id="finalCaption" aria-live="off">完整音频</div><audio id="finalAudio" controls preload="metadata"></audio><div class="final-options"><label><input id="followFinal" type="checkbox" checked>跟随播放</label><select id="finalSpeed" aria-label="成片播放速度"><option value="0.75">0.75×</option><option value="1" selected>1×</option><option value="1.25">1.25×</option><option value="1.5">1.5×</option><option value="2">2×</option></select><span id="finalClock">00:00.000</span></div></div><div id="finalTranscript"></div></section></main>
<aside><div class="sectionbar"><strong>剪切审查</strong><span id="count"></span></div><div id="inspector"></div><div class="listbar"><span>候选片段</span><select id="filter" aria-label="筛选候选"><option value="all">全部</option><option value="pending">待试听</option><option value="enabled">已启用</option></select></div><div id="cutList"></div></aside></div>
<footer><div class="transport"><div class="playgroup"><button id="play" class="round" title="播放 / 暂停" aria-label="播放"><i data-lucide="play"></i></button><span id="clock">00:00.000</span><small id="editedClock"></small></div><div class="segments"><button id="original" class="active">原音</button><button id="edited">初剪</button></div><div class="zoom"><i data-lucide="zoom-in"></i><input id="zoom" type="range" min="1" max="12" step="1" value="1" aria-label="波形缩放"></div><button id="add"><i data-lucide="scissors"></i>新增剪切</button></div><div id="waveScroll"><canvas id="wave" height="120"></canvas></div><div class="rangebar"><label>选区起点 <input id="rangeStart" type="number" min="0" step="0.01" value="0"></label><label>终点 <input id="rangeEnd" type="number" min="0" step="0.01" value="1"></label><span id="notice">句级字幕初检，未完成听审。句内标灰为估算。</span></div></footer>
<dialog id="subtitleDialog" aria-labelledby="subtitleTitle"><form id="subtitleForm"><div class="dialog-head"><strong id="subtitleTitle">编辑字幕</strong><button type="button" id="closeSubtitle" aria-label="关闭字幕编辑" title="关闭"><i data-lucide="x"></i></button></div><label for="subtitleText">字幕文字</label><textarea id="subtitleText" maxlength="2000" rows="4" required></textarea><div class="original-caption"><span>原始识别</span><p id="subtitleOriginal"></p></div><p id="subtitleError" role="alert"></p><div class="dialog-actions"><button type="button" id="resetSubtitle"><i data-lucide="rotate-ccw"></i>恢复校正版</button><button type="button" id="cancelSubtitle">取消</button><button type="submit" id="saveSubtitle" class="primary"><i data-lucide="check"></i>保存</button></div></form></dialog>
<div id="toast" role="status"></div><script src="vendor/lucide.min.js"></script><script src="app.js?v=96ea4dae2789"></script></body></html>
```

## File: skills/audio-subtitle-roughcut/assets/review-app/server.py
size: 19790
sha: b26a045c01986797f983f975c4f626026e614e12
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/assets/review-app/server.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/assets/review-app/server.py

## File: skills/audio-subtitle-roughcut/assets/review-app/styles.css
size: 10798
sha: cd77492652c4f111b53c1c09b8d077df5af47d5f
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/assets/review-app/styles.css

Content is not inlined in the catalog. Read the upstream file: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/assets/review-app/styles.css

## File: skills/audio-subtitle-roughcut/agents/openai.yaml
size: 447
sha: 0dea5f0c5256cd5f03abc511cb2e748426b3372a
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/agents/openai.yaml

```text
interface:
  display_name: "音频和字幕粗剪"
  short_description: "原音千问转写、自然人声处理与保留口播语气的可视化粗剪"
  default_prompt: "使用 $audio-subtitle-roughcut，按原音→自然人声处理→1.1倍速→千问Audio 3.1字幕识别→粗剪→+8dB执行；字幕时间与cuts使用已加速源坐标，粗剪导出不再加速。结合逐字稿校正分段，交付审片台与同步音频字幕。"
```

## File: skills/audio-subtitle-roughcut/requirements.txt
size: 20
sha: f10d2d4fc3dab262eac42f6cb7aae2a515a337f7
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/skills/audio-subtitle-roughcut/requirements.txt

```text
requests>=2.32.5,<3
```

## File: README.md
upstream: https://github.com/njrhts2kvv-star/fredtalk/blob/main/README.md

````text
<div align="center">

# FredTalk 2.5

### 用 Codex，把口播稿变成动态视频。

视频制作 Skill · 可检索视觉库 · 关键帧与音频审看

[**浏览在线视觉库 ↗**](https://www.fred-fu.com/visual-library) · [快速开始](#快速开始) · [使用 Skill](#使用-skill) · [English](README.en.md)

</div>

FredTalk 是我在日常视频制作中打磨的一套工作流程。把稿件、录音和素材交给 Agent，让它逐句选择画面、适配组件、生成关键帧，再完成动画、声音与视频输出。

你可以先在网页里看效果，也可以把仓库下载到本地，让 Codex 或其他编程 Agent 读取 Skill，开始制作自己的视频。

## 2.5 更新 · 2026-10-18

**整期编排与录屏表达升级。** 新增 47 条成片场景、8 条录屏操作组件、9 条章节过渡，更新 32 条历史组件；加入逐句动作表、好坏对照样例、可读性检查和更完整的整期骨架。

- **32 条历史返修版立即公开**：非会员也可获取源码、源码 ZIP 和原视频。
- **其余 64 条专属会员抢先 14 天**：发布满 14 天后，网站自动向所有人开放；此前批次日期保持。
- **场景按内容适配**：47 条回收场景保留真实场景代码，使用自己的文字、素材和口播时间修改。

[查看 2.5 完整说明](docs/releases/2.5.md) · [FredTalk 2.5 Release](https://github.com/njrhts2kvv-star/FredTalk/releases/tag/v2.5.0)

## 2.1 更新 · 2026-10-14

新增 **20 条组件**：10 条章节动画和 10 条内容进场／交接动画，按实际用途检索。

- **T12k–T12t**：章节序号、标题揭示与章节过渡。
- **T20i、T20j**：可用于开场，也可用于内容交接。
- **其余 8 条 T20 动画**：主要用于内容过渡，并按真实动作标记媒体进场、作品展示、问答和数字等用途，不作为默认开场推荐。
- **会员优先使用 14 天**：公开展示预览；源码、原视频和源码 ZIP 经网站登录下载，交给 Codex 后可直接校验安装。本批北京时间 10 月 14 日 08:59:11 开始，10 月 28 日 08:59:11 向其他用户开放下载。

[查看 2.1 更新说明](docs/releases/2.1.md) · [查看 2.1 Release](https://github.com/njrhts2kvv-star/FredTalk/releases/tag/v2.1.0)

## 2.0 更新 · 2026-10-13

这次升级围绕一件事：让 Codex 找到组件、认真选型，再把画面接成一条完整视频。

- **组件能找到了**：修复检索链路，“数据、价格、要点、代码终端”等常见说法参与匹配，制作和视觉库共用登记数据。
- **新组件有机会被用上**：同等匹配度下按来源批次轮流排，让新批次进入候选列表。
- **每段都认真挑**：当前前三候选用或不用，都写具体理由；门禁重新计算并拦截漏比较，不能直接退成大字页。
- **整期有规则**：录屏聚焦、对象交接、阅读停留、组件去重和动态自检一起执行；音效按整期限量，BGM 在原声欣赏区让位。
- **渲染与声音更稳**：上传断线续传、分块超时重试、口播与音效分轨、混音峰值保护和最终 AAC 复测。

本次 GitHub 新增 **106 条组件**，网站新增 **105 条**；最新组件置前标 **NEW**，**114 条**已归档组件在页面底部保留。

[查看 2.0 完整更新说明](docs/releases/2.0.md) · [下载公开组件与素材](https://github.com/njrhts2kvv-star/FredTalk/releases/tag/v2.0.0)

## 画面预览

从文字强调、步骤讲解，到录屏聚焦和作品展示，按你要表达的内容选择画面。点击[在线视觉库](https://www.fred-fu.com/visual-library)可播放预览、筛选场景，并按公开或抢先权限查看源码。

<table>
<tr><td width="25%"><img src="docs/assets/T05h.jpg" alt="一次性拷贝 vs 持续同步" width="240"><br><sub>T05h · 一次性拷贝 vs 持续同步</sub></td><td width="25%"><img src="docs/assets/T15e.jpg" alt="折线走势" width="240"><br><sub>T15e · 折线走势</sub></td><td width="25%"><img src="docs/assets/T17b.jpg" alt="终端运行：命令执行、输出滚动、结果行点亮" width="240"><br><sub>T17b · 终端运行：命令执行、输出滚动、结果行点亮</sub></td><td width="25%"><img src="docs/assets/T03e.jpg" alt="步骤折行串起" width="240"><br><sub>T03e · 步骤折行串起</sub></td></tr>
<tr><td width="25%"><img src="docs/assets/T08i.jpg" alt="毛玻璃要点卡" width="240"><br><sub>T08i · 毛玻璃要点卡</sub></td><td width="25%"><img src="docs/assets/T10a.jpg" alt="长回复拎要点" width="240"><br><sub>T10a · 长回复拎要点</sub></td><td width="25%"><img src="docs/assets/T09l.jpg" alt="复制地址交给 AI" width="240"><br><sub>T09l · 复制地址交给 AI</sub></td><td width="25%"><img src="docs/assets/T14c.jpg" alt="价格落定：数字逐位滚动，旧价划掉，差额亮出" width="240"><br><sub>T14c · 价格落定：数字逐位滚动，旧价划掉，差额亮出</sub></td></tr>
</table>

## 能做什么

- **按内容选画面**：根据每句口播，在文字、流程、对比、设备、录屏和作品展示中选择合适的表达。
- **改成你的内容**：结合组件源码，替换文字与素材，调整布局、动作和口播节奏。
- **先看关键帧，再做视频**：用真实内容确认画面，支持随音频查看关键帧、逐段记录修改意见。
- **完成视频输出**：通过 Remotion 合成画面，检查动态、声音和段落衔接后导出视频。
- **处理录音与字幕**：可选用音频字幕粗剪 Skill，整理录音、纠正字幕并检查剪切位置。

## 怎么制作一条视频

| ① 准备内容 | ② 确认画面 | ③ 输出视频 |
| :--- | :--- | :--- |
| 提供口播稿、录音和图片／录屏素材 | Agent 给出逐段建议，从视觉库选择组件，并生成真实内容关键帧 | 按反馈调整，检查动画、声音和衔接，渲染完整视频 |

制作时可以逐段修改，也可以沿用已经确认的方案继续推进。

## 快速开始

**只想先看效果？** 直接打开[在线视觉库](https://www.fred-fu.com/visual-library)，无需安装。

**想在本地使用？** 准备 Python 3.11+、Node.js 22+、npm 和 Git，然后运行：

```bash
git clone https://github.com/njrhts2kvv-star/FredTalk.git
cd FredTalk
cd apps/library
npm ci
npm run build
cd ../..
python3 scripts/library_server.py
```

打开 [http://127.0.0.1:3061/design/](http://127.0.0.1:3061/design/)。端口被占用时，加上 `--port 3063`。

### 下载预览与素材

仓库直接附带[日常使用的五个字体家族](library/fonts/README.md)和少量示例，克隆后即可使用字体；公开组件预览与其他制作素材通过 GitHub Release 下载；抢先组件通过网站授权下载。先查看体积，再按需安装：

```bash
python3 scripts/assets.py status
python3 scripts/assets.py download
python3 scripts/assets.py verify
python3 scripts/assets.py materialize
```

下载工具需要 [GitHub CLI](https://cli.github.com/)。更多安装选项见[素材安装说明](docs/assets.md)。

### 14 天专属会员抢先

首批 16 条、第二轮 42 条与补充 5 条、第三轮 40 条与补充 2 条，共 105 条新组件，提供 14 天专属会员抢先下载。普通会员不含抢先权限；窗口结束后公开获取。准确开始与公开时间在[在线视觉库](https://www.fred-fu.com/visual-library)显示。

公开组件继续从 GitHub 下载，新闻关键词快闪 NMC01 仍公开。抢先组件的源码 ZIP、源码和原画质素材通过网站的会员权限获取。

**最简单的用法**：登录网站下载源码 ZIP，把文件拖入 Codex，再粘贴组件详情里“复制给 Codex”的说明。Agent 会校验并安装已有的本地包，你无需配置网站令牌或手动输入终端命令。

Agent 使用的本地导入入口：

```bash
python3 scripts/assets.py import --zip /path/to/downloaded-source.zip
```

导入会按大小和 SHA-256 自动识别官方批次，安装到 Git 忽略的隔离目录；实际文件验证通过后，组件才进入可执行候选。它不读取会员凭证、不请求网络，也不重复下载 ZIP。需要批量自动下载时，仍可选择[网站读取授权](https://www.fred-fu.com/visual-library/access)；详细方法见[素材安装](docs/assets.md)。

本次下载渠道调整不撤回此前已经授予的 MIT 许可，已有副本仍可依原许可使用、修改与再分发。

## 使用 Skill

在下载好的仓库中，让 Codex 或其他编程 Agent 读取 [`skills/fred-remotion-output/SKILL.md`](skills/fred-remotion-output/SKILL.md)。保留仓库目录结构，方便 Agent 找到组件、素材和工具。

可以从这句话开始：

> 请读取 `skills/fred-remotion-output/SKILL.md`。这是我的口播稿、录音和素材。请根据每段内容，从视觉库选择合适的组件，展示参考并说明理由。方向确定后，生成真实内容关键帧供我检查，再继续制作视频。

音频和字幕处理入口：[`audio-subtitle-roughcut`](skills/audio-subtitle-roughcut/SKILL.md)。

### 按用途查找组件

```bash
python3 scripts/catalog.py --use explain --query "三个要点列表" --limit 3
python3 scripts/catalog.py --query "两个工具价格对比" --limit 5
python3 scripts/catalog.py --id SP024 --full
```

查询结果包含预览、源码位置和使用说明。组件适配方法见[源码使用指南](docs/reuse.md)。

## 更多文档

[素材安装](docs/assets.md) · [源码使用](docs/reuse.md) · [项目结构](docs/architecture.md) · [参与贡献](CONTRIBUTING.md)

## 许可

FredTalk 原创代码、Skill、模板与文档采用 [MIT License](LICENSE)，允许商用、修改和再分发，并按 MIT 要求保留版权与许可声明。

第三方代码、参考复刻工程、字体、音效、图片、录屏、视频及品牌素材继续按各自原许可或授权使用。具体范围见 [许可范围](docs/license-scope.md) 与 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。

新增组件的个人录屏、人物独立素材不随源码包提供；需要自备的输入路径见各包 `user-media-inputs.json`。预览保留认可画面，使用自己的素材后仍需检查实际输出。

抢先时间：北京时间 **2026-10-13 11:15 至 2026-10-27 11:15**（UTC `2026-10-13T03:15:00.000Z` 至 `2026-10-27T03:15:00.000Z`），共 14 天，适用于上述五个批次的专属会员下载。

此前公开的源码仍能从历史 commit/tag 获取，已有 MIT 授权保持。后续新批次从第一天采用私有源码、ZIP 与原片，只公开目录、海报及标明身份的派生预览；具体流程见[素材安装](docs/assets.md)。
````
