Case study / AI at work / Her Mind & Wellness

Every article, a podcast episode.

Some people will not read a 1,500-word guide but will listen to it on the drive home. So every clinician-approved guide in the Her Mind & Wellness library became an episode of its own podcast: two AI voices talking the guide through in its exact words. Nobody records anything, the voices cost nothing, and a check proves each episode says what the guide says and nothing else.

Hear the live show ↗Get the skill and code
After: The same guide as a two-voice podcast episode, in its own approved words. Before: A 2,400-word guide that busy readers never finish.

BeforeA 2,400-word guide that busy readers never finish.

AfterThe same guide as a two-voice podcast episode, in its own approved words.

What it is worthEvery approved article becomes an episode, word for word. The feed updates itself. Instead of recording every article yourself, or paying for AI voices by the minute.

More like this: get hours back every week ›

33episodes live, one for every published guide
2.8hours of audio, about 5 minutes an episode
100%word for word: all 85 scripts, live and drafted
$0for voices: free, open-source, no per-minute fees
0minutes recorded by the clinician

Counted from the practice's repository and its live podcast page on November 20, 2026. From the first "listen to this guide" button to 33 live episodes took under a day. Listener numbers are not tracked, so none are claimed. The guides themselves are drafted with the expert-reviewed article writer ›

Hear it

A 66-second sample, made with the free code below.

The article is made up, about watering a desert garden. The episode is exactly what listen.py made from it: script, check, voices. Grey words are filler; framed lines are the fixed welcome and closing. Every other word is the article's.

Read the script
  1. BellaWelcome to Listen. We're two AI voices, and in each episode we talk through one article in its own words.
  2. HeartToday's article: Watering a desert garden
  3. BellaMost desert plants die from too much water, not too little. Water deeply and less often, so roots grow down toward cooler soil.
  4. HeartLet's start here: When to water.
  5. BellaWater early in the morning, before the sun is high. Less water is lost to the air, and leaves dry before night.
  6. BellaYeah, and let the soil dry out about two inches down between waterings. In summer that might be every three or four days; in winter, every two weeks.
  7. HeartCheck with your finger before you water.
  8. BellaSkip a day after a good rain.
  9. HeartPlus: Water the soil, not the leaves.
  10. HeartNext up: Signs of too much water.
  11. BellaYellow leaves, soft stems and a sour smell from the soil all point the same way. Stop watering and let the soil dry before you try again.
  12. BellaThat was the whole article, word for word. The full text and its sources are on our website.

Match check: 100% word for word, 100% coverage. The article's source list is for reading and is not spoken.

01 / The problem

Audio for a health practice, without a single unreviewed sentence.

02 / How it works

Five pieces, from approved guide to podcast app.

Tap a piece to open it. Screens marked DEMO are redrawn with invented data.

01ScriptAssembled, not written

The conversation is built from the guide's own sentences, in order. The co-host raises each heading, the two voices take turns on paragraphs and list items, and a short "Mm-hm" or "Okay, so" keeps it sounding like two people talking.

Only five lines are fixed text, the same in every episode: the welcome that says the hosts are AI voices, the guide's title, a question and a short note about the practice, and a closing safety line with the crisis and emergency numbers.

The script is seeded by the guide's words, so the same text always gives the same script. Republishing an unchanged guide reuses its audio instead of voicing it again.

02Match checkWord for word, proven

Every episode is compared with the approved guide, sentence by sentence. Its match rating is the lower of two numbers: how much of what is said is the guide word for word, and how much of the guide is said.

A generated episode scores 100%. All 85 scripts, the 33 live and 52 drafted, are word for word today.

The check has permanent stress tests. It must refuse an invented fact, an invented dose, an opinion, a flipped "not", a changed number, a changed treatment, a trimmed, dropped or reordered sentence, and a script made from an older version of the guide. Filler must pass.

03VoicesFree and warm

Two voices from Kokoro, a free, open-source voice model that runs on an ordinary computer: Bella hosts, Heart co-hosts. A short three-note chime, generated in code, opens and closes each episode. No licensed music.

New or changed scripts are voiced automatically, published guides first, ten per run, until all are done. A word the voices say badly gets a pronunciation fix that changes the sound, never the checked words.

The ear decided. The phone's own read-aloud voice sounded robotic and was taken down the same afternoon, and the first free voices tried were rejected. Kokoro was the first to pass.

04One confirmationRead or listen, once

There is no separate podcast approval. On each guide's publish step in the practice's private dashboard, the clinician confirms the exact version by reading the guide or by listening to its episode, and one Publish puts both live.

