Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ The rest is written by hand.
| transcribe.py | /api/transcribe | 2 |
| tts.py | /api/tts | 3 |
| upscale.py | /api/media | 2 |
| voice_app.py | /api/speech/app | 4 |
| webhooks.py | /api/webhooks | 5 |
| window_key.py | /api/window | 3 |

Expand Down
26 changes: 26 additions & 0 deletions .docs/wiki/Models.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,32 @@ Pocket TTS (Kyutai, CC-BY-4.0 weights) and Chatterbox (Resemble AI, MIT, with
an inaudible watermark on its audio) are installable engines beside it, set up
once with `backend/setup_local_ai.py` and chosen from the same panel.

**A voice app on this computer.** The same panel's Engine list ends with
**Voice app on this computer**: any separate program that answers the
OpenAI-compatible speech API on this computer, which is how a voice cloned in
another app (qwentts.cpp, AudioCpp Desktop, VoiceStudio and the like) is used.
Start the app, give its address (default `http://127.0.0.1:8080`), and a key if
the app asks for one, press **Check**, then pick its model and voice. Generate
puts the sound on the timeline at the playhead, as the other engines do.

- Only an address on this computer is taken: `127.0.0.1`, `localhost` or
`[::1]`, no proxy and no redirect, so the text never leaves the computer
through this engine.
- The address, model and voice are kept in `voice-app.json` in the data folder.
A key is kept in the same file, readable by its owner only, and is never sent
back to the window.
- FormCut asks the app for `POST /v1/audio/speech` with
`response_format: "wav"`, and takes WAV, MP3, Ogg or FLAC back. Check reads
`GET /v1/models` and `GET /v1/audio/voices`; an app that lists neither still
works, with its own default model and voice.

```
GET /api/speech/app the address, model and voice, and whether a key is kept
PUT /api/speech/app {"base", "model", "voice", "key"}; key null keeps it, "" removes it
POST /api/speech/app/check {"base"}: what the app at that address offers
POST /api/speech/app/speak {"text", "speed"}: a job whose result is {"media": ...}
```

| File | Licence | Size |
| --- | --- | --- |
| `kokoro-v1.0.onnx` | Apache-2.0 | ~310 MB |
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
</p>

<p align="center">
<img alt="version v2.21.1" src="https://img.shields.io/badge/version-v2.21.1-eef0f4?style=flat-square">
<img alt="version v2.22.0" src="https://img.shields.io/badge/version-v2.22.0-eef0f4?style=flat-square">
<img alt="TypeScript and Vite" src="https://img.shields.io/badge/TypeScript-Vite-3178c6?style=flat-square&logo=typescript&logoColor=white">
<img alt="Python FastAPI" src="https://img.shields.io/badge/Python-FastAPI-3776ab?style=flat-square">
<img alt="macOS, Windows, Linux" src="https://img.shields.io/badge/macOS%20%C2%B7%20Windows%20%C2%B7%20Linux-native-2f7bf5?style=flat-square">
Expand Down
10 changes: 10 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@

Reasoning behind engine changes, newest first.

## 2.22.0 · a voice app on this computer speaks for the Studio (`app/voice_app.py` new; `main.py` include)

- **Why.** Issue 43, second part. FormMorpheus #31 asked for narration in a voice cloned in a separate free app (qwentts.cpp, AudioCpp Desktop, VoiceStudio), each of which answers the OpenAI-compatible speech API on this computer, by default at `http://127.0.0.1:8080`. FormCut clones a voice itself with Pocket TTS and Chatterbox, but had no way to use an outside app. The pattern is FormMorpheus's `services/voice_remote.py` (Apache-2.0, same owner), written again in this engine's idiom: `httpx` as `tts.py` uses it, `durable.write_json` for the settings, and a job that ingests the sound as `local_speech.py`'s jobs do.
- **Loopback only.** `normalize_base` takes `http` or `https`, a host of `127.0.0.1`, `localhost` or `::1`, any port, no user or password, no query or fragment, and a path of nothing or `/v1`; anything else is a 422. The client has `trust_env=False` so no system proxy carries the request elsewhere, and `follow_redirects=False` so an app cannot bounce it off the computer.
- **Settings.** `voice-app.json` in the data folder holds `base`, `model`, `voice` and an optional `key`, written with `private=True` because of the key. `settings()` says only whether a key is kept. `PUT` with `key: null` keeps the stored key, `""` removes it.
- **Check.** `GET /v1/models` (`data`) and `GET /v1/audio/voices` (`voices`, as strings or objects with `id`, `voice_id` or `name`), each allowed to be missing. A 401 or 403 from both says the app wants a key; nothing answering at all says so; an app that answers but lists neither is still found, and speaks with its own default model and voice.
- **Speak.** A `speech` job: `POST /v1/audio/speech` with `input`, `speed`, `response_format: "wav"`, and `model` and `voice` when chosen. The reply is streamed, capped at 200 MB, and cancellable between chunks. Its type comes from `Content-Type`, or from the bytes when the header is generic (RIFF/WAVE, ID3 or an MPEG frame, OggS, fLaC); anything else is refused as not a sound. The file is ingested with `source: "voice-app"` and its temporary copy removed. The job's result is `{"media": ...}`, the same as the other speech jobs, so the window adds it to the timeline the same way.
- **Not done.** No MCP tool and no subtitles from the spoken text; an agent can call the routes.
- **Seen.** Driven against a stand-in OpenAI-compatible app on loopback: six refused addresses and three normalised ones, Check with nothing listening, with a missing key, and with models and voices listed, the key kept at mode 600 and never returned, a spoken line ingested as a 0.6 second WAV with model, voice and speed sent as chosen, an HTML reply refused, and a 401 passed on in words. Not run: a real voice app, Windows.

## 2.21.1 · a person can choose the folder models are kept in (`app/paths.py`, `app/storage.py`, `app/local_speech.py`, `setup_local_ai.py`)

- **Why.** Issue 43: on Windows the installed app keeps every model in `%LOCALAPPDATA%\formcut\models`, on the system drive, and the largest catalogue entry alone is 22.19 GB. `FORMCUT_MODELS_DIR` could move them, but only from the environment, which an installed app gives a person no way to set.
Expand Down
4 changes: 3 additions & 1 deletion backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from .track import router as track_router
from .tts import router as tts_router
from .upscale import router as upscale_router
from .voice_app import router as voice_app_router
from .webhooks import router as webhooks_router

mimetypes.add_type("text/javascript", ".js")
Expand All @@ -37,7 +38,7 @@

prefer_bundled()

APP_VERSION = "2.21.1"
APP_VERSION = "2.22.0"

app = FastAPI(title="formcut engine", version=APP_VERSION)

Expand Down Expand Up @@ -170,6 +171,7 @@ def filter(self, record: logging.LogRecord) -> bool:
app.include_router(media_router)
app.include_router(stock_router)
app.include_router(tts_router)
app.include_router(voice_app_router)
app.include_router(presets_router)
from .generate import router as generate_router

Expand Down
264 changes: 264 additions & 0 deletions backend/app/voice_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
"""A voice app on this computer: any program that answers the OpenAI-compatible speech API on a loopback address.

This is how a person uses a voice they cloned in another app (qwentts.cpp, AudioCpp Desktop, VoiceStudio and the like).
The engine only ever talks to 127.0.0.1, localhost or ::1, with no proxy and no redirect, so nothing typed here can send
text off the computer. The address, model and voice are kept in voice-app.json in the data folder; an optional key for
an app that asks for one is kept in the same file, readable by its owner only, and is never returned."""

from __future__ import annotations

import tempfile
import urllib.parse
import uuid
from pathlib import Path

import httpx
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field

from . import jobs
from .durable import read_json, write_json
from .media import ingest_path
from .paths import DATA_DIR

router = APIRouter(prefix="/api/speech/app", tags=["speech"])

