Cotton code
115 lines · 4.5 KB · PythonRaw
#!/usr/bin/env python3"""Cut one recording of the whole script into one file per line, on its pauses.    split.py <recording> <script.json> <out-dir>The owner reads the script's lines in order into one Voice Memo with a ~2 spause between lines. This converts it (afconvert, any format Core Audio reads,m4a included) to 16 kHz mono PCM, finds the pauses, and writes u01.wav … uNN.wavin order. It REFUSES — writing nothing — unless it finds exactly as many spokenstretches as the script has lines, and says how many it found and how long eachwas, because a line matched to the wrong audio would score as a dictation error.The recording is read in place and the cut files go to <out-dir> only; nothingof it is printed but counts and durations."""import arrayimport jsonimport mathimport subprocessimport sysimport tempfileimport wavefrom pathlib import PathRATE = 16000FRAME = 320  # 20 msPAD = 0.25  # seconds of the pause kept either side of a lineSHORTEST = 0.4  # a stretch shorter than this is a click or a breath, not a line# The shortest pause that separates two lines. The owner is asked for ~2 s; a# pause inside a sentence is well under 1 s. The cut tries the asked-for pause# first and loosens only until the count matches, and says which it used.GAPS = [1.5, 1.4, 1.3, 1.2, 1.1, 1.0, 0.9, 0.8, 0.7]def pcm(recording: Path) -> array.array:    with tempfile.TemporaryDirectory() as tmp:        wav = Path(tmp) / "all.wav"        subprocess.run(["afconvert", "-f", "WAVE", "-d", f"LEI16@{RATE}", "-c", "1", str(recording), str(wav)],                       check=True, capture_output=True)        # afconvert writes WAVE_FORMAT_EXTENSIBLE, which `wave` will not        # open: the samples are the `data` chunk, 16-bit little-endian mono.        data = wav.read_bytes()        at = 12        while data[at:at + 4] != b"data":            at += 8 + int.from_bytes(data[at + 4:at + 8], "little")        size = int.from_bytes(data[at + 4:at + 8], "little")        samples = array.array("h", data[at + 8:at + 8 + size])    return samplesdef levels(samples: array.array) -> list:    out = []    for i in range(0, len(samples) - FRAME + 1, FRAME):        chunk = samples[i:i + FRAME]        rms = math.sqrt(sum(s * s for s in chunk) / FRAME) or 1.0        out.append(20 * math.log10(rms / 32768))    return outdef stretches(db: list, gap: float) -> list:    """[(first frame, last frame)] of speech, pauses of at least `gap` seconds between."""    ordered = sorted(db)    floor = ordered[len(ordered) // 10]    loud = ordered[int(len(ordered) * 0.95)]    threshold = floor + max(6.0, 0.25 * (loud - floor))    voiced = [d > threshold for d in db]    need = int(gap * RATE / FRAME)    found, start, quiet = [], None, 0    for i, v in enumerate(voiced):        if v:            if start is None:                start = i            quiet = 0        elif start is not None:            quiet += 1            if quiet >= need:                found.append((start, i - quiet))                start, quiet = None, 0    if start is not None:        found.append((start, len(voiced) - 1 - quiet))    shortest = int(SHORTEST * RATE / FRAME)    return [(a, b) for a, b in found if b - a + 1 >= shortest]def main() -> None:    recording, script, out = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])    lines = len(json.loads(script.read_text())["utterances"])    samples = pcm(recording)    db = levels(samples)    tried = []    for gap in GAPS:        found = stretches(db, gap)        tried.append((gap, len(found)))        if len(found) == lines:            break    else:        counts = ", ".join(f"{n} at a {g:.1f} s pause" for g, n in tried)        sys.exit(f"[voice] REFUSED: the recording ({len(samples) / RATE:.0f} s) has no cut into {lines} lines "                 f"— found {counts}. Re-record with a clear ~2 s pause between lines and none inside one.")    out.mkdir(parents=True, exist_ok=True)    pad = int(PAD * RATE)    for n, (a, b) in enumerate(found, 1):        first = max(0, a * FRAME - pad)        last = min(len(samples), (b + 1) * FRAME + pad)        with wave.open(str(out / f"u{n:02d}.wav"), "wb") as w:            w.setnchannels(1)            w.setsampwidth(2)            w.setframerate(RATE)            w.writeframes(samples[first:last].tobytes())    durations = " ".join(f"{(b - a + 1) * FRAME / RATE:.1f}" for a, b in found)    print(f"[voice] cut {len(found)} lines at a {gap:.1f} s pause; seconds each: {durations}")if __name__ == "__main__":    main()