The rating sets what she must do. Word for word: reading or listening is enough. Above 95% but not word for word: she must listen. Below 95%: she must read and listen.

A listening confirmation is tied to the exact script she heard. Change one line afterwards and it needs confirming again. The site build enforces this, not a person's memory.

05PublishingWherever the guide is

Each guide's page plays its own episode. A podcast page lists them all, the library and homepage show the latest, and an RSS feed carries them to podcast apps.

After every release, the site checks itself live: it streams every episode file and confirms each guide plays its own, then tells the podcast directories the feed has changed.

Any episode can be held back from the dashboard in one click, and a hold survives later edits. Listing the show on Apple Podcasts and Spotify is a one-time sign-up, made under the practice's own accounts; after that, new episodes reach the apps through the feed on their own.

03 / What it taught me

Three calls AI could not make for me.

The natural-sounding kind is the risky kind.

An AI that writes its own chat sounds great and adds things nobody approved. Building the script only from approved sentences gives up a little charm and removes the risk.

Let the ear decide.

Every voice was judged by listening, not by a spec sheet. Two voices taking turns, with a little filler between them, is what stopped it sounding like a screen reader.

One review, not two.

The first version had its own podcast approval queue, which doubled the clinician's work. Because the episode is proven word for word, one confirmation of the guide now covers both.

What AI did

  • Wrote the script builder and the match check
  • Wrote the stress tests that try to fool the check
  • Voiced all 85 scripts with the free voices
  • Built the players, podcast page, feed and live checks
  • Wrote the one-time steps for the podcast apps

Where a person decides

  • Every word of every guide, before it goes public
  • Which voices, by listening
  • Holding back any episode
  • Signing up the show on podcast apps

Tools: Claude, Kokoro (open-source voices), Python, ffmpeg, GitHub Actions, Cloudflare Workers, RSS.

How to use it

  1. Play the 66-second sample on this page, then an episode of the live show to hear a full one.
  2. Copy the skill and give it to your AI with one of your articles. Ask for the episode script and its match check.
  3. To make the audio yourself, download listen.py and run: selftest, then script, check, voice and feed.
  4. Submit the feed to Apple Podcasts and Spotify once. New episodes then reach the apps on their own.

Where it helps most

  • Clinics, law firms and advisers whose articles were approved word by word and must stay that way.
  • Blogs and newsletters whose readers would rather listen while driving, walking or cooking.
  • Anyone who wants a podcast without recording, a studio or paying for voices by the minute.

Free to take

Build your own.

Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›

Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other

---
name: articles-to-podcast
description: Turn written articles into a two-voice podcast that uses each article's exact words, checked sentence by sentence, voiced with free AI voices and published as a feed for Apple Podcasts and Spotify. Use when someone wants audio versions of their blog posts, guides or newsletters without recording anything, or asks to make a podcast from their articles.
---

# Articles to podcast, word for word

The promise to the author: an episode says what the article says, and nothing else. Do not let the voices improvise. A chatty AI podcast that writes its own lines can add advice, numbers or opinions the author never wrote.

## Rules for every episode
1. Every spoken sentence, apart from three fixed lines (a welcome, "Today's article: <title>", a closing), is a whole sentence of the article, word for word, in the article's order.
2. Filler is allowed: "Mm-hm.", "Okay.", "Right.", "Okay, so", "And", "Next up:". It carries no information.
3. Nothing new: no facts, numbers, names, advice, opinions, examples or jokes. No paraphrasing, no trimming, no merging sentences.
4. Nothing left out: every sentence of the article is said. Skip only the list of sources, which is for reading.
5. A changed article needs a new episode. An episode made from an older version is stale and is never published.

## Build the script
- The host opens with the welcome, which says plainly that the hosts are AI voices. The co-host says "Today's article: <title>".
- The co-host raises each heading ("Next up: When to water."). The two voices take turns on paragraphs, one or two sentences per line, under about 330 characters. List items alternate between voices. Now and then the other voice adds "Mm-hm."
- Seed any randomness with the article's text, so the same article always gives the same script and can reuse its audio.
- The host ends with the closing. For health, legal or money topics the closing says it is educational, not personal advice, and gives the crisis or emergency line that applies.

