caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

273 lines
12 KiB
Python

"""stills.py — text prompt → 1080x1920 PNG via FLUX.1-schnell (4-bit, Apple Silicon, $0).
Model: madroid/flux.1-schnell-mflux-4bit (pre-quantized 4-bit mflux checkpoint, Apache-2.0 base).
Quantisation: pre-quantized 4-bit; no re-quantization needed on first run.
Backend: mflux — runs on any M-series Mac, no GPU required.
Usage
-----
# activate the venv first:
source .venv/bin/activate
python stills.py "prompt text" [--out PATH] [--seed N] [--lora PATH] [--steps N]
# or import:
from stills import generate_still
path = generate_still("a rainy Istanbul street at night", out="rain.png", seed=42)
Disk requirement
----------------
The pre-quantized checkpoint downloads to ~/.cache/huggingface/hub/ on first run.
madroid/flux.1-schnell-mflux-4bit (pre-quantized mflux format)
transformer/ text_encoder/ text_encoder_2/ vae/ tokenizers
─────────────────────────────────
total download ~9.85 GB
Minimum free space recommended: 8 GB reserve after the download.
"""
from __future__ import annotations
import argparse
import shutil
import subprocess
import sys
import time
from pathlib import Path
# ── constants ──────────────────────────────────────────────────────────────────
WIDTH = 1080
HEIGHT = 1920
DEFAULT_STEPS = 4 # schnell recommended: 2-4 steps
# Pre-quantized 4-bit checkpoint from HuggingFace — no --quantize flag needed.
# Apache-2.0 base (FLUX.1-schnell); checkpoint by madroid.
HF_CHECKPOINT = "madroid/flux.1-schnell-mflux-4bit"
BASE_MODEL = "schnell"
MIN_FREE_GB = 8.0 # never drop below this
DOWNLOAD_GB = 10.0 # pre-quantized checkpoint download size
def _free_gb(path: str = "/") -> float:
"""Return available disk space in GB for the filesystem containing *path*."""
stat = shutil.disk_usage(path)
return stat.free / (1024 ** 3)
def _hf_cache_has_model() -> bool:
"""True when the madroid pre-quantized FLUX.1-schnell checkpoint is cached."""
try:
from huggingface_hub.constants import HF_HUB_CACHE
cache = Path(HF_HUB_CACHE)
# Pre-quantized checkpoint: madroid/flux.1-schnell-mflux-4bit
repo_dir = cache / "models--madroid--flux.1-schnell-mflux-4bit"
if not repo_dir.exists():
return False
# Check for transformer safetensors (the largest component) — ensures full download
return any(repo_dir.glob("snapshots/**/transformer/*.safetensors"))
except Exception:
return False
def _saved_checkpoint(out_dir: Path | None) -> Path | None:
"""Return an existing local mflux 4-bit checkpoint path, or None (legacy support)."""
candidates = [
Path.home() / ".cache" / "mflux" / "flux-schnell-4bit",
Path.cwd() / "flux-schnell-4bit",
]
if out_dir:
candidates.insert(0, out_dir)
for p in candidates:
if p.is_dir() and any(p.glob("*.safetensors")):
return p
return None
def check_disk(budget_gb: float = DOWNLOAD_GB) -> None:
"""Raise SystemExit with a clear message if there is not enough free space."""
free = _free_gb()
needed = budget_gb + MIN_FREE_GB
if free < needed:
print(
f"\n[stills] DISK CHECK FAILED\n"
f" Free disk : {free:.1f} GB\n"
f" Needed : {needed:.1f} GB "
f"({budget_gb:.0f} GB model + {MIN_FREE_GB:.0f} GB minimum reserve)\n"
f"\n"
f" Model: {HF_CHECKPOINT} (~{DOWNLOAD_GB:.0f} GB, pre-quantized 4-bit)\n"
f" Free {needed:.0f} GB before first run (clear npm/pip/pnpm/Homebrew caches).\n"
f" Subsequent runs use the HF cache and need only {MIN_FREE_GB:.0f} GB free.\n",
file=sys.stderr,
)
sys.exit(1)
def generate_still(
prompt: str,
out: str | Path | None = None,
seed: int | None = None,
lora: str | None = None,
steps: int = DEFAULT_STEPS,
saved_model: str | None = None,
init_image: str | Path | None = None,
init_strength: float = 0.5,
) -> Path:
"""Generate a 1080x1920 PNG and return its path.
Parameters
----------
prompt : str
Text description of the image.
out : path, optional
Output file path. Defaults to ``still_<seed>.png`` in the current dir.
seed : int, optional
RNG seed for reproducibility.
lora : path, optional
Path to a .safetensors LoRA adapter (character LoRA).
steps : int
Number of diffusion steps (2-4 recommended for schnell).
saved_model : path, optional
Override model path/HF repo. Defaults to HF_CHECKPOINT.
init_image : path, optional
Img2img init image for visual consistency across shots.
init_strength : float
Img2img strength (0.0 = copy init image, 1.0 = ignore it). Default 0.5.
"""
# ── disk check ─────────────────────────────────────────────────────────────
if not _hf_cache_has_model() and _saved_checkpoint(None) is None and saved_model is None:
check_disk(DOWNLOAD_GB)
# ── resolve output path ────────────────────────────────────────────────────
if out is None:
seed_part = str(seed) if seed is not None else "rand"
out = Path(f"still_{seed_part}.png")
out = Path(out)
out.parent.mkdir(parents=True, exist_ok=True)
# ── resolve model ──────────────────────────────────────────────────────────
model_id = saved_model if saved_model else HF_CHECKPOINT
# ── build mflux-generate command ───────────────────────────────────────────
venv_python = Path(sys.executable)
venv_bin = venv_python.parent
mflux_bin = venv_bin / "mflux-generate"
cmd: list[str] = [
str(mflux_bin),
"--model", str(model_id),
"--base-model", BASE_MODEL,
# No --quantize: the checkpoint is already pre-quantized 4-bit
"--width", str(WIDTH),
"--height", str(HEIGHT),
"--steps", str(steps),
"--output", str(out),
"--prompt", prompt,
]
if seed is not None:
cmd += ["--seed", str(seed)]
if lora:
cmd += ["--lora", str(lora)]
if init_image and Path(str(init_image)).exists():
cmd += ["--image", str(init_image), str(init_strength)]
# limit MLX cache to leave memory for the system
cmd += ["--mlx-cache-limit-gb", "12"]
# ── run ───────────────────────────────────────────────────────────────────
print(f"[stills] generating: {out}")
print(f"[stills] model : {model_id}")
print(f"[stills] prompt : {prompt[:80]}{'...' if len(prompt) > 80 else ''}")
t0 = time.monotonic()
result = subprocess.run(cmd, capture_output=False, text=True)
elapsed = time.monotonic() - t0
if result.returncode != 0:
sys.exit(f"[stills] mflux-generate failed (exit {result.returncode})")
if not out.exists():
sys.exit(f"[stills] output not created: {out}")
size_kb = out.stat().st_size // 1024
print(f"[stills] done in {elapsed:.1f} s -> {out} ({size_kb} KB)")
return out
# ── test stills ───────────────────────────────────────────────────────────────
TEST_STILLS = [
{
"key": "oxhan-hero-phoenix",
"seed": 1,
"prompt": (
"Vertical 9:16 medium shot, waist-up, cinematic mid-2000s game cutscene still. "
"A Turkish man, late 20s, tanned olive skin, messy swept-back black hair, strong brows, "
"light stubble, smug confident grin, black fingerless leather gloves, silver rings, a black "
"tespih (prayer beads) on his left wrist. He stands in a single hard white spotlight on a "
"glossy black stage floor. He wears a relaxed oversized BLACK crewneck sweatshirt; centred "
"on the chest is a dark-red (#7A0F14) flame-feathered phoenix rising behind two lines of "
"bone-white swash serif text reading exactly 'You met me at a very' / 'Turkish time in my "
"life.' — print fully visible and legible. Smooth waxy skin shading, cinematic rim light, "
"soft bloom. No other text, no logos, no watermark."
),
},
{
"key": "bidstage-tenders-closing",
"seed": 2,
"prompt": (
"Vertical 9:16 editorial illustration, clean modern flat design. A bold headline reads "
"'Tenders closing this week' in white on a deep navy background. Below it, a grid of three "
"tender cards each showing a project category icon (construction, IT services, healthcare "
"supply), a short project title in bold white text, a progress bar near 100%, and a red "
"countdown badge showing '2 days left', '1 day left', '3 days left'. Bottom: the Bidstage "
"wordmark in white. Minimalist, business-professional, no gradients, no people, no photos."
),
},
]
def run_tests(out_dir: str = "test-stills") -> None:
"""Generate the two test stills and print a summary."""
out_path = Path(out_dir)
out_path.mkdir(parents=True, exist_ok=True)
results = []
for spec in TEST_STILLS:
dest = out_path / f"{spec['key']}.png"
path = generate_still(spec["prompt"], out=dest, seed=spec["seed"])
results.append((spec["key"], path))
print("\n[stills] test summary")
for key, path in results:
print(f" {key:40s} {path}")
# ── CLI ───────────────────────────────────────────────────────────────────────
def main(argv: list[str] | None = None) -> None:
ap = argparse.ArgumentParser(
description="Generate a 1080x1920 PNG with FLUX.1-schnell (4-bit, Apple Silicon, $0).",
epilog="Run --test to generate the two built-in test stills.",
)
ap.add_argument("prompt", nargs="?", help="text prompt")
ap.add_argument("--out", "-o", default=None, help="output PNG path (default: still_<seed>.png)")
ap.add_argument("--seed", type=int, default=None)
ap.add_argument("--lora", default=None, help="LoRA .safetensors path")
ap.add_argument("--steps", type=int, default=DEFAULT_STEPS)
ap.add_argument("--saved-model", default=None, dest="saved_model",
help="path to a mflux-saved 4-bit checkpoint (skips HF download)")
ap.add_argument("--test", action="store_true", help="generate the 2 built-in test stills")
ap.add_argument("--test-dir", default="test-stills", dest="test_dir",
help="output directory for --test (default: test-stills)")
a = ap.parse_args(argv)
if a.test:
run_tests(a.test_dir)
return
if not a.prompt:
ap.error("provide a prompt or use --test")
generate_still(
prompt=a.prompt,
out=a.out,
seed=a.seed,
lora=a.lora,
steps=a.steps,
saved_model=a.saved_model,
)
if __name__ == "__main__":
main()