STORE = DATA_DIR / "voice-app.json"
DEFAULT_BASE = "http://127.0.0.1:8080"
LOOPBACK = ("127.0.0.1", "localhost", "::1")
MAX_BYTES = 200 * 1024 * 1024
PROBE_SECONDS = 5
SPEAK_SECONDS = 600
AUDIO = {
"audio/wav": ".wav",
"audio/x-wav": ".wav",
"audio/wave": ".wav",
"audio/vnd.wave": ".wav",
"audio/mpeg": ".mp3",
"audio/mp3": ".mp3",
"audio/ogg": ".ogg",
"application/ogg": ".ogg",
"audio/flac": ".flac",
"audio/x-flac": ".flac",
}
GENERIC = ("", "application/octet-stream", "binary/octet-stream", "text/plain", "audio/basic")


def normalize_base(base: str) -> str:
"""The address as http(s)://host[:port] on this computer, or a 422."""
refused = HTTPException(422, "Only an address on this computer is allowed, such as http://127.0.0.1:8080")
text = (base or "").strip()
try:
parts = urllib.parse.urlsplit(text)
host = (parts.hostname or "").lower()
port = parts.port
except ValueError as exc:
raise refused from exc
if parts.scheme not in ("http", "https") or host not in LOOPBACK or parts.username or parts.password:
raise refused
if parts.query or parts.fragment or parts.path.rstrip("/") not in ("", "/v1"):
raise refused
shown = "[::1]" if host == "::1" else host
return f"{parts.scheme}://{shown}" + (f":{port}" if port is not None else "")


def _stored() -> dict:
data = read_json(STORE, {})
return data if isinstance(data, dict) else {}


def settings() -> dict:
stored = _stored()
return {
"base": str(stored.get("base") or DEFAULT_BASE),
"model": str(stored.get("model") or ""),
"voice": str(stored.get("voice") or ""),
"hasKey": bool(str(stored.get("key") or "").strip()),
"default": DEFAULT_BASE,
}


def _client(seconds: float) -> httpx.Client:
# trust_env off: a system proxy must never carry this loopback traffic elsewhere.
return httpx.Client(timeout=seconds, follow_redirects=False, trust_env=False)


def _headers(json_body: bool = False) -> dict:
headers = {"Accept": "application/json"} if not json_body else {"Content-Type": "application/json"}
key = str(_stored().get("key") or "").strip()
if key:
headers["Authorization"] = "Bearer " + key
return headers


def _listing(client: httpx.Client, url: str, refused: list[int]):
try:
response = client.get(url, headers=_headers())
if response.status_code in (401, 403):
refused.append(response.status_code)
return response.json() if response.status_code == 200 else None
except (httpx.HTTPError, ValueError):
return None


def _names(listing, field: str) -> list[dict]:
items = listing.get(field) if isinstance(listing, dict) else listing
found: list[dict] = []
for item in items if isinstance(items, list) else []:
if isinstance(item, str):
ident, name = item, item
elif isinstance(item, dict):
ident = item.get("id") or item.get("voice_id") or item.get("name")
name = item.get("name") or ident
else:
continue
if isinstance(ident, str) and ident and all(entry["id"] != ident for entry in found):
found.append({"id": ident, "name": str(name)})
return found


def check(base: str) -> dict:
clean = normalize_base(base)
refused: list[int] = []
with _client(PROBE_SECONDS) as client:
models = _listing(client, clean + "/v1/models", refused)
voices = _listing(client, clean + "/v1/audio/voices", refused)
if refused and models is None and voices is None:
return {
"ok": False,
"base": clean,
"models": [],
"voices": [],
"error": f"The voice app asks for a key (error {refused[0]}). Enter the key it gives you and press Check again.",
}
if models is None and voices is None:
try:
client.get(clean + "/")
except httpx.HTTPError:
return {
"ok": False,
"base": clean,
"models": [],
"voices": [],
"error": "No voice app answered at that address. Check that it is running and that the address is right.",
}
return {"ok": True, "base": clean, "models": _names(models, "data"), "voices": _names(voices, "voices"), "error": ""}


