"""Inference engine orchestrating Anima pipeline, dual default LoRAs, Civitai API hot-mount, and ZeroGPU xlarge reservation.""" from __future__ import annotations import datetime as dt import math import random import shutil import time from typing import Any from PIL import Image, ImageDraw from anima_studio.catalog import BUILTIN_DEFAULT_KEYS, CatalogRepository, ReserveConfigStore from anima_studio.civitai import ( LoraArtifactStore, inspect_civitai, validate_anima_compatibility, ) from anima_studio.config import ( AUTO_MAX_RESERVE_SECONDS, AUTO_MIN_RESERVE_SECONDS, DEFAULT_HIGHRES_ENABLED, DEFAULT_HIGHRES_SCALE, DEFAULT_QUALITY_ENABLED, DEFAULT_QUALITY_SCALE, DEFAULT_RATING, MAX_LORA_STRENGTH, MAX_RESERVE_SECONDS, MIN_LORA_STRENGTH, MIN_RESERVE_SECONDS, PROMPT_PREFIX, ROPE_TOKENS, SCHEDULERS, AppSettings, ) from anima_studio.logging_utils import get_logger from anima_studio.models import GenerationTelemetry, LoraSpec, ReserveStatus from anima_studio.prompt import compose_lora_stack, compose_prompt logger = get_logger("engine") def parse_canvas_size(size: str) -> tuple[int, int]: """Parse ``'WxH'`` string into validated ``(width, height)`` pixel integers.""" raw = (size or "").strip().lower() parts = raw.split("x") if len(parts) != 2: raise ValueError(f"Invalid resolution format (expected WxH, e.g. 1024x1024): {size!r}") try: width, height = int(parts[0]), int(parts[1]) except ValueError as exc: raise ValueError(f"Resolution dimensions must be integers: {size!r}") from exc if not (256 <= width <= 4096 and 256 <= height <= 4096): raise ValueError(f"Resolution sides must be between 256 and 4096 pixels: {width}x{height}") return width, height def padded_multiple_of_16(width: int, height: int) -> tuple[int, int]: """Pad canvas sides upward to multiples of 16 (8x VAE × 2x2 DiT patch).""" return (-(-width // 16) * 16, -(-height // 16) * 16) def estimate_render_seconds(size: str, steps: float) -> float: """Empirical GPU execution time model for Anima renders.""" width, height = parse_canvas_size(size) megapixels = (width * height) / 1e6 return max(1.0, float(steps) * (0.10 + 0.29 * megapixels)) def booking_seconds(size: str, steps: float) -> int: """Automatic ZeroGPU xlarge lease declaration (clamped to [20, 150]s).""" measured = estimate_render_seconds(size, steps) return int(max(AUTO_MIN_RESERVE_SECONDS, min(AUTO_MAX_RESERVE_SECONDS, round(measured * 1.5)))) def resolve_lease_seconds( size: str, steps: float, *, request_reserve: float | int | None = 0, default_reserve: int = 0, ) -> int: """Compute final ZeroGPU duration lease in seconds.""" if request_reserve is not None: try: req_val = int(round(float(request_reserve))) except (TypeError, ValueError): req_val = 0 if req_val > 0: return max(MIN_RESERVE_SECONDS, min(MAX_RESERVE_SECONDS, req_val)) if default_reserve > 0: return max(MIN_RESERVE_SECONDS, min(MAX_RESERVE_SECONDS, int(default_reserve))) return booking_seconds(size, steps) def format_png_parameters( composed_prompt: str, negative_prompt: str, steps: int, scheduler: str, guidance: float, seed: int, width: int, height: int, ) -> str: """Build standard A1111-compatible ``parameters`` metadata string for PNG chunks.""" meta_tail = ( f"Steps: {steps}, Sampler: {scheduler}, CFG scale: {guidance:g}, Seed: {seed}, " f"Size: {width}x{height}, Model: Anima-Base-v1.0-Diffusers" ) if negative_prompt.strip(): return f"{composed_prompt}\nNegative prompt: {negative_prompt.strip()}\n{meta_tail}" return f"{composed_prompt}\n{meta_tail}" def disk_usage_summary(path: Any) -> dict[str, float | str]: """Return human-readable GiB disk usage metrics for ``path``.""" total, used, free = shutil.disk_usage(path) gib = float(1 << 30) return { "path": str(path), "total_gib": round(total / gib, 2), "used_gib": round(used / gib, 2), "free_gib": round(free / gib, 2), "used_pct": round((used / total) * 100.0, 1) if total else 0.0, } def _render_mock_preview( width: int, height: int, seed: int, scheduler: str, composed_prompt: str, ) -> Image.Image: """Synthesize a studio preview canvas when running in local CPU mock mode.""" rng = random.Random(seed) palettes = [ ((20, 26, 48), (67, 56, 202), (165, 180, 252)), ((16, 36, 42), (15, 118, 110), (110, 231, 183)), ((36, 22, 46), (109, 40, 217), (216, 180, 254)), ((20, 30, 52), (37, 99, 235), (147, 197, 253)), ] c_top, c_mid, c_accent = rng.choice(palettes) img = Image.new("RGB", (width, height), c_top) draw = ImageDraw.Draw(img) for y in range(height): t = y / max(height - 1, 1) r = int(c_top[0] * (1 - t) + c_mid[0] * t) g = int(c_top[1] * (1 - t) + c_mid[1] * t) b = int(c_top[2] * (1 - t) + c_mid[2] * t) draw.line([(0, y), (width, y)], fill=(r, g, b)) cx, cy = width // 2, height // 2 radius = min(width, height) // 3 for idx in range(3): rad = radius - idx * 24 if rad > 16: draw.ellipse( [cx - rad, cy - rad, cx + rad, cy + rad], outline=c_accent, width=2 if idx == 0 else 1, ) summary_lines = [ "A-IMAGE MOCK PREVIEW", f"Canvas: {width}x{height} | Seed: {seed} | Sampler: {scheduler}", f"Prompt: {composed_prompt[:72]}...", ] y_cursor = 32 for line in summary_lines: draw.text((32, y_cursor), line, fill=(238, 242, 255)) y_cursor += 22 return img class AnimaStudioEngine: """Production & mock-capable Anima Modular Pipeline engine.""" def __init__(self, settings: AppSettings) -> None: self.settings = settings self.store = LoraArtifactStore(settings) self.catalog = CatalogRepository(runtime_file=settings.runtime_loras_file) self.reserve_store = ReserveConfigStore( settings.runtime_config_file, gpu_size=settings.gpu_size, quota_factor=settings.quota_factor, initial_reserve=settings.initial_reserve_seconds, ) self.pipe: Any = None self.manager: Any = None self._schedulers: dict[str, Any] = {} self._boot() def report_disk(self) -> dict[str, float | str]: info = disk_usage_summary(self.settings.local_dir) logger.info( "[disk] %s: %.1f GiB free of %.1f GiB (%.1f GiB used)", info["path"], info["free_gib"], info["total_gib"], info["used_gib"], ) return info def resolve_lease( self, size: str, steps: float, reserve: float | int | None = 0 ) -> int: """Compute ZeroGPU lease duration respecting API ``reserve`` and Space default.""" return resolve_lease_seconds( size, steps, request_reserve=reserve, default_reserve=self.reserve_store.default_reserve_seconds, ) def get_reserve_status(self) -> ReserveStatus: return self.reserve_store.status() def set_default_reserve(self, reserve_seconds: int | float) -> ReserveStatus: return self.reserve_store.set_default_reserve(reserve_seconds) def _boot(self) -> None: self.report_disk() if self.settings.mock_mode: logger.info("[boot] ANIMA_MOCK_MODE=1 enabled — running lightweight studio mock engine") for spec in self.catalog.all_configured_specs.values(): enriched = spec.model_copy( update={"module_count": 448 if spec.key == "highres_boost" else 224, "formats": ["kohya:lora"]} ) self.catalog.mark_available(enriched) return import torch from diffusers import AnimaModularPipeline from transformers import Qwen2TokenizerFast, T5TokenizerFast from anima_studio.lora_loader import LoraManager, load_weights logger.info("[base] loading %s ...", self.settings.anima_repo) pipe = AnimaModularPipeline.from_pretrained(self.settings.anima_repo) pipe.update_components( tokenizer=Qwen2TokenizerFast.from_pretrained( self.settings.anima_repo, subfolder="tokenizer" ), t5_tokenizer=T5TokenizerFast.from_pretrained( self.settings.anima_repo, subfolder="t5_tokenizer", extra_special_tokens={}, ), ) pipe.load_components(torch_dtype=torch.bfloat16) pipe.transformer.rope.max_size = [ pipe.transformer.rope.max_size[0], ROPE_TOKENS, ROPE_TOKENS, ] self.pipe = pipe self.manager = LoraManager(pipe) configured = list(self.catalog.all_configured_specs.values()) prefetched = self.store.prefetch_all(configured) for spec in configured: local_path, error_reason = prefetched.get(spec.key, (None, "not fetched")) if local_path is None: self.catalog.mark_skipped(spec.key, error_reason or "download failed") continue try: weights, metadata = load_weights(local_path) count, unmatched, styles = self.manager.register(spec.key, weights, metadata) except Exception as exc: logger.warning("[lora:%s] failed to parse safetensors: %s", spec.key, exc) self.catalog.mark_skipped(spec.key, f"parse error: {exc}") continue if count == 0: reason = f"0 modules matched base model (formats={styles}, unmatched={len(unmatched)})" self.catalog.mark_skipped(spec.key, reason) logger.warning("[lora:%s] SKIPPED: %s", spec.key, reason) continue logger.info("[lora:%s] OK (%d modules, format=%s)", spec.key, count, styles) enriched = spec.model_copy( update={ "module_count": count, "unmatched_count": len(unmatched), "formats": styles, } ) self.catalog.mark_available(enriched) self.pipe.to("cuda") self.report_disk() def sync_worker_loras(self) -> None: """Synchronize runtime-added/removed Civitai LoRAs across ZeroGPU forked worker processes.""" added_specs, removed_keys = self.catalog.sync_from_disk() if self.settings.mock_mode: for spec in added_specs: self.catalog.mark_available( spec.model_copy(update={"module_count": 476, "formats": ["kohya:lora"]}) ) return if self.manager is None: return from anima_studio.lora_loader import load_weights for removed in removed_keys: self.manager.drop(removed) for key, spec in self.catalog.runtime_specs.items(): if self.manager.has_lora(key) and self.catalog.get_available(key) is not None: continue local_path, reason = self.store.ensure_local(spec) if local_path is None: self.catalog.mark_skipped(key, reason or "download failed") continue weights, metadata = load_weights(local_path) count, unmatched, styles = self.manager.register(key, weights, metadata) if count > 0: self.catalog.mark_available( spec.model_copy( update={ "module_count": count, "unmatched_count": len(unmatched), "formats": styles, } ) ) logger.info("[worker-sync] registered runtime LoRA %s (%d modules)", key, count) else: self.catalog.mark_skipped(key, f"0 modules matched ({styles})") def _scheduler_for(self, name: str) -> Any: if name not in SCHEDULERS: raise ValueError(f"Scheduler must be one of {', '.join(SCHEDULERS)}") if self.settings.mock_mode: return name if name not in self._schedulers: from anima_studio.samplers import build_scheduler self._schedulers[name] = build_scheduler(name, self.pipe.scheduler.config) return self._schedulers[name] def render( self, *, prompt: str, negative: str, size: str, steps: int | float, guidance: float, seed: int | float | None, scheduler: str | None = None, enable_highres_lora: bool = DEFAULT_HIGHRES_ENABLED, highres_lora_scale: float = DEFAULT_HIGHRES_SCALE, enable_quality_lora: bool = DEFAULT_QUALITY_ENABLED, quality_lora_scale: float = DEFAULT_QUALITY_SCALE, lora_name: str | None = "", lora_scale: float = 1.0, extra_loras: str = "", rating: str = DEFAULT_RATING, prefix: str = PROMPT_PREFIX, reserve: float | int | None = 0, ) -> tuple[Image.Image, GenerationTelemetry]: """Execute validation, multi-LoRA fusion, diffusion sampling, 16px crop, and telemetry.""" started = time.perf_counter() self.sync_worker_loras() effective_scheduler = (scheduler or self.settings.default_scheduler).strip() raw_seed = ( -1 if seed is None or (isinstance(seed, float) and math.isnan(seed)) else int(round(float(seed))) ) actual_seed = random.SystemRandom().randint(0, (1 << 31) - 1) if raw_seed < 0 else raw_seed selection = compose_lora_stack( enable_highres=bool(enable_highres_lora), highres_scale=highres_lora_scale, enable_quality=bool(enable_quality_lora), quality_scale=quality_lora_scale, lora_name=lora_name, lora_scale=lora_scale, extra_loras=extra_loras, resolver=self.catalog.resolve_available, ) sched_instance = self._scheduler_for(effective_scheduler) width, height = parse_canvas_size(size) gen_width, gen_height = padded_multiple_of_16(width, height) steps_int = max(1, min(100, int(round(float(steps))))) cfg_float = float(guidance) composed = compose_prompt(prefix, rating, prompt) negative_clean = str(negative or "") lease_sec = self.resolve_lease(f"{width}x{height}", steps_int, reserve) if self.settings.mock_mode: image = _render_mock_preview( width=width, height=height, seed=actual_seed, scheduler=effective_scheduler, composed_prompt=composed, ) else: import torch self.pipe.update_components(scheduler=sched_instance) torch.manual_seed(actual_seed) self.manager.apply(selection) logger.info( "[generate] seed=%d size=%dx%d scheduler=%s reserve=%ds(%s) loras=%s", actual_seed, width, height, effective_scheduler, lease_sec, self.settings.gpu_size, selection, ) self.pipe.guider.guidance_scale = cfg_float generator = torch.Generator("cpu").manual_seed(actual_seed) image = self.pipe( prompt=composed, negative_prompt=negative_clean, num_inference_steps=steps_int, width=gen_width, height=gen_height, generator=generator, output_type="pil", output="images", )[0] if (gen_width, gen_height) != (width, height): left = (gen_width - width) // 2 top = (gen_height - height) // 2 image = image.crop((left, top, left + width, top + height)) image.info["parameters"] = format_png_parameters( composed_prompt=composed, negative_prompt=negative_clean, steps=steps_int, scheduler=effective_scheduler, guidance=cfg_float, seed=actual_seed, width=width, height=height, ) elapsed = round(max(time.perf_counter() - started, 0.001), 2) telemetry = GenerationTelemetry( actual_seed=actual_seed, requested_size=f"{width}x{height}", internal_size=f"{gen_width}x{gen_height}", padded_and_cropped=(gen_width, gen_height) != (width, height), steps=steps_int, guidance=cfg_float, scheduler=effective_scheduler, rating=str(rating or "none"), gpu_size=self.settings.gpu_size, active_loras=selection, composed_prompt=composed, negative_prompt=negative_clean, elapsed_seconds=elapsed, lease_seconds=lease_sec, quota_seconds=round(lease_sec * self.settings.quota_factor, 1), timestamp_iso=dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"), ) return image, telemetry def install_online_lora( self, url_or_id: str, *, custom_trigger: str = "", custom_key: str = "", default_strength: float = 1.0, ) -> tuple[LoraSpec, bool, str]: """Inspect, validate, download, register, and persist an online Civitai Anima LoRA.""" strength_val = float(default_strength) if not MIN_LORA_STRENGTH <= strength_val <= MAX_LORA_STRENGTH: raise ValueError( f"Default strength must be between {MIN_LORA_STRENGTH:g} and {MAX_LORA_STRENGTH:g}: {strength_val:g}" ) meta = inspect_civitai(url_or_id) validate_anima_compatibility(meta) existing = self.catalog.find_by_version_id(meta.version_id) if ( existing is not None and self.catalog.get_available(existing.key) is not None and (not custom_key.strip() or custom_key.strip().lower() == existing.key) ): updated = existing if existing.online and (custom_trigger.strip() or strength_val != existing.strength): updated = existing.model_copy( update={ "trigger": custom_trigger.strip() or existing.trigger, "strength": strength_val, } ) self.catalog.save_runtime_spec(updated) return ( updated, True, f"LoRA '{updated.label}' is already installed (key='{updated.key}').", ) key = self.catalog.sanitize_custom_key(custom_key, meta.model_name or meta.label) effective_trigger = (custom_trigger or "").strip() or meta.default_trigger spec = LoraSpec( key=key, label=meta.label, series="Online (Civitai)", kind="character" if effective_trigger else "style", model_id=meta.model_id, version_id=meta.version_id, filename=meta.filename, sha256=meta.sha256, strength=round(strength_val, 2), default_enabled=False, trigger=effective_trigger, online=True, notes=f"Civitai model #{meta.model_id or '?'} / version #{meta.version_id} ({meta.size_mb:.1f} MB)", ) if self.settings.mock_mode: registered = spec.model_copy( update={"module_count": 476, "formats": ["kohya:lora"]} ) self.catalog.save_runtime_spec(registered) return ( registered, False, f"Installed '{registered.label}' in mock mode (key='{key}').", ) local_path, reason = self.store.ensure_local(spec) if local_path is None: raise ValueError(f"Download failed: {reason or 'Check CIVITAI_TOKEN and network connectivity'}") from anima_studio.lora_loader import load_weights weights, metadata = load_weights(local_path) count, unmatched, styles = self.manager.register(key, weights, metadata) if count == 0: raise ValueError(f"0 modules matched the Anima base model (detected formats: {styles})") registered = spec.model_copy( update={ "module_count": count, "unmatched_count": len(unmatched), "formats": styles, } ) self.catalog.save_runtime_spec(registered) msg = f"Installed '{registered.label}' (key='{key}', matched {count} modules)." logger.info("[lora:%s] online install OK (%d modules, %s)", key, count, styles) return registered, False, msg def remove_online_lora(self, key_or_id: str) -> tuple[LoraSpec | None, str]: """Unregister and remove a runtime-installed Civitai LoRA.""" target = (key_or_id or "").strip() if not target: return None, "Please specify the key or Civitai ID of the online LoRA to remove." if target in BUILTIN_DEFAULT_KEYS: return None, f"Built-in default LoRA '{target}' is protected and cannot be deleted." removed = self.catalog.remove_runtime_spec(target) if removed is None: return None, f"No removable online LoRA found for {target!r}." if not self.settings.mock_mode and self.manager is not None: self.manager.drop(removed.key) return removed, f"Removed online LoRA '{removed.label}' (key='{removed.key}')."