diff --git a/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md b/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md index a6b9a6b7..ddf30016 100644 --- a/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md +++ b/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md @@ -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 | diff --git a/.docs/wiki/Models.md b/.docs/wiki/Models.md index 81fa7568..dbaaf24c 100644 --- a/.docs/wiki/Models.md +++ b/.docs/wiki/Models.md @@ -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 diff --git a/README.md b/README.md index ce6d4da7..b1547071 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@
-
+
diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md
index 372f6414..e277173e 100644
--- a/backend/HASHOUT_LOG.md
+++ b/backend/HASHOUT_LOG.md
@@ -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.
diff --git a/backend/app/local_speech.py b/backend/app/local_speech.py
index 4ca48fda..6a860671 100644
--- a/backend/app/local_speech.py
+++ b/backend/app/local_speech.py
@@ -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"])
@@ -146,6 +146,12 @@ 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
@@ -153,7 +159,7 @@ def interpreter():
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
@@ -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)
@@ -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]:
diff --git a/backend/app/main.py b/backend/app/main.py
index d3ab7c43..65d7a474 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -37,7 +37,7 @@
prefer_bundled()
-APP_VERSION = "2.21.0"
+APP_VERSION = "2.21.1"
app = FastAPI(title="formcut engine", version=APP_VERSION)
diff --git a/backend/app/paths.py b/backend/app/paths.py
index 24ffe013..ebab7988 100644
--- a/backend/app/paths.py
+++ b/backend/app/paths.py
@@ -1,3 +1,4 @@
+import json
import os
import sys
from pathlib import Path
@@ -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"
diff --git a/backend/app/storage.py b/backend/app/storage.py
index 24f2d94a..d4c623ef 100644
--- a/backend/app/storage.py
+++ b/backend/app/storage.py
@@ -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"])
@@ -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
@@ -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))
diff --git a/backend/setup_local_ai.py b/backend/setup_local_ai.py
index 4c49cdd7..e9e836dc 100644
--- a/backend/setup_local_ai.py
+++ b/backend/setup_local_ai.py
@@ -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)
diff --git a/example.env b/example.env
index 38d2bee2..b3f7ee64 100644
--- a/example.env
+++ b/example.env
@@ -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
diff --git a/form-functions.json b/form-functions.json
index 55cbb71a..d12a3085 100644
--- a/form-functions.json
+++ b/form-functions.json
@@ -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",
diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md
index 436946df..b78659f3 100644
--- a/frontend/HASHOUT_LOG.md
+++ b/frontend/HASHOUT_LOG.md
@@ -2,6 +2,14 @@
Reasoning behind interface changes, newest first.
+## 2.21.1 · Storage chooses the models folder (`ui/start-screen.ts` renderStorage, modelsLine, the storage branch of show; `i18n/en.json`, `de.json`, `es.json`)
+
+- **What it adds.** The home screen's Storage view gains a line under the usage summary, `Models folder: