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 @@ -70,7 +70,7 @@ The rest is written by hand.
| render_api.py | /api/render | 13 |
| render_stream.py | /api/render | 1 |
| stock.py | /api/stock | 7 |
| storage.py | /api/storage | 1 |
| storage.py | /api/storage | 3 |
| subtitles.py | /api/subtitles | 2 |
| templates.py | /api/templates | 7 |
| terminal.py | /api/terminal | 2 |
Expand Down
32 changes: 32 additions & 0 deletions .docs/wiki/Models.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,38 @@ Three things are true of all of them:
reach GitHub or Hugging Face; the pin still applies, so a mirror cannot
substitute a different file.

## Where models are kept

The installed app keeps models in the `models` folder of its data folder, which
on Windows is on the system drive. To keep them on another drive, open the home
screen's **Storage** view and press **Choose models folder**. The line above the
list shows the folder and the free space on its drive.

- **It applies after a restart.** The engine settles the folder once, when it
starts. Until then the line says the folder is used after formcut restarts.
- **What goes there.** Every model the app downloads, the downloads of the
Pocket TTS and Chatterbox voices, and the speech runtime when it is next set
up. A speech runtime already made in the data folder keeps working from there;
remove the `ai-runtime` folder and run `setup_local_ai` again to move it.
- **A folder that already holds other files** gets a `formcut-models` folder
inside it, so models never mix with your own files.
- **Copy downloaded models** copies what is already downloaded into the new
folder, with progress. Nothing is removed from the folder in use; delete the
old `models` folder yourself once formcut has restarted and the models show as
installed.
- **Use the default folder** goes back, also after a restart.
- **If the folder cannot be reached** at start (a drive that is not plugged
in), formcut uses the default folder for that run and says so on the line.

`FORMCUT_MODELS_DIR` still wins when it is set, and the buttons are then off.
The choice is one small file, `models-folder.json`, in the data folder.

```
GET /api/storage includes "models": the folder, where it comes from, what applies after a restart
PUT /api/storage/models-folder {"folder": "D:\\AI"} to choose, {"folder": null} for the default
POST /api/storage/models-folder/copy copy the downloaded models there, as a job with progress
```

## Local image models on Apple silicon: Krea 2, FLUX.2 [klein] 4B, LoRA stacks

Krea 2 Turbo and FLUX.2 [klein] 4B are optional, installed from their cards in Studio > Local models and run by
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.0" src="https://img.shields.io/badge/version-v2.21.0-eef0f4?style=flat-square">
<img alt="version v2.21.1" src="https://img.shields.io/badge/version-v2.21.1-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
11 changes: 11 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@

Reasoning behind engine changes, newest first.