## Check before anything is published
Match rating = the lower of:
- word for word: the share of spoken words (filler and fixed lines aside) that are whole article sentences, in order;
- coverage: the share of the article's sentences that are said.
One review covers article and episode. At 100% the author may approve by reading the article or by listening. Anything lower goes to the author with two lists: lines that are not in the article, and article sentences that are missing. From 95% up they must listen to that exact version before saying yes; below 95% they must read the article and listen.
Prove the check works before trusting it. It must refuse an invented sentence, an opinion, a flipped "not", a changed number, a trimmed sentence, a dropped sentence, reordered sentences and a stale script, and it must let filler through.

## Voices
- Use free, open voices that run on your own computer: Kokoro (the kokoro-onnx package). Two voices, for example af_bella as host and af_heart as co-host, at speed 0.98.
- A pause of about 0.4 s when the speaker changes and 0.3 s when the same voice goes on. Export MP3, mono, 64 kbps.
- Fix pronunciation in the audio only, with a "say" list (for example "PMHNP" said as "P M H N P"). Never change the checked words.
- Make any intro sound yourself, in code. No licensed music.
- Let the owner choose the voices by listening to a sample, not from a list.

## Publish
1. Put each episode on its article's page as "Listen to this article", and all episodes on one podcast page.
2. Write an RSS feed with the iTunes tags: show title, author, owner email, a square cover of 1400 to 3000 px, category, explicit flag, and for each episode an enclosure with its byte length, a duration and a stable guid.
3. After each release, check the live site: every audio file loads and every article plays its own episode.
4. One time only: submit the feed in Apple Podcasts Connect and Spotify for Creators. The owner signs in with their own accounts; never create accounts in their name. New episodes then reach the apps through the feed.

## If you can run code
Use listen.py from https://sghadimi.com/work/listen-podcast/ (one Python file, MIT license). Run "python3 listen.py selftest" first, then "script", "check", "voice" and "feed" for each article.

## If you cannot run code
Write the script as two columns, Host and Co-host, by copying whole sentences from the article. Then list every sentence of the article with a tick where it is said, and give both to the author. Say that the check was done by hand and suggest a free text-to-speech tool for the voices.

## Never
- Never present an AI voice as a person, or let it speak as the author.
- Never publish a stale episode or one below 100% without the author's yes for that exact version.
- Never put private customer, client or patient details in an article, script, audio file or feed.
Get the code3 files, exactly as they run on this site · free under the MIT license

One Python file does it all: script, match check, free voices and the feed, with a sample article and settings file. The practice's own version, built into its private dashboard, stays private; this is the same method.

listen.py (script, check, voices, feed, self-test)454 lines

Raw file

#!/usr/bin/env python3
"""listen.py: turn written articles into a two-voice podcast, in the article's own words.

Two AI voices talk an article through. Every spoken sentence, apart from a fixed
welcome and closing and a few filler words ("Mm-hm.", "Okay, so"), is a whole
sentence of the article, word for word, in order. A match check proves it before
anything is published, so the episode can never say something the author did not.

  python3 listen.py script  article.md            -> article.episode.json (the conversation)
  python3 listen.py check   article.md article.episode.json   (exit 1 unless 100% word for word)
  python3 listen.py voice   article.episode.json  -> article.mp3 (free Kokoro voices, runs offline)
  python3 listen.py feed    episodes/*.episode.json > feed.xml  (RSS for Apple Podcasts, Spotify...)
  python3 listen.py selftest                       (stress tests for the match check)

Settings (voices, welcome, closing, feed details) live in show.json next to this file.
Needs Python 3.9+. For "voice": pip install kokoro-onnx soundfile, and ffmpeg on PATH.
Free to use, change and share under the MIT license. Shahrouz Ghadimi, sghadimi.com
"""
import argparse
import hashlib
import json
import random
import re
import sys
from datetime import datetime, timezone
from email.utils import format_datetime
from html import escape
from pathlib import Path

HERE = Path(__file__).resolve().parent
SHOW_DEFAULTS = {
    'title': 'Listen', 'author': 'Your name', 'owner_email': 'you@example.com', 'site': 'https://example.com',
    'feed_url': 'https://example.com/podcast/feed.xml', 'audio_base': 'https://example.com/podcast/audio/',
    'cover': 'https://example.com/podcast/cover.jpg', 'description': 'Our articles, talked through by two AI voices in their own words.',
    'language': 'en-us', 'category': 'Education', 'explicit': False,
    'voices': {'host': 'af_bella', 'cohost': 'af_heart'}, 'speed': 0.98,
    'intro': "Welcome to Listen. We're two AI voices, and in each episode we talk through one article in its own words.",
    'today': "Today's article: {title}",
    'closing': 'That was the whole article, word for word. The full text and its sources are on our website.',
    'say': {},   # pronunciation fixes for the audio only, e.g. {"PMHNP": "P M H N P"}; the words checked stay the same
}

