Python
Candado de perfil de Modal
neuregex4f1494552679
diff --git a/.env.example b/.env.exampleindex bf63bde..5013f9b 100644--- a/.env.example+++ b/.env.example@@ -1,3 +1,6 @@+# Modal profile this repo uses (`modal profile list`). Deploys, downloads, the lab and setup_token.py+# stop when another profile is active.+FREEFIELD_MODAL_PROFILE=# Gateway in front of comfy-api-proxy (the Modal URL printed by `modal deploy infra/modal_app.py`,# or http://127.0.0.1:8000 when running the gateway locally).COMFY_BASE_URL=https://YOUR-WORKSPACE--freefield-serve.modal.rundiff --git a/README.md b/README.mdindex a4987a6..972cce6 100644--- a/README.md+++ b/README.md@@ -64,7 +64,7 @@ You need Node 22.6+, Python 3.10+ and a [Modal](https://modal.com) account.# 0. what is missing: Node, Modal login and secrets, Hugging Face license access per model, .envpython tools/doctor.py-# 1. secrets (once)+# 1. secrets (once). Pick the Modal workspace first: in .env, FREEFIELD_MODAL_PROFILE=<profile from `modal profile list`>python tools/setup_token.py # gateway token: Modal secret "freefield" and .env get the same valuemodal secret create huggingface HF_TOKEN=hf_... # accept the LTX-2.5 and FLUX 3 Klein licenses on the Hub firstdiff --git a/infra/common.py b/infra/common.pyindex d835771..5bc356b 100644--- a/infra/common.py+++ b/infra/common.py@@ -16,7 +16,11 @@ from pathlib import Pathimport modal+from infra.modal_profile import enforce as _enforce_profile+ROOT = Path(__file__).resolve().parent.parent+if modal.is_local(): # on your machine, before modal run/deploy creates anything; never inside containers+ _enforce_profile(ROOT)COMFYUI_COMMIT = "e3bee7ffcb7d6547ed0bcd15221792f3b8646b17" # 2026-10-19, ComfyUI 0.42.0+COMFY_API_PROXY = "comfy-api-proxy==0.1.6"COMFY_DIR = "/comfyui"diff --git a/infra/modal_profile.py b/infra/modal_profile.pynew file mode 100644index 0000000..16dc5a9--- /dev/null+++ b/infra/modal_profile.py@@ -0,0 +1,62 @@+"""Which Modal profile a command will act on, and whether it is the one this repo is pinned to.++Modal takes the profile from MODAL_PROFILE, otherwise from the section marked `active = true`+in ~/.modal.toml (MODAL_CONFIG_PATH moves that file). Freefield pins its own with+FREEFIELD_MODAL_PROFILE, in the environment or in .env, so a deploy, a download or a lab run+cannot land in another workspace by accident. Only section names are read, never tokens.+No Modal import here: tools/doctor.py and tools/setup_token.py use it too.+"""+from __future__ import annotations++import os+import re+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+++def active_profile() -> str | None:+ """The profile Modal will use, or None when explicit tokens (MODAL_TOKEN_ID) override profiles."""+ if os.environ.get("MODAL_TOKEN_ID"):+ return None+ if os.environ.get("MODAL_PROFILE"):+ return os.environ["MODAL_PROFILE"].strip()+ path = Path(os.environ.get("MODAL_CONFIG_PATH") or Path.home() / ".modal.toml")+ if not path.exists():+ return None+ section = None+ for raw in path.read_text(encoding="utf-8").splitlines():+ line = raw.strip()+ header = re.match(r"""^\[\s*["']?([^"'\]]+?)["']?\s*\]$""", line)+ if header:+ section = header[1]+ elif section and re.match(r"^active\s*=\s*true$", line, flags=re.I):+ return section+ return "default" # Modal's own fallback when no section is marked active+++def pinned_profile(root: Path = ROOT) -> str | None:+ """FREEFIELD_MODAL_PROFILE from the environment, else from .env; None when not set."""+ value = os.environ.get("FREEFIELD_MODAL_PROFILE", "").strip()+ if not value and (root / ".env").exists():+ m = re.search(r"^\s*FREEFIELD_MODAL_PROFILE\s*=\s*(\S+)\s*$", (root / ".env").read_text(encoding="utf-8"), flags=re.M)+ value = m[1].strip("\"'") if m else ""+ return value or None+++def check(root: Path = ROOT) -> tuple[str | None, str | None, bool]:+ """(active, pinned, ok). ok is False only when both are known and differ."""+ active, pinned = active_profile(), pinned_profile(root)+ return active, pinned, pinned is None or active is None or active == pinned+++def enforce(root: Path = ROOT) -> None:+ """Stop before Modal creates anything in the wrong workspace; otherwise say where things go."""+ active, pinned, ok = check(root)+ if not ok:+ raise SystemExit(f'Modal profile "{active}" is active, but this repo is pinned to "{pinned}" '+ f"(FREEFIELD_MODAL_PROFILE). Switch with: modal profile activate {pinned}")+ where = active if active else "chosen by MODAL_TOKEN_ID"+ hint = "" if pinned else " (pin it with FREEFIELD_MODAL_PROFILE=<profile> in .env)"+ print(f"Modal profile: {where}{hint}", file=sys.stderr)diff --git a/tools/doctor.py b/tools/doctor.pyindex 0e047b4..178c5dd 100644--- a/tools/doctor.py+++ b/tools/doctor.py@@ -60,6 +60,17 @@ def check_modal() -> None:report(BAD, "Modal CLI not installed for this Python", f"{Path(sys.executable).name} -m pip install modal")returnreport(OK, f"Modal CLI {out.split()[-1] if out else ''}".strip())+ sys.path.insert(0, str(ROOT))+ from infra.modal_profile import check+ active, pinned, ok = check(ROOT)+ if not ok:+ report(BAD, f'Modal profile "{active}" is active, but .env pins "{pinned}"', f"modal profile activate {pinned}")+ return # the secrets below would be the wrong workspace's+ if pinned:+ report(OK, f'Modal profile "{active or pinned}" (pinned in .env)')+ else:+ report(WARN, f'Modal profile "{active}" is active and nothing pins this repo to it',+ "add FREEFIELD_MODAL_PROFILE=<profile> to .env (modal profile list shows them)")code, out = run([sys.executable, "-m", "modal", "secret", "list", "--json"], timeout=90)if code != 0:report(BAD, "Modal is not logged in (or unreachable)", "modal setup")@@ -74,9 +85,9 @@ def check_modal() -> None:}for name, fix in fixes.items():if name in names:- report(OK, f'Modal secret "{name}"')+ report(OK, f'Modal secret "{name}" in profile "{active}"')else:- report(BAD, f'Modal secret "{name}" missing', fix)+ report(BAD, f'Modal secret "{name}" missing in profile "{active}"', fix)def hf_token() -> str | None:diff --git a/tools/setup_token.py b/tools/setup_token.pyindex 87325b8..4e3e101 100644--- a/tools/setup_token.py+++ b/tools/setup_token.py@@ -35,6 +35,13 @@ def main(argv: list[str] | None = None) -> int:token = secrets.token_urlsafe(32)if not a.env_only:+ sys.path.insert(0, str(ROOT))+ from infra.modal_profile import check+ active, pinned, ok = check(ROOT)+ if not ok:+ print(f'Modal profile "{active}" is active, but .env pins "{pinned}"; nothing changed. '+ f"Switch with: modal profile activate {pinned}", file=sys.stderr)+ return 1cmd = [sys.executable, "-m", "modal", "secret", "create", "freefield", f"FREEFIELD_TOKEN={token}", "--force"]try:r = subprocess.run(cmd, capture_output=True, text=True, timeout=120)@@ -45,7 +52,7 @@ def main(argv: list[str] | None = None) -> int:print((r.stderr or r.stdout).strip(), file=sys.stderr)print('the Modal secret "freefield" was not updated, so .env was left as it was', file=sys.stderr)return 1- print('stored the token in the Modal secret "freefield"')+ print(f'stored the token in the Modal secret "freefield" of profile "{active}"')text = env.read_text(encoding="utf-8")line = f"FREEFIELD_TOKEN={token}"