Thats crazy how fast everything evolves and develops. I used to play with Fooocus - image generation locally - but not really locally - using google colab cloud computing platform. So the problem is that due to that rapid development Fooocus natively is ... well, kind of is not supported? At least with the commands which still exist in Fooocus github page.
I dived into how to solve this and with a bit of discussion with Google Gemini I got a running Fooocus with this:
# ----------------------------------------------------------
# ==============================================================
# FOOOCUS - COMPLETE VERBOSE GOOGLE COLAB INSTALLER
# ==============================================================
# Python 3.10 | NVIDIA T4 | Fooocus 2.5.5
#
# - Installs Miniconda
# - Creates isolated Python environment
# - Installs all Fooocus dependencies
# - Applies tested Gradio/FastAPI compatibility fixes
# - Shows installation progress and errors in real time
# - Downloads models during Fooocus startup
# - Detects and displays the public Gradio URL
# ==============================================================
import os
import sys
import re
import time
import pty
import select
import shutil
import signal
import subprocess
from pathlib import Path
from datetime import datetime
from IPython.display import display, HTML
# ==============================================================
# CONFIGURATION
# ==============================================================
ROOT = "/content"
CONDA_DIR = f"{ROOT}/miniconda"
FOOOCUS_DIR = f"{ROOT}/Fooocus"
INSTALLER = f"{ROOT}/miniconda.sh"
CONDA = f"{CONDA_DIR}/bin/conda"
PYTHON = f"{CONDA_DIR}/envs/fooocus/bin/python"
# True deletes previous installations, models and outputs.
# False reuses existing installations when possible.
CLEAN_INSTALL = False
VERBOSE_PIP = True
os.chdir(ROOT)
os.environ.pop("PYTHONPATH", None)
os.environ["MPLBACKEND"] = "agg"
os.environ["PYTHONUNBUFFERED"] = "1"
os.environ["PYTHONIOENCODING"] = "utf-8"
os.environ["PIP_PROGRESS_BAR"] = "on"
os.environ["TERM"] = "xterm"
START_TIME = time.monotonic()
# ==============================================================
# LOGGING
# ==============================================================
def timestamp():
return datetime.now().strftime("%H:%M:%S")
def log(message):
print(
f"[{timestamp()}] {message}",
flush=True
)
def banner(number, title):
print("\n" + "=" * 72, flush=True)
print(f" STEP {number:02d} | {title}", flush=True)
print("=" * 72, flush=True)
# ==============================================================
# REAL-TIME COMMAND EXECUTION WITH PTY
# ==============================================================
def run(command, cwd=None, env=None, detect_gradio=False):
"""
Execute a command using a pseudo-terminal.
Features:
- Streams stdout and stderr live
- Displays terminal progress bars
- Reports command failures
- Detects Gradio public URLs
- Preserves output during long-running startup
"""
command = [str(x) for x in command]
log("COMMAND: " + " ".join(command))
master, slave = pty.openpty()
started = time.monotonic()
process = None
captured = ""
displayed_urls = set()
url_pattern = re.compile(
r"https://[a-zA-Z0-9-]+\.gradio\.live"
)
try:
process = subprocess.Popen(
command,
cwd=cwd,
env=env,
stdin=subprocess.DEVNULL,
stdout=slave,
stderr=slave,
start_new_session=True,
bufsize=0
)
os.close(slave)
slave = -1
while True:
readable, _, _ = select.select(
[master], [], [], 0.2
)
if readable:
try:
data = os.read(master, 65536)
except OSError:
break
if not data:
break
# Display process output immediately
sys.stdout.write(
data.decode("utf-8", errors="replace")
)
sys.stdout.flush()
if detect_gradio:
captured += data.decode(
"utf-8", errors="replace"
)
# Keep only recent output
captured = captured[-12000:]
for url in url_pattern.findall(captured):
if url not in displayed_urls:
displayed_urls.add(url)
print("\n")
print("=" * 72)
print(" FOOOCUS PUBLIC GRADIO LINK")
print("=" * 72)
print(url)
print("=" * 72)
display(HTML(
'<div style="padding:15px;'
'border:1px solid #999;'
'border-radius:8px;">'
'<h3>Fooocus is available</h3>'
f'<a href="{url}" '
'target="_blank" '
'rel="noopener noreferrer">'
f'{url}</a>'
'</div>'
))
if process.poll() is not None and not readable:
break
return_code = process.wait()
elapsed = time.monotonic() - started
if return_code != 0:
log(f"FAILED: Exit code {return_code}")
raise subprocess.CalledProcessError(
return_code, command
)
log(f"SUCCESS: Completed in {elapsed:.1f} seconds")
except KeyboardInterrupt:
log("Interrupted by user.")
if process is not None and process.poll() is None:
os.killpg(process.pid, signal.SIGTERM)
process.wait()
raise
finally:
os.close(master)
if slave != -1:
os.close(slave)
# ==============================================================
# PIP INSTALLATION HELPER
# ==============================================================
def pip_install(*packages, extra=None):
command = [
PYTHON,
"-m",
"pip",
"install",
"--no-input",
"--progress-bar", "on"
]
if VERBOSE_PIP:
command.append("-v")
command.extend(packages)
if extra:
command.extend(extra)
run(command)
# ==============================================================
# STEP 1 - SYSTEM INFORMATION
# ==============================================================
banner(1, "SYSTEM INFORMATION")
run(["uname", "-a"])
run(["df", "-h", ROOT])
run(["free", "-h"])
run(["nvidia-smi"])
# ==============================================================
# STEP 2 - CLEANUP
# ==============================================================
banner(2, "CHECK PREVIOUS INSTALLATIONS")
if CLEAN_INSTALL:
log("Clean installation enabled.")
for folder in [CONDA_DIR, FOOOCUS_DIR]:
if os.path.exists(folder):
log(f"Removing {folder}")
shutil.rmtree(folder)
else:
log("Existing installations will be reused.")
# ==============================================================
# STEP 3 - DOWNLOAD MINICONDA
# ==============================================================
banner(3, "DOWNLOAD MINICONDA")
if not Path(CONDA).exists():
run([
"wget",
"--show-progress",
"--progress=bar:force",
"-O", INSTALLER,
"https://repo.anaconda.com/miniconda/"
"Miniconda3-latest-Linux-x86_64.sh"
])
log(
"Installer size: "
f"{Path(INSTALLER).stat().st_size / 1024**2:.1f} MB"
)
else:
log("Miniconda already installed. Skipping download.")
# ==============================================================
# STEP 4 - INSTALL MINICONDA
# ==============================================================
banner(4, "INSTALL MINICONDA")
if not Path(CONDA).exists():
run([
"bash",
INSTALLER,
"-b",
"-p", CONDA_DIR
])
else:
log("Using existing Miniconda installation.")
run([CONDA, "--version"])
# ==============================================================
# STEP 5 - ACCEPT CONDA TERMS
# ==============================================================
banner(5, "ACCEPT CONDA TERMS")
for channel in [
"https://repo.anaconda.com/pkgs/main",
"https://repo.anaconda.com/pkgs/r"
]:
run([
CONDA,
"tos",
"accept",
"--override-channels",
"--channel", channel
])
# ==============================================================
# STEP 6 - CREATE PYTHON 3.10 ENVIRONMENT
# ==============================================================
banner(6, "CREATE PYTHON ENVIRONMENT")
if not Path(PYTHON).exists():
run([
CONDA,
"create",
"-n", "fooocus",
"python=3.10",
"-y",
"-v"
])
else:
log("Python environment already exists.")
run([PYTHON, "--version"])
# ==============================================================
# STEP 7 - UPDATE PIP
# ==============================================================
banner(7, "UPDATE PIP")
pip_install("--upgrade", "pip")
run([PYTHON, "-m", "pip", "--version"])
# ==============================================================
# STEP 8 - CLONE FOOOCUS
# ==============================================================
banner(8, "CLONE FOOOCUS")
if not Path(FOOOCUS_DIR).exists():
run([
"git",
"clone",
"--progress",
"https://github.com/lllyasviel/Fooocus.git",
FOOOCUS_DIR
])
else:
log("Fooocus repository already exists.")
run([
"git",
"-C", FOOOCUS_DIR,
"log",
"-1",
"--oneline"
])
# ==============================================================
# STEP 9 - INSTALL FOOOCUS REQUIREMENTS
# ==============================================================
banner(9, "INSTALL FOOOCUS REQUIREMENTS")
requirements = (
f"{FOOOCUS_DIR}/requirements_versions.txt"
)
if not Path(requirements).exists():
raise FileNotFoundError(requirements)
log("Requirements:")
with open(requirements, "r") as file:
print(file.read(), flush=True)
pip_install("-r", requirements)
# ==============================================================
# STEP 10 - VERIFY PYTORCH AND CUDA
# ==============================================================
banner(10, "VERIFY PYTORCH AND CUDA")
torch_check = subprocess.run(
[
PYTHON,
"-c",
(
"import torch; "
"print('Torch:', torch.__version__); "
"print('CUDA:', torch.cuda.is_available()); "
"assert torch.cuda.is_available()"
)
],
check=False
)
if torch_check.returncode != 0:
log("CUDA-enabled PyTorch unavailable.")
log("Installing CUDA PyTorch.")
pip_install(
"torch==2.1.0",
"torchvision==0.16.0",
extra=[
"--index-url",
"https://download.pytorch.org/whl/cu121"
]
)
run(["nvidia-smi"])
# ==============================================================
# STEP 11 - COMPATIBILITY FIXES
# ==============================================================
banner(11, "INSTALL COMPATIBLE UI DEPENDENCIES")
pip_install(
"--force-reinstall",
"pydantic==1.10.15",
"fastapi==0.103.1",
"starlette==0.27.0",
"gradio==3.41.2",
"jinja2==3.1.2",
"markupsafe==2.1.5",
"pyyaml==6.0.1"
)
# ==============================================================
# STEP 12 - VERIFY INSTALLED PACKAGES
# ==============================================================
banner(12, "VERIFY INSTALLED PACKAGES")
run([
PYTHON,
"-c",
"""
import torch
import torchvision
import gradio
import fastapi
import starlette
import pydantic
import jinja2
import yaml
packages = [
("PyTorch", torch.__version__),
("Torchvision", torchvision.__version__),
("Gradio", gradio.__version__),
("FastAPI", fastapi.__version__),
("Starlette", starlette.__version__),
("Pydantic", pydantic.__version__),
("Jinja2", jinja2.__version__),
("PyYAML", yaml.__version__)
]
print("\\nINSTALLED PACKAGES:")
for name, version in packages:
print(f"{name:15} {version}")
print("\\nCUDA STATUS:")
print("Available:", torch.cuda.is_available())
if torch.cuda.is_available():
print("GPU:", torch.cuda.get_device_name(0))
print("CUDA version:", torch.version.cuda)
"""
])
# ==============================================================
# STEP 13 - CHECK DEPENDENCIES
# ==============================================================
banner(13, "CHECK DEPENDENCY CONFLICTS")
check = subprocess.run(
[PYTHON, "-m", "pip", "check"],
check=False
)
if check.returncode != 0:
log("WARNING: Dependency conflicts detected.")
else:
log("No dependency conflicts detected.")
# ==============================================================
# STEP 14 - INSTALLATION SUMMARY
# ==============================================================
banner(14, "INSTALLATION SUMMARY")
elapsed = time.monotonic() - START_TIME
log(f"Installation time: {elapsed / 60:.1f} minutes")
log(f"Fooocus directory: {FOOOCUS_DIR}")
log(f"Python: {PYTHON}")
run(["df", "-h", ROOT])
run(["nvidia-smi"])
# ==============================================================
# STEP 15 - LAUNCH FOOOCUS USING NATIVE COLAB COMMAND
# ==============================================================
banner(15, "LAUNCH FOOOCUS")
print("Starting Fooocus using native Colab execution...")
print("Waiting for Gradio public URL...")
print("Keep this cell running.")
print("=" * 72)
%cd /content/Fooocus
!/content/miniconda/envs/fooocus/bin/python -u launch.py --share
# ----------------------------------------------------------
I hope that it will be useful to someone. Maybe for ... a few days in this very rapid time?
Nav komentāru:
Ierakstīt komentāru