# Filler: a line may start with, or be only, one of these. They carry no information.
BACKCHANNEL = ['Mm-hm.', 'Okay.', 'Right.', 'Yeah.', 'Got it.', 'Mm, okay.', 'Okay, yeah.', 'Right, okay.']
LEADS = ['So, ', 'Okay, so ', 'Yeah, and ', 'And ', 'Right, and ', 'Well, ', 'Also, ']
HEADING_LEADS = ['Okay. Next: ', 'So, next: ', 'Next up: ', 'Okay, so: ', 'And then: ']
LIST_LEADS = ['First: ', 'Another one: ', 'And: ', 'Also: ', 'Then: ', 'Plus: ']
FILLER_PREFIX = re.compile(
    r"^(?:(?:mm-hm|mm|okay|right|yeah|got it|let's start here|so|and then|and|well|also|next up|next|first|another one|then|plus)"
    r'\b[\s,.:!—-]*)+', re.I)
ABBREV = ['e.g.', 'i.e.', 'etc.', 'vs.', 'Dr.', 'U.S.', 'Mr.', 'Mrs.', 'Ms.', 'No.', 'St.', 'approx.']


def load_show(path=None):
    path = Path(path) if path else HERE / 'show.json'
    show = dict(SHOW_DEFAULTS)
    if path.exists():
        show.update(json.loads(path.read_text(encoding='utf-8')))
    return show


# ── Reading the article ──────────────────────────────────────────────────────
def clean(text):
    text = re.sub(r'!\[[^\]]*\]\([^)]*\)', '', str(text or ''))          # images
    text = re.sub(r'\[([^\]]+)\]\([^)]*\)', r'\1', text)                 # [link text](url) -> link text
    text = re.sub(r'\s*\[\d+(?:[,–-][^\]]{0,40})?\]', '', text)          # citation marks [1], [2-4]
    text = re.sub(r'(\*\*|__|\*|_|`)(.+?)\1', r'\2', text)              # bold, italics, code
    return re.sub(r'\s+', ' ', text).strip()


def read_article(path):
    """A Markdown article as (title, blocks). Blocks are (kind, text), kind = heading, para or bullet.
    The first '# ' line is the title. Reading stops at a Sources/References heading: lists are for reading."""
    title, blocks, para = None, [], []

    def flush():
        if para:
            blocks.append(('para', clean(' '.join(para))))
            para.clear()

    for raw in Path(path).read_text(encoding='utf-8').splitlines():
        line = raw.strip()
        heading = re.match(r'^(#{1,6})\s+(.*)$', line)
        bullet = re.match(r'^(?:[-*+]|\d+[.)])\s+(.*)$', line)
        if heading:
            flush()
            text = clean(heading.group(2))
            if len(heading.group(1)) == 1 and title is None:
                title = text
            elif re.fullmatch(r'(sources|references|citations|further reading)\s*:?', text, re.I):
                break
            else:
                blocks.append(('heading', text))
        elif bullet:
            flush()
            blocks.append(('bullet', clean(bullet.group(1))))
        elif not line:
            flush()
        else:
            para.append(line)
    flush()
    if not title:
        raise SystemExit(f'{path}: the article needs a title line starting with "# "')
    return title, [(k, t) for k, t in blocks if t]


def article_sha(title, blocks):
    return hashlib.sha256(json.dumps([title, blocks], ensure_ascii=False).encode()).hexdigest()[:16]


def sentences(text):
    """Split prose into sentences without breaking common abbreviations."""
    protected = text
    for i, abbr in enumerate(ABBREV):
        protected = protected.replace(abbr, f'\x00{i}\x00')
    out, start = [], 0
    for m in re.finditer(r'[.!?…]["”’)]?(\s+)(?=["“‘(]?[A-Z0-9])', protected):
        out.append(protected[start:m.start(1)])
        start = m.end(1)
    out.append(protected[start:])
    result = []
    for part in out:
        for i, abbr in enumerate(ABBREV):
            part = part.replace(f'\x00{i}\x00', abbr)
        if part.strip():
            result.append(part.strip())
    return result


def chunks(text, max_sentences=2, max_chars=330):
    """Speakable pieces of a paragraph, each made of whole sentences."""
    out, current = [], []
    for s in sentences(text):
        if current and (len(current) >= max_sentences or len(' '.join(current + [s])) > max_chars):
            out.append(' '.join(current))
            current = []
        current.append(s)
    if current:
        out.append(' '.join(current))
    return out