def _extension(content_type: str, data: bytes) -> str:
declared = (content_type or "").split(";")[0].strip().lower()
if declared in AUDIO:
return AUDIO[declared]
if declared in GENERIC:
if data[:4] == b"RIFF" and data[8:12] == b"WAVE":
return ".wav"
if data[:3] == b"ID3" or (len(data) > 1 and data[0] == 0xFF and (data[1] & 0xE0) == 0xE0):
return ".mp3"
if data[:4] == b"OggS":
return ".ogg"
if data[:4] == b"fLaC":
return ".flac"
raise ValueError("The voice app answered with something that is not a sound.")


def synthesise(text: str, model: str, voice: str, speed: float, cancelled) -> tuple[bytes, str]:
stored = settings()
base = normalize_base(stored["base"])
body: dict = {"input": text, "speed": speed, "response_format": "wav"}
if model:
body["model"] = model
if voice:
body["voice"] = voice
chunks: list[bytes] = []
size = 0
try:
with (
_client(SPEAK_SECONDS) as client,
client.stream("POST", base + "/v1/audio/speech", json=body, headers=_headers(True)) as response,
):
if response.status_code != 200:
said = response.read()[:150].decode("utf-8", "replace").strip()
raise ValueError(f"The voice app refused the request (error {response.status_code})" + (f": {said}" if said else "."))
for chunk in response.iter_bytes():
if cancelled():
raise InterruptedError("Cancelled")
size += len(chunk)
if size > MAX_BYTES:
raise ValueError("The voice app sent back a sound larger than 200 MB, so it was dropped.")
chunks.append(chunk)
content_type = response.headers.get("content-type", "")
except httpx.HTTPError as exc:
raise ValueError("The voice app did not answer. Check that it is running and that its address is right.") from exc
data = b"".join(chunks)
if not data:
raise ValueError("The voice app answered with an empty sound.")
return data, _extension(content_type, data)


class AppSettings(BaseModel):
base: str = DEFAULT_BASE
model: str = Field(default="", max_length=200)
voice: str = Field(default="", max_length=200)
key: str | None = Field(default=None, max_length=500)


class CheckInput(BaseModel):
base: str = DEFAULT_BASE


class AppSpeech(BaseModel):
text: str = Field(min_length=1, max_length=10000)
model: str = Field(default="", max_length=200)
voice: str = Field(default="", max_length=200)
speed: float = Field(default=1, ge=0.25, le=4)


@router.get("")
def get_settings() -> dict:
return settings()


@router.put("")
def save_settings(body: AppSettings) -> dict:
"""The address, model and voice used from now on. key: None keeps the stored key, "" removes it."""
stored = _stored()
data = {
"base": normalize_base(body.base) if body.base.strip() else DEFAULT_BASE,
"model": body.model.strip(),
"voice": body.voice.strip(),
}
key = stored.get("key", "") if body.key is None else body.key.strip()
if key:
data["key"] = key
write_json(STORE, data, private=True)
return settings()


@router.post("/check")
def check_route(body: CheckInput) -> dict:
"""What the app at this address offers: its models and voices, each list empty when the app does not say."""
return check(body.base)


@router.post("/speak", status_code=202)
def speak(body: AppSpeech) -> dict:
stored = settings()
normalize_base(stored["base"])
model = body.model.strip() or stored["model"]
voice = body.voice.strip() or stored["voice"]
words = body.text.strip()
if not words:
raise HTTPException(422, "There is no text to speak")

def operation(_job_id, report, cancelled):
data, extension = synthesise(words, model, voice, body.speed, cancelled)
report(0.9)
draft = Path(tempfile.gettempdir()) / f"formcut_voice_app_{uuid.uuid4().hex}{extension}"
draft.write_bytes(data)
try:
label = "".join(ch for ch in words[:40] if ch.isalnum() or ch in " -_").strip() or "speech"
return {"media": ingest_path(draft, label + extension, {"source": "voice-app", "voice": voice or "default"})}
finally:
draft.unlink(missing_ok=True)

return jobs.submit("speech", operation)
2 changes: 1 addition & 1 deletion form-functions.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"format": "form-functions",
"format_version": 1,
"app": "formcut",
"app_version": "2.21.1",
"app_version": "2.22.0",
"functions": [
{
"id": "transcribe",
Expand Down
Loading
Loading