Spaces:
Running on Zero
Running on Zero
File size: 6,586 Bytes
610a02a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | from __future__ import annotations
import math
import random
from typing import Any
from src import config
from src.config import GenerationParams
from src.errors import UserFacingError
def _as_int(name: str, value: Any, lo: int, hi: int) -> int:
if value is None:
raise UserFacingError(f"Missing value for {name!r}.")
try:
n = int(round(float(value)))
except (TypeError, ValueError):
raise UserFacingError(
f"Invalid {name!r}: expected a number in [{lo}, {hi}].", details=str(value)
)
if n < lo or n > hi:
raise UserFacingError(
f"Invalid {name!r}: {n} is outside the allowed range [{lo}, {hi}]."
)
return n
def _as_float(name: str, value: Any, lo: float, hi: float) -> float:
if value is None:
raise UserFacingError(f"Missing value for {name!r}.")
try:
n = float(value)
except (TypeError, ValueError):
raise UserFacingError(
f"Invalid {name!r}: expected a number in [{lo}, {hi}].", details=str(value)
)
if not math.isfinite(n):
raise UserFacingError(f"Invalid {name!r}: must be a finite number.")
if n < lo or n > hi:
raise UserFacingError(
f"Invalid {name!r}: {n} is outside the allowed range [{lo}, {hi}]."
)
return n
def _clamp_int(name: str, value: Any, lo: int, hi: int) -> tuple[int, str | None]:
"""Return clamped int and optional warning if clamped from out-of-range input."""
try:
n = int(round(float(value)))
except (TypeError, ValueError):
raise UserFacingError(
f"Invalid {name!r}: expected a number; got {value!r}.", details=repr(value)
)
if n < lo:
return lo, f"{name} was {n} (below minimum {lo}); using {lo}."
if n > hi:
return hi, f"{name} was {n} (above maximum {hi}); using {hi}."
return n, None
def _clamp_float(
name: str,
value: Any,
lo: float,
hi: float,
*,
step: float | None = None,
decimals: int | None = None,
) -> tuple[float, str | None]:
try:
n = float(value)
except (TypeError, ValueError):
raise UserFacingError(
f"Invalid {name!r}: expected a number; got {value!r}.", details=repr(value)
)
if not math.isfinite(n):
raise UserFacingError(f"Invalid {name!r}: must be a finite number.")
warn = None
if n < lo:
warn = f"{name} was {n} (below minimum {lo}); using {lo}."
n = lo
elif n > hi:
warn = f"{name} was {n} (above maximum {hi}); using {hi}."
n = hi
if step is not None and step > 0:
# Snap to grid relative to lo
n = lo + round((n - lo) / step) * step
n = min(hi, max(lo, n))
if decimals is not None:
n = round(n, decimals)
return n, warn
def _normalize_sampler(name: str) -> tuple[str, str | None]:
s = (name or "").strip()
if not s:
return config.DEFAULT_SAMPLER, f"Empty sampler: using default {config.DEFAULT_SAMPLER!r}."
if s in config.SAMPLER_CHOICES:
return s, None
# Common alias from Z-Image / Z-Anime docs
if s in ("euler_a", "euler-a", "euler a"):
return "euler_ancestral", (
f"Sampler {name!r} is not a known id; remapped to 'euler_ancestral'."
)
return config.DEFAULT_SAMPLER, (
f"Sampler {name!r} is not in the supported set for this Space; using "
f"{config.DEFAULT_SAMPLER!r}. Supported examples: {', '.join(config.SAMPLER_CHOICES[:6])}…"
)
def _normalize_scheduler(name: str) -> tuple[str, str | None]:
s = (name or "").strip()
if not s:
return config.DEFAULT_SCHEDULER, f"Empty scheduler: using default {config.DEFAULT_SCHEDULER!r}."
if s in config.SCHEDULER_CHOICES:
return s, None
return config.DEFAULT_SCHEDULER, (
f"Scheduler {name!r} is not in the supported set for this Space; using "
f"{config.DEFAULT_SCHEDULER!r}."
)
def validate_and_clamp(
*,
prompt: str,
negative_prompt: str | None,
width: Any,
height: Any,
steps: Any,
cfg: Any,
batch_size: Any,
sampler_name: str | None,
scheduler: str | None,
denoise: Any,
seed: Any = None,
randomize_seed: bool = True,
) -> GenerationParams:
"""
Validate and clamp all user parameters; collect non-fatal warnings.
Rejects unparseable types with clear messages.
"""
warnings: list[str] = []
p = (prompt or "").strip()
if not p:
raise UserFacingError("Prompt must not be empty.")
if len(p) > 20_000:
raise UserFacingError("Prompt is too long (max 20,000 characters).")
neg = (negative_prompt or "").strip()
if len(neg) > 20_000:
raise UserFacingError("Negative prompt is too long (max 20,000 characters).")
w, wmsg = _clamp_int("width", width, config.MIN_WH, config.MAX_WH)
if wmsg:
warnings.append(wmsg)
h, hmsg = _clamp_int("height", height, config.MIN_WH, config.MAX_WH)
if hmsg:
warnings.append(hmsg)
st, stmsg = _clamp_int("steps", steps, config.MIN_STEPS, config.MAX_STEPS)
if stmsg:
warnings.append(stmsg)
cfg_v, cmsg = _clamp_float("cfg", cfg, config.MIN_CFG, config.MAX_CFG, step=0.1, decimals=1)
if cmsg:
warnings.append(cmsg)
d_v, dmsg = _clamp_float(
"denoise", denoise, config.MIN_DENOISE, config.MAX_DENOISE, step=0.01, decimals=2
)
if dmsg:
warnings.append(dmsg)
bs, bmsg = _clamp_int("batch_size", batch_size, config.MIN_BATCH, config.MAX_BATCH)
if bmsg:
warnings.append(bmsg)
sampler, sm = _normalize_sampler(sampler_name or "")
if sm:
warnings.append(sm)
sched, sc = _normalize_scheduler(scheduler or "")
if sc:
warnings.append(sc)
if randomize_seed:
seed_value = random.randint(config.MIN_SEED, config.MAX_SEED)
else:
seed_value, seed_msg = _clamp_int("seed", seed, config.MIN_SEED, config.MAX_SEED)
if seed_msg:
warnings.append(seed_msg)
return GenerationParams(
prompt=p,
negative_prompt=neg,
width=w,
height=h,
steps=st,
cfg=cfg_v,
batch_size=bs,
sampler_name=sampler,
scheduler=sched,
denoise=d_v,
seed=seed_value,
warnings=tuple(warnings),
)
|