# ── Writing the conversation ─────────────────────────────────────────────────
def lower_first(text, vocabulary):
    """After a lead such as "And ", lower-case the first word unless it is a name or acronym."""
    m = re.match(r'([“"‘(]?)([A-Za-z][\w’\'-]*)', text)
    if not m:
        return text
    word = m.group(2)
    if word == 'I' or word.startswith(("I'", 'I’')) or (len(word) > 1 and not word[1:].islower()):
        return text
    if word.lower() not in vocabulary:
        return text
    return m.group(1) + word[0].lower() + text[len(m.group(1)) + 1:]


def heading_line(text, rng, first):
    if text.endswith('?') or re.match(r'^(myth|fact|step|question|tip)\b', text, re.I):
        return text if first or rng.random() < .5 else rng.choice(['So: ', 'Okay, so: ']) + text
    return ("Let's start here: " if first else rng.choice(HEADING_LEADS)) + text.rstrip('.') + '.'


def make_script(title, blocks, show):
    """The episode: the host reads, the co-host raises each heading, they share paragraphs and list items.
    Seeded by the article's words, so the same text always gives the same script (and can reuse its audio)."""
    sha = article_sha(title, blocks)
    rng = random.Random(sha)
    vocabulary = {w for _, t in blocks for w in re.findall(r"\b[a-z][\w'’-]*", t)}
    lines = [{'speaker': 'host', 'text': show['intro']},
             {'speaker': 'cohost', 'text': show['today'].format(title=title)}]
    speaker, bullet_turn, first_heading, previous = 'host', 0, True, None
    for kind, text in blocks:
        if kind == 'heading':
            lines.append({'speaker': 'cohost', 'text': heading_line(text, rng, first_heading)})
            first_heading, speaker, previous = False, 'host', kind
            continue
        if kind == 'bullet':
            lead = rng.choice(LIST_LEADS) if bullet_turn and rng.random() < .45 else ''
            lines.append({'speaker': 'cohost' if bullet_turn % 2 == 0 else 'host', 'text': lead + text})
            bullet_turn, previous = bullet_turn + 1, kind
            continue
        bullet_turn = 0
        pieces = chunks(text)
        for i, piece in enumerate(pieces):
            if i == 0 and previous == 'para' and lines[-1]['speaker'] == speaker and rng.random() < .55:
                piece = rng.choice(LEADS) + lower_first(piece, vocabulary)
            lines.append({'speaker': speaker, 'text': piece})
            if i < len(pieces) - 1 and rng.random() < .55:
                lines.append({'speaker': 'cohost' if speaker == 'host' else 'host', 'text': rng.choice(BACKCHANNEL)})
        if rng.random() < .6:
            speaker = 'cohost' if speaker == 'host' else 'host'
        previous = kind
    lines.append({'speaker': 'host', 'text': show['closing']})
    merged = []
    for line in lines:   # no voice answers its own "Mm-hm."
        if merged and line['text'] in BACKCHANNEL and merged[-1]['speaker'] == line['speaker']:
            continue
        merged.append(line)
    first = next((t for k, t in blocks if k == 'para'), title)
    return {'title': title, 'description': first[:300], 'article_sha': sha, 'lines': merged}


# ── The match check ──────────────────────────────────────────────────────────
def words(text):
    text = clean(text).lower().replace('’', "'").replace('‘', "'").replace('—', ' ').replace('–', ' ')
    return re.findall(r"[a-z0-9]+(?:['.-][a-z0-9]+)*", text)


def key(sentence):
    return ' '.join(words(FILLER_PREFIX.sub('', sentence.strip(), count=1)))


