#!/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'{e(ep["title"])}{e(ep.get("description", ep["title"]))}'
f'{e(ep["article_sha"])}{format_datetime(when)}'
f''
f'{clock(audio["seconds"])}'
+ (f'{ep["number"]}' if ep.get('number') else '')
+ 'full')
explicit = 'true' if show['explicit'] else 'false'
return ('\n'
f'{e(show["title"])}{e(show["site"])}'
f''
f'{e(show["description"])}{e(show["language"])}'
f'{e(show["author"])}'
f'{e(show["author"])}{e(show["owner_email"])}'
f''
f'{explicit}episodic'
+ ''.join(items) + '\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()