## 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.
- **`paths.py`.** `models_place()` returns the folder and where it came from: `environment` (`FORMCUT_MODELS_DIR`, as before, and it wins), `chosen` (the absolute path in `models-folder.json` in the data folder, read by `chosen_models_folder()`), `default` (`default_models_root()`, the earlier body of `models_root()`), or `unreachable` when the chosen folder cannot be made at start, in which case the default folder is used for that run so the engine still starts. `MODELS_DIR` and `MODELS_SOURCE` come from it. `models_root()` stays and returns the folder. Replaced, quoted exactly: `MODELS_DIR = models_root()`.
- **Applies at the next start.** `MODELS_DIR` is a constant that `model_manager`, `klein`, `krea2`, `local_diffusion`, `checkpoints`, `ai_upscale` and the function isolation import, so a change made while the engine runs is written to the file and taken up when it starts again. Making it live would mean every one of those reading the folder on each use.
- **The voices follow only a chosen folder.** `VOICE_CACHE_DIR` and `SPEECH_RUNTIME_DIR` are the models folder (and `ai-runtime` inside it) when the source is `chosen`, and the data folder's `models` and `ai-runtime` otherwise, so nobody who runs from source or sets the variable has a download or a runtime move under them. `_worker_env` hands them to the Pocket TTS and Chatterbox workers as `HF_HOME` and `TORCH_HOME`. Replaced, quoted exactly: ` cache = DATA_DIR / "models" / "huggingface"` and ` return {**env, "HF_HOME": str(cache), "TORCH_HOME": str(DATA_DIR / "models" / "torch")}`.
- **The speech runtime is not moved.** A virtual environment holds absolute paths, so `_venv_python()` uses the runtime in the chosen folder when there is one and otherwise the earlier one in the data folder, which keeps working. `setup_local_ai.py` makes a new one in `SPEECH_RUNTIME_DIR`. Replaced twice in `local_speech.py`, quoted exactly: ` venv = DATA_DIR / "ai-runtime" / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")`; and in `setup_local_ai.py`: ` root = DATA_DIR / "ai-runtime"`.
- **`storage.py`.** `GET /api/storage` gains `models` (`folder` in use, `source`, `default`, `next` for the folder after a restart, `restart`, `free` on that folder's drive, `copyable`) and an area `models folder` when the folder in use is outside the data folder. `PUT /api/storage/models-folder` settles the path in `_settle`: it must be absolute, not a file, outside the data folder and writable (a file is made and removed); a folder that already holds files and whose name does not begin with `formcut` gets `formcut-models` inside it, so a person who picks `D:\` does not get model files among their own. The choice is written beside itself and renamed into place; `{"folder": null}` removes it. With the variable set the route answers 409.
- **Copy, never move.** `POST /api/storage/models-folder/copy` is a `models-copy` job: everything under the folder in use except `ai-runtime`, and the two voice folders when they are elsewhere, into the folder for the next start. Each file is written as `.part` and renamed, a file already there at the same size is kept, links are made again as links (the Hugging Face folder is built from them), and the job stops before it begins when the drive has too little room. Nothing is removed, because the running engine still reads the old folder until it restarts. After the restart `model_manager.adopt_legacy` finds its files already in place and moves nothing.
- **Seen.** Driven against a scratch data folder across two engine starts: the three refusals, the nested `formcut-models`, the copy and a second copy that keeps every file, the folder in use after the restart, the voice folders following it, the default again, and the 409 with the variable set. Not run: Windows, a real second drive, a drive unplugged at start, a copy of tens of gigabytes.

## Unreleased · THIRD-PARTY-NOTICES.txt holds the full licence text of everything that ships (`setup/notices.py`, `app/notices_api.py`)

- **What was missing.** NOTICE and `.docs/wiki/Licences.md` named the components and their licences, but only some of the licence texts travelled with the app (the FFmpeg sidecar's, OpenCV's, a few in copied package metadata). MIT, BSD and Apache terms ask for the text with the binaries.
Expand Down
16 changes: 11 additions & 5 deletions backend/app/local_speech.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from . import jobs
from .media import ingest_path
from .model_manager import ROOT, ready
from .paths import DATA_DIR
from .paths import DATA_DIR, SPEECH_RUNTIME_DIR, VOICE_CACHE_DIR
from .processes import communicate

router = APIRouter(prefix="/api/speech", tags=["speech"])
Expand Down Expand Up @@ -146,14 +146,20 @@ def synthesise_in_engine(args: dict) -> None:
_kokoro_models: dict = {}


def _venv_python() -> Path:
name = "Scripts/python.exe" if sys.platform == "win32" else "bin/python"
chosen, earlier = SPEECH_RUNTIME_DIR / name, DATA_DIR / "ai-runtime" / name
return earlier if earlier.is_file() and not chosen.is_file() else chosen


def interpreter():
# The shipped voice runs in the engine itself when it can; the override
# and the data/ai-runtime venv are for the two PyTorch voices, which are
# an opt-in that creates that second environment only when installed.
if kokoro_in_engine() and not os.environ.get("FORMCUT_AI_PYTHON"):
return ENGINE_RUNTIME
override = os.environ.get("FORMCUT_AI_PYTHON")
venv = DATA_DIR / "ai-runtime" / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
venv = _venv_python()
candidate = override or (str(venv) if venv.is_file() else (sys.executable if not getattr(sys, "frozen", False) else None))
if not candidate:
return None
Expand All @@ -169,7 +175,7 @@ def interpreter():
def runtime() -> str | None:
"""The speech runtime's Python, whatever it has installed: the override, or data/ai-runtime."""
override = os.environ.get("FORMCUT_AI_PYTHON")
venv = DATA_DIR / "ai-runtime" / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
venv = _venv_python()
return override or (str(venv) if venv.is_file() else None)


Expand Down Expand Up @@ -202,9 +208,9 @@ def _worker_env() -> dict:
env[name] = os.pathsep.join(kept)
else:
env.pop(name, None)
cache = DATA_DIR / "models" / "huggingface"
cache = VOICE_CACHE_DIR / "huggingface"
cache.mkdir(parents=True, exist_ok=True)
return {**env, "HF_HOME": str(cache), "TORCH_HOME": str(DATA_DIR / "models" / "torch")}
return {**env, "HF_HOME": str(cache), "TORCH_HOME": str(VOICE_CACHE_DIR / "torch")}


def pocket_voices() -> list[str]:
Expand Down
2 changes: 1 addition & 1 deletion backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@

prefer_bundled()

APP_VERSION = "2.21.0"
APP_VERSION = "2.21.1"

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

Expand Down
41 changes: 36 additions & 5 deletions backend/app/paths.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import os
import sys
from pathlib import Path
Expand All @@ -20,13 +21,43 @@ def data_root() -> Path:
DATA_DIR = data_root()


def models_root() -> Path:
configured = os.environ.get("FORMCUT_MODELS_DIR")
if configured:
return Path(configured).expanduser().resolve()
MODELS_CHOICE = DATA_DIR / "models-folder.json"


def default_models_root() -> Path:
if getattr(sys, "frozen", False):
return DATA_DIR / "models"
return Path(__file__).resolve().parents[2] / "models"


MODELS_DIR = models_root()
def chosen_models_folder() -> Path | None:
try:
folder = json.loads(MODELS_CHOICE.read_text(encoding="utf-8"))["folder"]
except (OSError, ValueError, KeyError, TypeError):
return None
if not isinstance(folder, str) or not Path(folder).is_absolute():
return None
return Path(folder)


def models_place() -> tuple[Path, str]:
configured = os.environ.get("FORMCUT_MODELS_DIR")
if configured:
return Path(configured).expanduser().resolve(), "environment"
chosen = chosen_models_folder()
if chosen is None:
return default_models_root(), "default"
try:
chosen.mkdir(parents=True, exist_ok=True)
except OSError:
return default_models_root(), "unreachable"
return chosen, "chosen"


def models_root() -> Path:
return models_place()[0]


MODELS_DIR, MODELS_SOURCE = models_place()
VOICE_CACHE_DIR = MODELS_DIR if MODELS_SOURCE == "chosen" else DATA_DIR / "models"
SPEECH_RUNTIME_DIR = MODELS_DIR / "ai-runtime" if MODELS_SOURCE == "chosen" else DATA_DIR / "ai-runtime"
137 changes: 135 additions & 2 deletions backend/app/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@
"""

import contextlib
import json
import os
import shutil
from pathlib import Path

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

from .paths import DATA_DIR
from . import jobs
from .paths import DATA_DIR, MODELS_CHOICE, MODELS_DIR, MODELS_SOURCE, VOICE_CACHE_DIR, chosen_models_folder, default_models_root

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

Expand Down Expand Up @@ -54,6 +58,10 @@ def usage() -> dict:
size, count = _size(DATA_DIR / folder)
if size or count:
areas.append({"label": label, "folder": folder, "bytes": size, "files": count, "derived": derived})
if MODELS_DIR.resolve() != (DATA_DIR / "models").resolve():
size, count = _size(MODELS_DIR)
if size or count:
areas.append({"label": "models folder", "folder": str(MODELS_DIR), "bytes": size, "files": count, "derived": True})
free = 0
with contextlib.suppress(OSError):
free = shutil.disk_usage(DATA_DIR).free
Expand All @@ -63,4 +71,129 @@ def usage() -> dict:
"reclaimable": sum(area["bytes"] for area in areas if area["derived"]),
"free": free,
"areas": sorted(areas, key=lambda area: -area["bytes"]),
"models": models_folder(),
}


def _after_restart() -> Path:
if MODELS_SOURCE == "environment":
return MODELS_DIR
return chosen_models_folder() or default_models_root()


def _free(path: Path) -> int:
for place in (path, *path.parents):
if place.exists():
with contextlib.suppress(OSError):
return shutil.disk_usage(place).free
return 0
return 0


def _copy_plan(target: Path) -> list[tuple[Path, Path]]:
plan: list[tuple[Path, Path]] = []
roots = [(MODELS_DIR, target)]
if VOICE_CACHE_DIR.resolve() != MODELS_DIR.resolve():
roots += [(VOICE_CACHE_DIR / name, target / name) for name in ("huggingface", "torch")]
for source, into in roots:
if not source.is_dir() or source.resolve() == into.resolve():
continue
for entry in source.rglob("*"):
relative = entry.relative_to(source)
if relative.parts[0] == "ai-runtime" or entry.name.endswith(".part"):
continue
if entry.is_symlink() or entry.is_file():
plan.append((entry, into / relative))
return plan


def models_folder() -> dict:
after = _after_restart()
restart = after.resolve() != MODELS_DIR.resolve()
return {
"folder": str(MODELS_DIR),
"source": MODELS_SOURCE,
"default": str(default_models_root()),
"next": str(after),
"restart": restart,
"free": _free(after),
"copyable": restart and bool(_copy_plan(after)),
}


class FolderBody(BaseModel):
folder: str | None = None


def _settle(folder: str) -> Path:
path = Path(folder.strip()).expanduser()
if not path.is_absolute():
raise HTTPException(422, "Give the full path of a folder on this computer")
path = path.resolve()
if path.is_file():
raise HTTPException(422, "That is a file. Choose a folder")
data = DATA_DIR.resolve()
if path == data or data in path.parents:
raise HTTPException(422, "Choose a folder outside formcut's data folder, or use the default folder")
try:
if path.is_dir() and any(path.iterdir()) and not path.name.lower().startswith("formcut"):
path = path / "formcut-models"
path.mkdir(parents=True, exist_ok=True)
probe = path / ".formcut-write-check"
probe.write_bytes(b"")
probe.unlink()
except OSError as exc:
raise HTTPException(422, f"formcut cannot write to {path}") from exc
return path


@router.put("/models-folder")
def set_models_folder(body: FolderBody) -> dict:
"""Where models are kept from the next start on: a folder the person chose, or the default again with none."""
if MODELS_SOURCE == "environment":
raise HTTPException(409, "The models folder is set by FORMCUT_MODELS_DIR. Remove that setting to choose a folder here")
if body.folder is None or not body.folder.strip():
MODELS_CHOICE.unlink(missing_ok=True)
return models_folder()
path = _settle(body.folder)
DATA_DIR.mkdir(parents=True, exist_ok=True)
draft = MODELS_CHOICE.with_name(MODELS_CHOICE.name + ".part")
draft.write_text(json.dumps({"folder": str(path)}), encoding="utf-8")
os.replace(draft, MODELS_CHOICE)
return models_folder()


def _copy(target: Path, report, cancelled) -> dict:
plan = _copy_plan(target)
waiting = [
(source, into) for source, into in plan if source.is_symlink() or not into.is_file() or into.stat().st_size != source.stat().st_size
]
total = sum(source.stat().st_size for source, _into in waiting if not source.is_symlink())
if total > _free(target):
raise ValueError(f"{target} has too little free space for the models already downloaded")
done = 0
copied = 0
for source, into in waiting:
if cancelled():
raise InterruptedError("Cancelled")
into.parent.mkdir(parents=True, exist_ok=True)
if source.is_symlink():
if not into.is_symlink() and not into.exists():
os.symlink(os.readlink(source), into)
continue
draft = into.with_name(into.name + ".part")
shutil.copy2(source, draft)
os.replace(draft, into)
copied += 1
done += source.stat().st_size
report(done / total if total else 1.0)
return {"folder": str(target), "copied": copied, "kept": len(plan) - len(waiting), "bytes": done}


@router.post("/models-folder/copy", status_code=202)
def copy_models() -> dict:
"""Copy the models already downloaded into the folder used after the next start. Nothing is removed from the folder in use."""
target = _after_restart()
if target.resolve() == MODELS_DIR.resolve():
raise HTTPException(409, "The models are already in the folder formcut uses")
return jobs.submit("models-copy", lambda _id, report, cancelled: _copy(target, report, cancelled))
4 changes: 2 additions & 2 deletions backend/setup_local_ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ def main():
key, sep, value = line.strip().partition("=")
if sep and key.strip() == "FORMCUT_DATA_DIR":
os.environ["FORMCUT_DATA_DIR"] = value.strip().strip("\"'")
from app.paths import DATA_DIR
from app.paths import SPEECH_RUNTIME_DIR

root = DATA_DIR / "ai-runtime"
root = SPEECH_RUNTIME_DIR
python = root / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
if python.is_file():
probe = subprocess.run([str(python), "-c", "import kokoro_onnx"], capture_output=True, text=True)
Expand Down
1 change: 1 addition & 0 deletions example.env
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ ELEVENLABS_API_KEY=

# Where AI models live. Defaults to models/ at the repository root when run
# from source, and to the data directory's models folder in the packaged app.
# The home screen's Storage view can choose a folder too; this setting wins over it.
# FORMCUT_MODELS_DIR=/absolute/path/to/models

# Missing models download in the background when the engine starts. Set to 0
Expand Down
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.0",
"app_version": "2.21.1",
"functions": [
{
"id": "transcribe",
Expand Down
Loading
Loading