def check(title, blocks, episode, show):
    """Compare an episode with its article. Every spoken sentence outside the fixed framing must be a whole
    sentence of the article, word for word, in order (filler aside), and every article sentence must be said.
    match = the lower of word-for-word % and coverage %. ok = 100%, nothing added, nothing missing, not stale."""
    article = [s for _, t in blocks for s in sentences(t)]
    keys = [key(s) for s in article]
    framing = {show['intro'], show['today'].format(title=title), show['closing']}
    spoken = verbatim = 0
    problems, said, last = [], set(), -1
    for n, line in enumerate(episode['lines'], 1):
        text = line['text'].strip()
        if text in framing or text in BACKCHANNEL:
            continue
        for s in sentences(FILLER_PREFIX.sub('', text, count=1)):
            k = key(s)
            if not k:
                continue
            count = len(k.split())
            spoken += count
            places = [i for i, a in enumerate(keys) if a == k]
            if not places:
                problems.append({'line': n, 'text': s, 'why': 'not a whole sentence of the article, word for word'})
                continue
            later = [i for i in places if i > last]
            if not later:
                problems.append({'line': n, 'text': s, 'why': "out of the article's order"})
                continue
            said.add(later[0])
            last = later[0]
            verbatim += count
    missing = [article[i] for i in range(len(article)) if i not in said]
    word_match = round(100 * verbatim / spoken, 1) if spoken else 0.0
    coverage = round(100 * len(said) / len(article), 1) if article else 0.0
    stale = episode.get('article_sha') != article_sha(title, blocks)
    return {'match': min(word_match, coverage), 'word_for_word': word_match, 'coverage': coverage,
            'not_in_article': problems, 'missing': missing, 'stale': stale,
            'ok': not problems and not missing and not stale and spoken > 0}


# ── Voices (Kokoro: free, open source, runs on your own computer) ────────────
MODEL_BASE = 'https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/'
MODEL_FILES = ('kokoro-v1.0.onnx', 'voices-v1.0.bin')


def chime(np, rate, notes):
    """A short three-note chime, generated here: no licensed music."""
    parts = []
    for i, f in enumerate(notes):
        t = np.arange(int(rate * 0.9)) / rate
        tone = 0.12 * np.sin(2 * np.pi * f * t) * np.exp(-3.2 * t) + 0.04 * np.sin(4 * np.pi * f * t) * np.exp(-5 * t)
        parts.append(np.concatenate([np.zeros(int(rate * 0.18 * i)), tone]))
    mix = np.zeros(max(len(p) for p in parts))
    for p in parts:
        mix[:len(p)] += p
    return mix


def voice(episode, show, out_path, models):
    import subprocess
    import tempfile
    import urllib.request
    import numpy as np
    import soundfile as sf
    from kokoro_onnx import Kokoro
    models = Path(models)
    models.mkdir(parents=True, exist_ok=True)
    for name in MODEL_FILES:   # about 350 MB, downloaded once
        if not (models / name).exists():
            print('downloading', name, file=sys.stderr)
            urllib.request.urlretrieve(MODEL_BASE + name, models / name)
    kokoro = Kokoro(str(models / MODEL_FILES[0]), str(models / MODEL_FILES[1]))
    rate = 24000
    parts, previous = [chime(np, rate, (523.25, 659.25, 783.99)), np.zeros(int(rate * 0.5))], None
    for line in episode['lines']:
        text = line['text']
        for word, said in show.get('say', {}).items():
            text = re.sub(r'\b' + re.escape(word) + r'\b', said, text)
        samples, rate = kokoro.create(text, voice=show['voices'][line['speaker']], speed=show['speed'], lang='en-us')
        if previous is not None:   # a slightly longer pause when the other voice takes over
            parts.append(np.zeros(int(rate * (0.42 if line['speaker'] != previous else 0.3))))
        parts.append(samples.astype(np.float64))
        previous = line['speaker']
    parts += [np.zeros(int(rate * 0.6)), chime(np, rate, (783.99, 659.25, 523.25))]
    audio = np.concatenate(parts)
    audio = audio / max(1e-6, np.abs(audio).max()) * 0.9
    with tempfile.TemporaryDirectory() as tmp:
        wav = Path(tmp) / 'episode.wav'
        sf.write(wav, audio, rate)
        subprocess.run(['ffmpeg', '-loglevel', 'error', '-y', '-i', str(wav), '-ac', '1', '-b:a', '64k',
                        '-metadata', 'title=' + episode['title'], '-metadata', 'artist=' + show['author'],
                        '-metadata', 'album=' + show['title'], str(out_path)], check=True)
    return round(len(audio) / rate)


# ── The feed podcast apps read ───────────────────────────────────────────────
def clock(seconds):
    return f'{seconds // 3600:d}:{seconds // 60 % 60:02d}:{seconds % 60:02d}' if seconds >= 3600 else f'{seconds // 60:d}:{seconds % 60:02d}'


