Skip to content
Open
Prev Previous commit
Next Next commit
feat: natural OpenAI voices (Marin, Cedar) for Motion Studio
Edge TTS records each beat separately, which resets the intonation every
few seconds. OpenAI voices read the whole script in one directed take with
gpt-4o-mini-tts; whisper-1 then returns word times, which are matched back
to the script's words (spelling variants such as आवाज़/आवाज or call/कौल
included), so captions keep the script's spelling and beats stay timed.

OpenAI voices reuse the script writer's OpenAI key: the API rejects them
with another provider, the key now lives in the job frame until the voice
is recorded, it is passed explicitly (never the server's env key), and
OpenAI errors become plain messages without the key.
  • Loading branch information
ashifhusainoo7 committed Nov 9, 2026
commit 3f02a656f6eb9d97d030d0befe58467f536654e7
2 changes: 2 additions & 0 deletions app/controllers/v1/motion.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ def get_character(request: Request, character_id: str = Path(pattern=CHARACTER_I
def create_job(request: Request, body: MotionJobRequest):
if body.voice not in VOICE_BY_ID:
raise _fail(request, 400, f"unknown voice: {body.voice}")
if VOICE_BY_ID[body.voice].get("openai") and body.llm.provider != "openai":
raise _fail(request, 400, "OpenAI voices use your OpenAI API key: choose OpenAI as the script writer's provider.")
try:
job = jobs.submit(body)
except jobs.Busy:
Expand Down
6 changes: 5 additions & 1 deletion app/services/motion/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from app.models.motion import MotionJobRequest
from app.services.motion import pipeline, writer
from app.services.motion.errors import MotionError
from app.services.motion.speech import VOICE_BY_ID
from app.utils import utils

ROOT = Path(utils.storage_dir("motion", create=True))
Expand Down Expand Up @@ -229,6 +230,8 @@ def _run(job: Job, character: Path | None) -> None:
request = job.secret.pop() # the request holds the API key; it lives only in this frame now
job_dir = JOBS_DIR / job.id
voice, title = request.voice, request.title
# OpenAI voices reuse the writer's key, so it lives in this frame until the voice is recorded.
voice_key = request.llm.api_key if VOICE_BY_ID.get(voice, {}).get("openai") else None
try:
job_dir.mkdir(parents=True, exist_ok=True)
_stage(job, "writing")
Expand All @@ -238,7 +241,8 @@ def _run(job: Job, character: Path | None) -> None:
storyboard.youtube.title = title
(job_dir / "youtube.json").write_text(storyboard.youtube.model_dump_json(), encoding="utf-8")
_stage(job, "voicing")
speech = pipeline.prepare(job_dir, storyboard, voice, character)
speech = pipeline.prepare(job_dir, storyboard, voice, character, voice_key)
voice_key = None
_stage(job, "rendering")
_render(job, job_dir)
for copy in job_dir.glob("character.*"): # the upload itself stays in uploads/
Expand Down
10 changes: 7 additions & 3 deletions app/services/motion/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import shutil
from pathlib import Path

from pydantic import SecretStr

from app.models.motion import Storyboard
from app.services.motion import speech
from app.services.motion.speech import Speech
Expand Down Expand Up @@ -37,15 +39,17 @@ def scene_storyboard(storyboard: Storyboard, voice: Speech, character: dict, pal
return {"character": character, "palette": palette, "beats": beats, "duration": voice.duration}


def prepare(job_dir: Path, storyboard: Storyboard, voice_id: str, character_file: Path | None) -> Speech:
"""Record the voice and lay out everything the renderer needs inside job_dir."""
def prepare(job_dir: Path, storyboard: Storyboard, voice_id: str, character_file: Path | None,
api_key: SecretStr | None = None) -> Speech:
"""Record the voice and lay out everything the renderer needs inside job_dir (api_key: OpenAI voices only)."""
character = {"kind": "none"}
if character_file is not None:
target = job_dir / f"character{character_file.suffix.lower()}"
shutil.copyfile(character_file, target)
kind = "image" if target.suffix in IMAGE_SUFFIXES else "glb"
character = {"kind": kind, "url": f"/job/{target.name}"}
voice = speech.synthesize([beat.say for beat in storyboard.beats], voice_id, job_dir)
key = api_key.get_secret_value() if api_key else None
voice = speech.synthesize([beat.say for beat in storyboard.beats], voice_id, job_dir, key)
scene = scene_storyboard(storyboard, voice, character, next_palette(job_dir.parent))
(job_dir / "storyboard.json").write_text(json.dumps(scene, ensure_ascii=False, indent=1), encoding="utf-8")
return voice
168 changes: 158 additions & 10 deletions app/services/motion/speech.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
"""Motion Studio voice: one Edge TTS call per beat, joined into one track with exact beat times.
"""Motion Studio voice: one track with exact word and beat times.

Per-beat synthesis means every beat's start time is known exactly, so visuals never drift from the
voice. The same decoded samples give the per-frame loudness the host's mouth follows.
Edge TTS (free): one call per beat, joined, so every beat's start time is known exactly.
OpenAI (uses the creator's OpenAI key): the whole script in one directed take, which sounds far more
natural, then a transcription pass gives word times that are matched back to the script's words.
The same samples give the per-frame loudness the host's mouth follows.
"""

import asyncio
import difflib
import io
import json
import re
import subprocess
import unicodedata
import wave
from dataclasses import dataclass
from pathlib import Path

import edge_tts
import numpy as np
import openai
from imageio_ffmpeg import get_ffmpeg_exe

from app.services.motion.errors import MotionError
Expand All @@ -24,6 +30,17 @@
BEAT_GAP_S = 0.18 # breath between beats
HOLD_S = 0.8 # silence after the last word, while the last frame stays on screen
RATE = "+15%" # brisk Shorts pace
OPENAI_TTS_MODEL = "gpt-4o-mini-tts"
OPENAI_TIMING_MODEL = "whisper-1" # returns word timestamps
OPENAI_TIMEOUT_S = 120
OPENAI_INSTRUCTIONS = (
"You are a friendly YouTube Shorts host explaining something useful to young viewers. Speak natural, "
"conversational {language}, and say English words the way local speakers do. Warm and energetic but not "
"shouting, a quick Shorts pace, real pauses at commas and full stops, like talking to a friend."
)
LEAD_S = 0.12 # a scene appears just before its first word
PHRASE_END = (",", "?", "।", "!", ".", ":", ";", ",", "。", "?", "!")
EDGE_PUNCT = "\"'“”‘’()[]{}.,!?;:…।॥—–,。?!" # stripped from the ends of caption words

# Voices whose script the engine fonts cover (Baloo 2: Latin + Devanagari; CJK uses system fonts).
VOICES = [
Expand All @@ -38,6 +55,15 @@
{"id": "zh-CN-XiaoxiaoNeural", "label": "Chinese, Xiaoxiao (female)", "language": "Simplified Chinese"},
{"id": "es-ES-AlvaroNeural", "label": "Spanish, Alvaro (male)", "language": "Spanish"},
{"id": "pt-BR-FranciscaNeural", "label": "Portuguese (Brazil), Francisca (female)", "language": "Brazilian Portuguese"},
# OpenAI voices reuse the script writer's OpenAI key (provider must be OpenAI).
{"id": "openai-marin-hi", "label": "Hindi, Marin (OpenAI, most natural; uses your OpenAI key)", "language": "Hindi",
"openai": "marin", "lang": "hi"},
{"id": "openai-cedar-hi", "label": "Hindi, Cedar (OpenAI; uses your OpenAI key)", "language": "Hindi",
"openai": "cedar", "lang": "hi"},
{"id": "openai-marin-en", "label": "English, Marin (OpenAI, most natural; uses your OpenAI key)", "language": "English",
"openai": "marin", "lang": "en"},
{"id": "openai-cedar-en", "label": "English, Cedar (OpenAI; uses your OpenAI key)", "language": "English",
"openai": "cedar", "lang": "en"},
]
VOICE_BY_ID = {voice["id"]: voice for voice in VOICES}

Expand Down Expand Up @@ -100,11 +126,15 @@ def mark_breaks(words: list[dict], text: str) -> None:
tokens = text.split()
if len(tokens) == len(words) and all(w["text"] in tok for w, tok in zip(words, tokens)):
for w, tok in zip(words, tokens):
w["br"] = tok.rstrip("\"'”’").endswith((",", "?", "।", "!", ".", ":", ";", ",", "。", "?", "!"))
w["br"] = _ends_phrase(tok)
if words:
words[-1]["br"] = True


def _ends_phrase(token: str) -> bool:
return token.rstrip("\"'”’").endswith(PHRASE_END)


def _norm(s: str) -> str:
return re.sub(r"[^\w]", "", unicodedata.normalize("NFC", s).casefold())

Expand All @@ -130,10 +160,8 @@ def envelope(samples: np.ndarray) -> list[float]:
return (rms / max(float(np.percentile(rms, 95)), 1e-6)).clip(0, 1).round(3).tolist()


def synthesize(texts: list[str], voice: str, out_dir: Path) -> Speech:
"""Speak each beat, join them, and write audio.m4a, words.json and env.json into out_dir."""
if voice not in VOICE_BY_ID:
raise MotionError(f"Unknown voice: {voice}")
def _edge_take(texts: list[str], voice: str) -> tuple[np.ndarray, list[dict], list[tuple[float, float]]]:
"""Speak each beat with Edge TTS and join them with a short breath."""
words, beats, parts, cursor = [], [], [], 0
gap = np.zeros(int(BEAT_GAP_S * SAMPLE_RATE), np.int16)
for i, text in enumerate(texts):
Expand All @@ -157,8 +185,128 @@ def synthesize(texts: list[str], voice: str, out_dir: Path) -> Speech:
if i < len(texts) - 1:
parts.append(gap)
cursor += len(gap)
parts.append(np.zeros(int(HOLD_S * SAMPLE_RATE), np.int16))
audio = np.concatenate(parts)
return np.concatenate(parts), words, beats


def _key(text: str) -> str:
"""Comparison form of a word: case, nukta and punctuation don't count (आवाज़ = आवाज)."""
return re.sub(r"[^\w]", "", unicodedata.normalize("NFC", text).casefold().replace("़", ""))


def _script_tokens(texts: list[str]) -> list[dict]:
"""Every written word with its beat, its caption text and whether a caption phrase ends after it."""
out = []
for beat, text in enumerate(texts):
first = len(out)
for token in text.split():
shown = token.strip(EDGE_PUNCT)
if shown:
out.append({"beat": beat, "text": shown, "br": _ends_phrase(token)})
elif len(out) > first and _ends_phrase(token): # a lone "..." after a word
out[-1]["br"] = True
if len(out) > first:
out[-1]["br"] = True
return out


def _spread(tokens: list[dict], times: list, i1: int, i2: int, lo: float, hi: float) -> None:
"""Share lo..hi among tokens[i1:i2] in proportion to their length."""
weights = [max(len(t["text"]), 1) for t in tokens[i1:i2]]
total, at = sum(weights), lo
for k, weight in enumerate(weights):
end = at + (hi - lo) * weight / total
times[i1 + k] = (at, end)
at = end


def align(texts: list[str], heard: list[tuple[str, float, float]], total: float) -> tuple[list[dict], list[tuple[float, float]]]:
"""Time every written word from the transcribed audio; returns the words and each beat's (start, end).

The transcript spells some words differently from the script (आवाज़/आवाज, call/कौल). Matching words take
the transcript's times, differing runs share their transcript span, and the rest share the gap between
timed neighbours. Captions always show the script's own spelling.
"""
tokens = _script_tokens(texts)
times: list = [None] * len(tokens)
matcher = difflib.SequenceMatcher(None, [_key(t["text"]) for t in tokens], [_key(h[0]) for h in heard], autojunk=False)
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == "equal":
for k in range(i2 - i1):
times[i1 + k] = heard[j1 + k][1:]
elif tag == "replace":
_spread(tokens, times, i1, i2, heard[j1][1], heard[j2 - 1][2])
i = 0
while i < len(tokens):
if times[i] is not None:
i += 1
continue
j = i
while j < len(tokens) and times[j] is None:
j += 1
lo = times[i - 1][1] if i else 0.0
_spread(tokens, times, i, j, lo, max(times[j][0] if j < len(tokens) else total, lo))
i = j
words = [{"text": t["text"], "start": round(s, 3), "end": round(e, 3), "br": t["br"]} for t, (s, e) in zip(tokens, times)]
starts, last_end = [], 0.0
for beat in range(len(texts)):
mine = [w for w, t in zip(words, tokens) if t["beat"] == beat]
starts.append(0.0 if beat == 0 else max(last_end, mine[0]["start"] - LEAD_S) if mine else last_end)
last_end = mine[-1]["end"] if mine else last_end
ends = starts[1:] + [round(max(total, last_end), 3)]
return words, [(round(s, 3), round(e, 3)) for s, e in zip(starts, ends)]


def _wav(pcm: bytes) -> bytes:
buffer = io.BytesIO()
with wave.open(buffer, "wb") as out:
out.setnchannels(1)
out.setsampwidth(2)
out.setframerate(SAMPLE_RATE)
out.writeframes(pcm)
return buffer.getvalue()


def _openai_take(texts: list[str], voice: dict, api_key: str | None) -> tuple[np.ndarray, list[dict], list[tuple[float, float]]]:
"""The whole script in one directed OpenAI take, timed by a transcription pass."""
if not api_key:
raise MotionError("OpenAI voices use your OpenAI API key. Choose OpenAI as the provider and paste your key.")
client = openai.OpenAI(api_key=api_key, timeout=OPENAI_TIMEOUT_S, max_retries=1) # never the server's env key
try:
pcm = client.audio.speech.create(
model=OPENAI_TTS_MODEL, voice=voice["openai"], input=" ".join(texts), response_format="pcm",
instructions=OPENAI_INSTRUCTIONS.format(language=voice["language"]),
).content
heard = client.audio.transcriptions.create(
model=OPENAI_TIMING_MODEL, file=("voice.wav", _wav(pcm), "audio/wav"), language=voice["lang"],
response_format="verbose_json", timestamp_granularities=["word"],
).words or []
except openai.AuthenticationError:
raise MotionError("OpenAI rejected the API key.") from None
except openai.PermissionDeniedError:
raise MotionError(f"This OpenAI key can't use the voice models ({OPENAI_TTS_MODEL}, {OPENAI_TIMING_MODEL}).") from None
except openai.RateLimitError:
raise MotionError("OpenAI's rate limit or quota is reached. Check your plan and try again.") from None
except openai.APIConnectionError:
raise MotionError("Couldn't reach OpenAI. Check your internet connection and try again.") from None
except openai.APIError:
raise MotionError("OpenAI's voice service failed. Try again in a minute.") from None
samples = np.frombuffer(pcm[: len(pcm) // 2 * 2], np.int16) # 24 kHz 16-bit mono
if not len(samples):
raise MotionError("OpenAI returned no audio. Try again in a minute.")
words, beats = align(texts, [(w.word, w.start, w.end) for w in heard], len(samples) / SAMPLE_RATE)
return samples, words, beats


def synthesize(texts: list[str], voice: str, out_dir: Path, api_key: str | None = None) -> Speech:
"""Speak the beats and write audio.m4a, words.json and env.json into out_dir.

api_key is only used by OpenAI voices, for this one take, and is never stored.
"""
if voice not in VOICE_BY_ID:
raise MotionError(f"Unknown voice: {voice}")
entry = VOICE_BY_ID[voice]
samples, words, beats = _openai_take(texts, entry, api_key) if entry.get("openai") else _edge_take(texts, voice)
audio = np.concatenate([samples, np.zeros(int(HOLD_S * SAMPLE_RATE), np.int16)])
subprocess.run(
[get_ffmpeg_exe(), "-loglevel", "error", "-y", "-f", "s16le", "-ar", str(SAMPLE_RATE), "-ac", "1", "-i", "pipe:0",
"-c:a", "aac", "-b:a", "160k", str(out_dir / "audio.m4a")],
Expand Down
10 changes: 8 additions & 2 deletions docs/motion-studio.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,9 @@ OpenAI-compatible endpoint (base URL). Calls go through LiteLLM, which MoneyPrin
depends on. The model field is free text; the suggestions are only a starting point.

The key you paste goes from the studio to this server and straight to the provider for that video.
It is never written to disk, logged, returned by the API or kept after the job's script is written,
and the studio keeps it in memory only (not in local storage). Provider error messages are scrubbed
It is never written to disk, logged, returned by the API or kept after the job's script is written
(with an OpenAI voice, after the voice is recorded), and the studio keeps it in memory only (not in
local storage). Provider error messages are scrubbed
of anything key-like before they are shown.

The AI is told to use only facts from your brief or common knowledge and never to invent statistics,
Expand All @@ -68,6 +69,11 @@ Edge TTS (free, no key): Hindi, English (India and US), Marathi, Simplified Chin
Brazilian Portuguese voices. The script is written in the voice's language. Hindi scripts keep common
English terms in English letters.

OpenAI voices (Marin, Cedar; Hindi and English) sound far more natural. They read the whole script in
one directed take with `gpt-4o-mini-tts`, then `whisper-1` returns word times that are matched back to
the script, so captions keep the script's spelling. They use the script writer's OpenAI key, so the
provider must be OpenAI; a 45-second video costs roughly US$0.02.

## Publishing to YouTube

YouTube offers no way for another site to attach a video or prefill the upload form. **Upload to
Expand Down
Loading