def feed(episodes, show):
    """RSS with the iTunes tags Apple Podcasts and Spotify ask for. Episodes need "audio" (from the voice step)."""
    e = lambda s: escape(str(s), quote=True)
    items = []
    for ep in sorted(episodes, key=lambda x: x.get('number', 0), reverse=True):
        audio = ep['audio']
        when = datetime.fromisoformat(ep.get('date', audio['date'])).replace(tzinfo=timezone.utc)
        items.append(
            f'<item><title>{e(ep["title"])}</title><description>{e(ep.get("description", ep["title"]))}</description>'
            f'<guid isPermaLink="false">{e(ep["article_sha"])}</guid><pubDate>{format_datetime(when)}</pubDate>'
            f'<enclosure url="{e(show["audio_base"] + audio["file"])}" length="{audio["bytes"]}" type="audio/mpeg"/>'
            f'<itunes:duration>{clock(audio["seconds"])}</itunes:duration>'
            + (f'<itunes:episode>{ep["number"]}</itunes:episode>' if ep.get('number') else '')
            + '<itunes:episodeType>full</itunes:episodeType></item>')
    explicit = 'true' if show['explicit'] else 'false'
    return ('<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" '
            'xmlns:atom="http://www.w3.org/2005/Atom"><channel>'
            f'<title>{e(show["title"])}</title><link>{e(show["site"])}</link>'
            f'<atom:link href="{e(show["feed_url"])}" rel="self" type="application/rss+xml"/>'
            f'<description>{e(show["description"])}</description><language>{e(show["language"])}</language>'
            f'<itunes:author>{e(show["author"])}</itunes:author>'
            f'<itunes:owner><itunes:name>{e(show["author"])}</itunes:name><itunes:email>{e(show["owner_email"])}</itunes:email></itunes:owner>'
            f'<itunes:image href="{e(show["cover"])}"/><itunes:category text="{e(show["category"])}"/>'
            f'<itunes:explicit>{explicit}</itunes:explicit><itunes:type>episodic</itunes:type>'
            + ''.join(items) + '</channel></rss>\n')


# ── Stress tests: the match check must catch every way a script can drift ────
SAMPLE = """# Watering a desert garden

Most plants die from too much water, not too little. Water deeply and less often.

## When to water

Water early in the morning, before 8 a.m. The soil should dry out 2 inches down between waterings.

- Check with your finger before you water.
- Skip a day after rain.

## Sources

1. Not read aloud.
"""


def selftest():
    import tempfile
    show = dict(SHOW_DEFAULTS)
    with tempfile.TemporaryDirectory() as tmp:
        path = Path(tmp) / 'a.md'
        path.write_text(SAMPLE, encoding='utf-8')
        title, blocks = read_article(path)
    good = make_script(title, blocks, show)
    assert not any('Not read aloud' in l['text'] for l in good['lines']), 'the source list is not spoken'
    assert check(title, blocks, good, show)['ok'], 'a generated script is word for word'

    def edited(change):
        ep = json.loads(json.dumps(good))
        change(ep['lines'])
        return check(title, blocks, ep, show)

    def swap(old, new):
        def change(lines):
            hit = [l for l in lines if old in l['text']]
            assert hit, f'test setup: "{old}" not in script'
            hit[0]['text'] = hit[0]['text'].replace(old, new)
        return change

    def add(text):
        return lambda lines: lines.insert(3, {'speaker': 'cohost', 'text': text})

    def drop(sentence):
        def change(lines):
            for l in lines:
                l['text'] = l['text'].replace(sentence, '').strip()
            lines[:] = [l for l in lines if l['text']]
        return change

    cases = {
        'an invented fact': add('Cacti need watering every day.'),
        'an opinion': add('Honestly, I think this is the best advice out there.'),
        'a flipped negation': swap('not too little', 'too little'),
        'a changed number': swap('2 inches', '4 inches'),
        'a changed time': swap('morning', 'evening'),
        'a trimmed sentence': swap(' and less often', ''),
        'a dropped sentence': drop('Skip a day after rain.'),
        'reordered sentences': lambda lines: lines.reverse(),
    }
    for name, change in cases.items():
        assert not edited(change)['ok'], f'the check missed {name}'
    assert edited(add('Mm-hm.'))['ok'], 'filler is allowed'
    assert edited(swap('Check with', 'Okay, so check with'))['ok'], 'a lead word in front of a sentence is allowed'
    assert edited(lambda lines: lines.insert(len(lines) - 1, {'speaker': 'host', 'text': 'Right.'}))['ok'], 'a backchannel line is allowed anywhere'
    stale = check(title, blocks + [('para', 'A new sentence.')], good, show)
    assert stale['stale'] and not stale['ok'], 'an episode from an older version of the article is stale'
    print(f'selftest passed: {len(cases)} kinds of drift caught, filler allowed, stale scripts refused.')


def main():
    p = argparse.ArgumentParser(description='Turn articles into a two-voice podcast in their own words.')
    p.add_argument('--show', help='show.json (default: next to this file)')
    sub = p.add_subparsers(dest='cmd', required=True)
    s = sub.add_parser('script'); s.add_argument('article'); s.add_argument('--out')
    c = sub.add_parser('check'); c.add_argument('article'); c.add_argument('episode')
    v = sub.add_parser('voice'); v.add_argument('episode'); v.add_argument('--out')
    v.add_argument('--models', default=str(Path.home() / '.cache' / 'kokoro'))
    f = sub.add_parser('feed'); f.add_argument('episodes', nargs='+')
    sub.add_parser('selftest')
    a = p.parse_args()
    show = load_show(a.show)
    if a.cmd == 'selftest':
        return selftest()
    if a.cmd == 'script':
        title, blocks = read_article(a.article)
        ep = make_script(title, blocks, show)
        out = Path(a.out or Path(a.article).with_suffix('.episode.json'))
        out.write_text(json.dumps(ep, indent=1, ensure_ascii=False) + '\n', encoding='utf-8')
        print(f'{out}: {len(ep["lines"])} lines')
    elif a.cmd == 'check':
        title, blocks = read_article(a.article)
        report = check(title, blocks, json.loads(Path(a.episode).read_text(encoding='utf-8')), show)
        print(json.dumps(report, indent=1, ensure_ascii=False))
        sys.exit(0 if report['ok'] else 1)
    elif a.cmd == 'voice':
        path = Path(a.episode)
        ep = json.loads(path.read_text(encoding='utf-8'))
        out = Path(a.out or str(path).replace('.episode.json', '.mp3'))
        seconds = voice(ep, show, out, a.models)
        ep['audio'] = {'file': out.name, 'seconds': seconds, 'bytes': out.stat().st_size,
                       'date': datetime.now(timezone.utc).date().isoformat()}
        path.write_text(json.dumps(ep, indent=1, ensure_ascii=False) + '\n', encoding='utf-8')
        print(f'{out}: {seconds} s')
    elif a.cmd == 'feed':
        eps = [json.loads(Path(x).read_text(encoding='utf-8')) for x in a.episodes]
        missing = [x for x, ep in zip(a.episodes, eps) if 'audio' not in ep]
        if missing:
            raise SystemExit('voice these first: ' + ', '.join(missing))
        sys.stdout.write(feed(eps, show))


if __name__ == '__main__':
    main()
show.json (voices, welcome, closing, feed details)20 lines

Raw file

{
 "title": "Listen: Desert Garden Notes",
 "author": "Desert Garden Notes",
 "owner_email": "you@example.com",
 "site": "https://example.com",
 "feed_url": "https://example.com/podcast/feed.xml",
 "audio_base": "https://example.com/podcast/audio/",
 "cover": "https://example.com/podcast/cover.jpg",
 "description": "Every Desert Garden Notes article, talked through by two AI voices in its own words.",
 "language": "en-us",
 "category": "Leisure",
 "explicit": false,
 "voices": {"host": "af_bella", "cohost": "af_heart"},
 "speed": 0.98,
 "intro": "Welcome to Listen. We're two AI voices, and in each episode we talk through one article in its own words.",
 "today": "Today's article: {title}",
 "closing": "That was the whole article, word for word. The full text and its sources are on our website.",
 "say": {}
}
sample-article.md (the made-up article in the sample)22 lines

Raw file

# Watering a desert garden

Most desert plants die from too much water, not too little. Water deeply and less often, so roots grow down toward cooler soil.

## When to water

Water early in the morning, before the sun is high. Less water is lost to the air, and leaves dry before night.

Let the soil dry out about two inches down between waterings. In summer that might be every three or four days; in winter, every two weeks.

- Check with your finger before you water.
- Skip a day after a good rain.
- Water the soil, not the leaves.

## Signs of too much water

Yellow leaves, soft stems and a sour smell from the soil all point the same way. Stop watering and let the soil dry before you try again.

## Sources

1. Your local extension office. Lists like this one are for reading, so the episode skips them.

Want a workflow like this inside your business?

The skill above is free and yours to adapt. If you would rather have it built around your own inbox, forms and files, tested, and handed over, I do that for a fixed price agreed up front. The first call is free.

How it works and what it costs Book a free call ↗

Or write to me · how to use what is here