"""HTML rendering helpers for the Gradio command center.""" from __future__ import annotations import os import base64 from html import escape from pathlib import Path from .catalog import catalog_summary, parameter_budget from .schema import GenerationRun def badge(label: str, tone: str = "neutral") -> str: """ Generate an HTML badge element with a tone-specific CSS class. Parameters: label (str): The badge text content. tone (str): A CSS class modifier for the badge style; defaults to "neutral". Returns: str: An HTML span element with the specified tone class. """ return f'{escape(label)}' def icon(name: str) -> str: paths = { "forge": '', "wardrobe": '', "lore": '', "models": '', "security": '', "runs": '', "zoom": '', "frame": '', "lock": '', "dot": '', } return f'' def _metric(label: str, value: str, tone: str = "neutral") -> str: """ Render an HTML metric block with a label and value. Parameters: tone (str): The styling variant name (default: "neutral"). Returns: str: HTML markup for the metric. """ return f'
{escape(label)}{escape(value)}
' def _display_state(value: str) -> str: """Return user-facing state labels without changing machine state values.""" normalized = str(value or "").replace("_", " ").strip().lower() labels = { "blocked": "Export Gate Active", "generated": "Generated", "missing secret": "Optional - Secret Required", "missing_secret": "Optional - Secret Required", "export_ready": "Export Ready", "configured": "CONFIGURED", "dry-run": "Dry Run", "dry run": "Dry Run", "success": "SUCCESS", } return labels.get(normalized, normalized.title() if normalized else "Pending") def _gate_label(export_gate: str) -> str: normalized = str(export_gate or "pending").upper() if normalized == "BLOCKED": return "Export Blocked - Override Available" if normalized == "CLEAR": return "EXPORT CLEAR" if normalized == "PENDING": return "Export waits for review" return f"EXPORT {normalized}" def _env_configured(*names: str) -> bool: """ Determine whether any of the provided environment variables are set and truthy. Returns: True if any of the environment variables exists and is truthy, False otherwise. """ return any(bool(os.environ.get(name)) for name in names) def _provider_configured(base_url_name: str, *key_names: str) -> bool: """ Determines if a provider is configured with both a base URL and authentication keys. Returns: True if the base URL environment variable is set and at least one of the provided key environment variables is set, False otherwise. """ return bool(os.environ.get(base_url_name)) and _env_configured(*key_names) _SCAN_REDACTION_TERMS = ( "payload", "payload_excerpt", "hidden content", "recovered", "raw byte", "base64", "hex dump", ) def _redact_scan_text(value: object) -> str: """ Sanitizes scan text by redacting sensitive content and truncating excessively long values. Parameters: value (object): A scan detail to sanitize. Returns: str: A redaction notice if the text contains sensitive terms; the original text truncated to 177 characters plus "..." if it exceeds 180 characters; otherwise the original text converted to a string. """ text = str(value) lowered = text.lower() if any(term in lowered for term in _SCAN_REDACTION_TERMS): return "Redacted scan detail; review the gated ST3GG evidence packet." if len(text) > 180: return text[:177] + "..." return text def _space_runtime_status() -> dict[str, str]: """ Determines the current runtime environment and active provider configuration. Returns: dict[str, str]: A dict with `space_id`, `hardware`, `bucket`, and `secrets` keys describing the deployment context and configured provider secrets. """ space_id = os.environ.get("SPACE_ID") or os.environ.get("HF_SPACE_ID") or "local-preview" hardware = os.environ.get("SPACE_HARDWARE") or os.environ.get("NEXUS_SPACE_HARDWARE") or "ZeroGPU" bucket = "/data mounted" if os.path.isdir("/data") else "bucket optional" configured = [] if _env_configured("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): configured.append("HF") if _provider_configured("MINICPM_BASE_URL", "MINICPM_API_KEY", "OPENBMB_API_KEY"): configured.append("MiniCPM") if _provider_configured("NEMOTRON_BASE_URL", "NEMOTRON_API_KEY", "NVIDIA_API_KEY"): configured.append("Nemotron") if _env_configured("FAL_KEY", "NETLIFY_AUTH_TOKEN", "OPENAI_API_KEY", "MODAL_TOKEN_ID"): configured.append("optional") secrets = "configured: " + ", ".join(configured) if configured else "no provider secrets" return { "space_id": space_id, "hardware": hardware, "bucket": bucket, "secrets": secrets, } def _image_data_uri(path: str | None) -> str | None: """ Create a data URI string from a file's contents, selecting MIME type by extension. Returns: data_uri (str | None): A data URI string with base64-encoded file contents if the path exists and is readable; `None` otherwise. MIME type is determined by file extension (.png, .jpg/.jpeg, .webp; otherwise application/octet-stream). """ if not path: return None target = Path(path) if not target.exists() or not target.is_file(): return None suffix = target.suffix.lower() mime = "image/png" if suffix == ".png" else "image/jpeg" if suffix in {".jpg", ".jpeg"} else "image/webp" if suffix == ".webp" else "application/octet-stream" data = base64.b64encode(target.read_bytes()).decode("ascii") return f"data:{mime};base64,{data}" def render_command_header() -> str: """ Render the command header section of the dashboard. Returns: An HTML string containing the command header, description, and status badges. """ return f"""
COMMAND INPUT Raven Chronicle Active Weave Prompt, reference scan, model route, and checkpoint controls stay in one sticky operator strip.
{badge("SFW DEFAULT", "pass")} {badge("ST3GG ALWAYS ON", "cyan")} {badge("FLUX.2 9B PINNED", "accent")} {badge("4B SIDECAR", "cyan")} {badge("HUMAN CHECKPOINT", "warn")}
""" def render_trust_strip(scan: dict | None = None, operator_state: dict | None = None) -> str: """ Renders a trust model strip showing scan findings, export gate status, and safety checkpoint state. Returns: An HTML string for the trust strip section containing badge cards with redacted scan details. """ scan = scan or {"status": "idle", "export_gate": "pending", "findings": [], "purification_actions": []} operator_state = operator_state or {} status = str(scan.get("status", "idle")).upper() status_label = "READY" if status == "IDLE" else status export_gate = str(scan.get("export_gate", "pending")).upper() checkpoint = str(operator_state.get("checkpoint", "pending")).replace("_", " ").title() raw_findings = scan.get("findings") if raw_findings is None: default_finding = "No upload selected. Always-on scanner ready." if status == "IDLE" else "No findings." raw_findings = [default_finding] elif not raw_findings: raw_findings = ["No findings." if status != "IDLE" else "No upload selected. Always-on scanner ready."] findings = [_redact_scan_text(item) for item in raw_findings] actions = [_redact_scan_text(item) for item in (scan.get("purification_actions") or [ "strip metadata before export", "truncate PNG after IEND when needed", "run LSB statistical review", ])] tone = _scan_status_tone(str(scan.get("status", "idle"))) return f"""
TRUST MODEL Generation is not export. Every artifact must pass ST3GG scan, purification, and human checkpoint before release.
{badge(f"ST3GG {status_label}", tone)}{escape(str(findings[0]))}
{badge(_gate_label(export_gate), "pass" if export_gate == "CLEAR" else "warn" if export_gate == "BLOCKED" else "muted")}{escape(str(actions[0]))}
{badge(f"CHECKPOINT {checkpoint.upper()}", "pass" if checkpoint == "Approved" else "muted")}Adult Mode never bypasses safety, consent, provenance, or dataset gates.
{badge("FIXTURE EVIDENCE", "cyan")}Clean PNG -> pass. PNG trailing bytes -> blocked.
""" def render_topbar( adult_mode: bool = False, relay_status: dict | None = None, scan: dict | None = None, operator_state: dict | None = None, ) -> str: """ Render the dashboard topbar with budget metrics, relay status, adult mode controls, and trust model information. Parameters: relay_status: Dictionary with relay rotation safety information. scan: Dictionary with scan status and findings. operator_state: Dictionary with operator checkpoint and provider state. Returns: HTML markup for the topbar and trust strip sections. """ summary = catalog_summary(adult_mode) active = float(summary["active_b"]) pct = max(0, min(100, int((active / 32.0) * 100))) adult_label = "ON - research partition" if adult_mode else "OFF" relay_status = relay_status or {} rotation_safe = bool(relay_status.get("rotation_safe", True)) relay_label = "Rotation Safe" if rotation_safe else "Rotation Limited" relay_tone = "pass" if rotation_safe else "warn" space = _space_runtime_status() return f"""
NEXUSVisual Weaver
ProjectRaven Chronicle
Active PresetDark Couture v2.4
32B Parameter Budget{active:.2f}B / 32B ({pct}%)
HF ConnectedHugging Face
HF / Modal / GMR{badge(relay_label, relay_tone)}Helper rotation only
{escape(space["space_id"])}{escape(space["hardware"])}{escape(space["bucket"])} / {escape(space["secrets"])}
Adult Mode {icon("lock")} {escape(adult_label)}
18+Locked. Enable in Security with explicit justification.
{render_trust_strip(scan, operator_state)} """ def render_left_rail(active_section: str = "Forge") -> str: items = [("Forge", "forge"), ("Wardrobe", "wardrobe"), ("Lore", "lore"), ("Models", "models"), ("Security", "security"), ("Runs", "runs")] rows = "".join( f'
{icon(icon_name)}{escape(label)}
' for label, icon_name in items ) return f""" """ def render_command_rail(active_section: str = "Forge") -> str: """ Render a contextual command rail for the selected section. Returns: str: An HTML string with the command rail displaying the section's title, description, and selection badge. """ section = escape(active_section) hints = { "Forge": ("Active Weave", "Prompt, judge, locate, generate, checkpoint."), "Wardrobe": ("Outfit Slots", "Materials, footwear, locks, reference regions."), "Lore": ("Video Continuity", "Identity, garment meaning, scene motion."), "Models": ("Relay Stack", "Pinned core plus quota-aware helper rotation."), "Security": ("ST3GG Gate", "Scan, purify, provenance, export decision."), "Runs": ("Run Ledger", "Checkpointed dry-runs and handoff packets."), } title, body = hints.get(active_section, hints["Forge"]) return f"""
{escape(title)} {escape(body)} {badge(f"Selected: {section}", "muted")}
""" def render_workflow(run: GenerationRun | None = None, operator_state: dict | None = None) -> str: """ Render an SVG workflow diagram and console showing the generation pipeline. The diagram visualizes a multi-stage workflow (seed prompt, refine, judge, locate, generate, video, checkpoint) with nodes, edges, and status indicators. Node content and labels reflect the provided run and operator context. Parameters: run: GenerationRun object providing run-specific values for trust score, checkpoint ID, model labels, video preset, and required actions. Defaults to mock values if None. operator_state: Dict containing operator context including checkpoint status, provider state, recommendation, and message. Defaults to an empty dict. Returns: str: HTML section containing SVG workflow graph, legend badges, and console cards with checkpoint, action, model lane, and signal information. """ operator_state = operator_state or {} score = run.checkpoint.trust_score if run else 0.82 checkpoint_id = run.checkpoint.checkpoint_id if run else "nw-dry-run" checkpoint_status = str(operator_state.get("checkpoint", "pending_review" if run else "pending")) provider_state = str(operator_state.get("provider_state", "dry-run" if run else "idle")) recommendation = operator_state.get("message") or (run.checkpoint.recommendation.replace("_", " ").title() if run else "Awaiting Run") required_actions = run.checkpoint.required_actions if run else ["Review candidate thumbnails before promotion"] action_label = required_actions[0] if required_actions else "No action pending" if checkpoint_status == "approved": action_label = "Checkpoint approved; export packet may be prepared after ST3GG gate." elif provider_state == "stopped": action_label = "Provider handoff stopped; dry-run evidence remains available." model_label = _short_repo(run.model_stack[0].repo_id) if run and run.model_stack else "FLUX.2" locate_label = run.inspection.locate_model.split("/")[-1] if run else "LocateAnything-3B" nodes = { "seed": (35, 52, 190, 210, "Seed Prompt", ["Rogue archivist moving", "through rain-slick neon", "city, couture layers."], "Text-to-Image (FLUX.2)", "complete", "red"), "refine": (275, 52, 185, 160, "Refine", ["Prompt Refiner", "Style Harmonizer", "Negative Purge"], "Qwen2.5-7B", "complete", "violet"), "judge": (540, 52, 185, 160, "Judge", ["Aesthetic Scorer", "ST3GG Policy Filter", f"Score {score:.2f}"], "MiniCPM / Nemotron", "complete", "blue"), "locate": (785, 52, 185, 160, "Locate", ["Reference Locator", "Pose & Composition", "IP-Adapter"], "Refs 3/5", "complete", "cyan"), "generate": (275, 280, 235, 210, "Generate", ["Image / Video Generation", "FLUX.2 9B + adapter stack", "4B sidecar fallback"], "Steps 4 CFG 1.0", "ready", "green"), "video": (590, 280, 235, 210, "Video Path", ["Image to Video", "Frame interpolation", run.video.preset if run else "Wan2.2 / LTX swap"], "Duration 5.6s 24fps", "ready", "blue"), "checkpoint": (880, 285, 185, 185, "Human Checkpoint", ["Human review required", "Verify intent, vibe,", "and output before final."], "Review Now", "paused", "amber"), } edges = [ ("seed", "refine"), ("refine", "judge"), ("judge", "locate"), ("locate", "video"), ("refine", "generate"), ("generate", "video"), ("video", "checkpoint"), ("judge", "checkpoint"), ] lines = [] for source, target in edges: x1, y1, w1, h1, *_ = nodes[source] x2, y2, w2, h2, *_ = nodes[target] y_offset = 76 if source in {"seed", "refine", "judge", "locate"} else 96 lines.append( f'' ) cards = [] for node_id, (x, y, width, height, title, body, footer, status, tone) in nodes.items(): body_lines = "".join(f'{escape(line)}' for idx, line in enumerate(body)) thumb_strip = "" if node_id in {"generate", "video"}: thumbs = [] for idx in range(4): tx = x + 16 + idx * 47 thumbs.append( f'' ) thumb_strip = "".join(thumbs) cards.append( f""" {escape(title)} {body_lines} {thumb_strip} {escape(footer)} """ ) generation = operator_state.get("generation") or {} generated = isinstance(generation, dict) and generation.get("status") == "success" output_summary = "Real FLUX.2 Klein 9B artifact generated" if generated else "Awaiting generated artifact" checkpoint_summary = _display_state(checkpoint_status) export_summary = _display_state(str(operator_state.get("export", provider_state))) next_summary = "Add override reason or complete review" if provider_state == "blocked" else action_label return f"""
Active Weave Live / Weave ID: 4f7c9e2b
Layout Auto{icon("zoom")}{icon("frame")}
Current Run Summary Output{escape(output_summary)} SecurityST3GG review active Checkpoint{escape(checkpoint_summary)} Export{escape(export_summary)} Next{escape(next_summary)}
{"".join(lines)} {"".join(cards)}
{badge("Text Flow", "accent")} {badge("Refine Loop", "violet")} {badge("Policy Gate", "blue")} {badge("Media Flow", "cyan")} {badge("Human Gate", "warn")} {badge(_display_state(provider_state), "pass" if provider_state == "exported" else "warn" if provider_state in {"blocked", "stopped"} else "muted")}
Selected Node Human Checkpoint {escape(str(recommendation))} / {escape(checkpoint_id)}
Next Operator Action {escape(action_label)} Checkpoint blocks video promotion until reviewed.
Pinned Model Lanes {escape(model_label)} + {escape(locate_label)} + ST3GG Core lanes stay fixed; helper lanes may rotate.
Hackathon Signal Workflow, governance, visual creation Judge view keeps product purpose visible without a landing page.
""" def render_artifact_lane(run: GenerationRun | None = None, scan: dict | None = None, operator_state: dict | None = None) -> str: """ Render an artifact preview panel with generated output and status cards. Displays the current artifact output (if available from a provider call), preview metadata about checkpoint and export status, and a grid of artifact cards showing progress through generation stages. Supports both dry-run and live provider output scenarios. Parameters: run (GenerationRun | None): Generation run with output image path, refined prompt, and continuity data. If None, shows dry-run placeholder content. scan (dict | None): Security scan state with status and export gate information. Defaults to {"status": "idle", "export_gate": "pending"}. operator_state (dict | None): Operator context including checkpoint status, provider state, and generated output. Defaults to {}. Returns: str: HTML markup for the artifact preview section. """ scan = scan or {"status": "idle", "export_gate": "pending"} operator_state = operator_state or {} active_prompt = run.refined_prompt.refined[:150] if run else "Describe the look and click Generate Image." checkpoint = operator_state.get("checkpoint", getattr(run.checkpoint, "recommendation", "pending") if run else "pending") provider_state = str(operator_state.get("provider_state", "dry-run" if run else "idle")) generation = operator_state.get("generation") or {} generated_uri = _image_data_uri(generation.get("output_path")) if isinstance(generation, dict) else None generated_status = str(generation.get("status", "")) if isinstance(generation, dict) else "" generated_message = str(generation.get("message", "")) if isinstance(generation, dict) else "" output_ready = bool(generated_uri) preview_mode = { "idle": "Idle", "dry-run": "Dry Run", "checkpointed": "Checkpointed", "export_ready": "Export Ready", "exported": "Exported", "blocked": "Export Gate Active", "stopped": "Stopped", "generated": "Generated", }.get(provider_state, provider_state.replace("_", " ").title()) demo_seed = (run.checkpoint.checkpoint_id[-4:] if run else "0000").upper() export_gate = str(scan.get("export_gate", "pending")).upper() checkpoint_label = str(checkpoint).replace("_", " ").title() next_action = "Generate an image to unlock checkpoint review." if output_ready and str(checkpoint) != "approved": next_action = "Approve checkpoint to unlock audit export." elif output_ready and str(checkpoint) == "approved" and export_gate != "CLEAR": next_action = "Add override reason or complete ST3GG review, then prepare audit export." elif output_ready and str(checkpoint) == "approved": next_action = "Prepare audit export." return f"""
{'Generated image ready' if output_ready else 'Output'}Real output and export evidence appear here
{badge(_gate_label(export_gate), "warn" if export_gate == "BLOCKED" else "pass" if export_gate == "CLEAR" else "muted")}
{'Generated FLUX artifact' if generated_uri else ''}
PRIMARY OUTPUT STAGE / {escape(generated_status.upper() or "JUDGE-SAFE DEMO OUTPUT")} / SEED {escape(demo_seed)} {'Real FLUX.2 Klein artifact' if generated_uri else 'No image generated yet'} {escape(generated_message or active_prompt)}
Output{'Ready' if output_ready else 'Waiting'}
Checkpoint{escape(checkpoint_label)}
Export{escape(_gate_label(export_gate))}
Current state{escape(preview_mode)}
SecurityST3GG review active
Next action{escape(next_action)}
""" def render_operations_panel( active_section: str = "Forge", run: GenerationRun | None = None, scan: dict | None = None, relay_status: dict | None = None, *, adult_mode: bool = False, operator_state: dict | None = None, ) -> str: """ Render an operations panel with section-specific operation cards. Generates an HTML section containing three operation cards tailored to the selected section, with content drawn from run state, scan results, relay decisions, and operator context. Invalid section names default to "Forge". Parameters: active_section (str): The section name determining which operation cards to display. Valid sections are "Forge", "Wardrobe", "Lore", "Models", "Security", and "Runs". adult_mode (bool): If True, scope label is "Private research scope"; otherwise "Public demo scope". operator_state (dict | None): Operator context dict with "provider_state" and "message" keys. Returns: str: HTML string representing the operations panel section. """ scan = scan or {"status": "idle", "export_gate": "pending", "findings": []} relay_status = relay_status or {} operator_state = operator_state or {} section = active_section if active_section in {"Forge", "Wardrobe", "Lore", "Models", "Security", "Runs"} else "Forge" checkpoint = getattr(run, "checkpoint", None) if run else None outfit = getattr(run, "outfit", None) if run else None lore = getattr(run, "lore", None) if run else None run_id = getattr(checkpoint, "checkpoint_id", "not-started") outfit_count = len(getattr(outfit, "slots", []) or []) lore_count = len(getattr(lore, "beats", []) or []) scan_status = str(scan.get("status", "idle")).upper() export_gate = str(scan.get("export_gate", "pending")).upper() provider_state = str(operator_state.get("provider_state", "idle")).replace("_", " ").upper() operator_message = str(operator_state.get("message", "No operator action yet.")) decisions = relay_status.get("decisions", []) first_decision = decisions[0] if decisions else {} first_primary = (first_decision.get("primary") or {}) if first_decision else {} adult_scope = "Private research scope" if adult_mode else "Public demo scope" panels = { "Forge": [ ("Prompt contract", "Taste-refined prompt, material locks, negative purge, and checkpoint requirements."), ("Active run", f"{run_id} / checkpoint remains human-reviewed before video promotion."), ("Provider posture", f"{provider_state}: {operator_message}"), ], "Wardrobe": [ ("Slot coverage", f"{outfit_count or 9} garment/accessory regions tracked with locks and edit priority."), ("Footwear focus", "Platform boots, stilettos, high-heel boots, hardware, and silhouette constraints stay first-class."), ("Locate map", "Reference regions feed preflight and post-generation outfit verification."), ], "Lore": [ ("Beat budget", f"{lore_count or 6} compact beats: identity, garment meaning, world context, emotion, motion."), ("Video checkpoint", "Video presets remain handoff plans until human approval."), ("Continuity locks", "Lore-to-video keeps garment meaning and motion cue visible without tab sprawl."), ], "Models": [ ("Primary helper", _short_repo(str(first_primary.get("repo_id", "pending")))), ("Rotation mode", "Pinned core stays fixed; helper lanes rotate by license, budget, quota, and health."), ("Scope", adult_scope), ], "Security": [ ("ST3GG state", f"{scan_status} / export {export_gate}"), ( "Findings", "; ".join(_redact_scan_text(item) for item in (scan.get("findings") or [])[:2]) or ("No findings." if scan_status != "IDLE" else "No upload selected."), ), ("Public export", "Consent, provenance, metadata, age, dataset, and payload gates stay active."), ], "Runs": [ ("Current checkpoint", run_id), ("Ledger mode", f"Operator state: {provider_state}. Run JSON, catalog summary, and ST3GG evidence remain in the evidence accordion."), ("Rollback path", "Feature branches and draft PRs carry implementation checkpoints."), ], } rows = "".join( f"""
{escape(title)} {escape(body)}
""" for title, body in panels[section] ) return f"""
{escape(section)} OperationsSection-aware control surface for the selected command rail lane
{badge(f"{escape(section).upper()} ACTIVE", "cyan")}
{rows}
""" def _short_repo(repo_id: str) -> str: """ Extract the repository name from a repository identifier. Returns the last segment after splitting on forward slashes. Returns: str: The repository name """ return repo_id.split("/")[-1] def _render_relay_panel(relay_status: dict | None = None) -> str: """ Render an HTML panel summarizing model relay decisions and pinned lanes. Returns: str: An HTML string containing the GMR panel with pinned core lanes, up to two decisions, and dedup metrics. """ relay_status = relay_status or {} pinned = relay_status.get("pinned", {}) decisions = relay_status.get("decisions", []) pinned_labels = [] for lane in ["image_generation", "grounding", "security"]: record = pinned.get(lane) if record: pinned_labels.append(_short_repo(record["repo_id"])) pinned_rows = [ f"""
  • pinned core {escape(" / ".join(pinned_labels[:3]) or "pending")} image, grounding, and security never rotate
  • """ ] decision_rows = [] for decision in decisions[:2]: primary = decision.get("primary") or {} fallbacks = decision.get("fallbacks") or [] fallback_label = ", ".join(_short_repo(item["repo_id"]) for item in fallbacks[:2]) or "none" decision_rows.append( f"""
  • {escape(decision["lane"].replace("_", " "))} {escape(_short_repo(primary.get("repo_id", "blocked")))} {escape(decision["strategy"])} / fallback: {escape(fallback_label)}
  • """ ) rows = "".join(pinned_rows + decision_rows) if not rows: rows = "
  • GMRsnapshot pendingrelay idle
  • " dedup_hits = relay_status.get("dedup_hits", 0) return f"""

    GMR ModelRelay

      {rows}
    {badge("FLUX.2 9B pinned", "pass")} {badge("4B sidecar", "cyan")} {badge("LocateAnything pinned", "pass")} {badge(f"dedup hits {dedup_hits}", "muted")}
    """ def render_provider_cards(relay_status: dict | None = None, adult_mode: bool = False) -> str: """ Generates an HTML panel displaying provider cards with operational status and licensing information. Constructs cards for each relay-decided provider showing the lane, repository, provider name, license gate status, and health meter. Includes optional provider cards for off-by-default gateways. The panel header shows the current operational mode (private research or public demo). Parameters: relay_status (dict | None): Relay status containing provider decisions with quota impact and license gate data. If None, defaults to empty dict. adult_mode (bool): If True, displays "PRIVATE RESEARCH" mode label; otherwise displays "PUBLIC DEMO SAFE". Returns: str: HTML section markup for the provider cards panel. """ relay_status = relay_status or {} decisions = relay_status.get("decisions", []) optional_statuses = { "openbmb": "configured" if _provider_configured("MINICPM_BASE_URL", "MINICPM_API_KEY", "OPENBMB_API_KEY") else "missing secret", "nvidia": "configured" if _provider_configured("NEMOTRON_BASE_URL", "NEMOTRON_API_KEY", "NVIDIA_API_KEY") else "missing secret", "fal": "configured" if _env_configured("FAL_KEY") else "deferred", "netlify": "configured" if _env_configured("NETLIFY_AUTH_TOKEN", "NETLIFY_SITE_ID", "OPENAI_BASE_URL") else "deferred", "cloudflare": "configured" if _env_configured("CLOUDFLARE_API_TOKEN", "CF_ACCOUNT_ID") else "deferred", } cards = [] for decision in decisions[:5]: primary = decision.get("primary") or {} quota = decision.get("quota_impact") or {} provider = primary.get("provider", "blocked") repo = _short_repo(primary.get("repo_id", "blocked")) lane = decision.get("lane", "helper").replace("_", " ") status = quota.get("status", "blocked") provider_state = "dry-run" if status == "ready" else "blocked" if status == "blocked" else "limited" if provider in optional_statuses: provider_state = optional_statuses[provider] tone = "pass" if provider_state == "configured" else "warn" if provider_state in {"limited", "failed"} else "muted" gate = primary.get("license_gate", "unknown") cards.append( f"""
    {escape(lane)} {escape(repo)} {escape(str(provider))} / {escape(str(gate))}
    {badge(_display_state(provider_state), tone)}{badge("CHECKPOINTED", "muted")}
    """ ) if not cards: cards.append('
    providerssnapshot pendingrelay idle
    {}
    '.format(badge("DRY-RUN", "muted"))) for provider, state in optional_statuses.items(): cards.append( f"""
    optional gateway {escape(provider.title())} optional lane / secrets required
    {badge(_display_state(state), "pass" if state == "configured" else "muted")}{badge("SPONSOR LANE" if provider in {"openbmb", "nvidia", "hf_nvidia"} else "DEFERRED", "muted")}
    """ ) mode_label = "private research" if adult_mode else "public demo safe" return f"""
    Optional Provider LanesVisible capability cards; success is claimed only after configured calls
    {badge(mode_label.upper(), "warn" if adult_mode else "pass")}
    {"".join(cards)}
    """ def _scan_status_tone(scan_status: str) -> str: """ Map a scan status to a display tone. Returns: str: "pass" if status is "pass", "warn" if status is "review" or "error", "muted" otherwise. """ if scan_status == "pass": return "pass" if scan_status in {"review", "error"}: return "warn" return "muted" def render_inspector( run: GenerationRun | None = None, scan: dict | None = None, relay_status: dict | None = None, operator_state: dict | None = None, ) -> str: """ Render an inspector sidebar with taste profile, material checklist, model stack, sponsor evidence, and ST3GG scan details. Returns: str: HTML markup for the inspector panel. """ if run: checks = [ ("Patent Leather", True), ("Faux Fur", any(slot.material == "faux_fur" for slot in run.outfit.slots)), ("Lace / Mesh", any("lace" in slot.material for slot in run.outfit.slots)), ("Crimson Hardware", any(slot.material == "crimson_hardware" for slot in run.outfit.slots)), ("Platform Boots", any(slot.name == "footwear" for slot in run.outfit.slots)), ("Layered Garments", True), ] stack_label = " / ".join(_short_repo(model.repo_id) for model in run.model_stack[:3]) model_rows = f"
  • active stack{escape(stack_label)}
  • " score = int(run.checkpoint.trust_score * 100) scan_status = (scan or {}).get("status", "pass") else: checks = [(label, True) for label in ["Patent Leather", "Faux Fur", "Lace / Mesh", "Crimson Hardware", "Platform Boots", "Layered Garments"]] model_rows = "
  • active stackFLUX.2 9B / MiniCPM / LocateAnything
  • " score = 86 scan_status = (scan or {}).get("status", "pass") checks_html = "".join(f'
  • {"✓" if ok else "!"}{escape(label)}
  • ' for label, ok in checks) relay = _render_relay_panel(relay_status) scan = scan or {"status": scan_status, "findings": [], "purification_actions": [], "export_gate": "pending"} operator_state = operator_state or {} minicpm = operator_state.get("minicpm_judge") or {} nemotron = operator_state.get("nemotron_evidence") or {} sponsor_rows = "".join( f"
  • {escape(label)}{escape(_display_state(str(result.get('status', 'pending'))))}{escape(str(result.get('repo_id', repo)))}
  • " for label, repo, result in [ ("OpenBMB MiniCPM", "openbmb/MiniCPM-V-4.6", minicpm), ("NVIDIA Nemotron", "nvidia/NVIDIA-Nemotron-Parse-v1.2", nemotron), ] ) findings = [_redact_scan_text(item) for item in (scan.get("findings") or [])] actions = [_redact_scan_text(item) for item in (scan.get("purification_actions") or ["metadata strip ready", "IEND truncation ready", "LSB review ready"])] finding_rows = "".join(f"
  • {escape(item)}
  • " for item in findings[:4]) or "
  • No upload selected. Scanner ready.
  • " action_rows = "".join(f"
  • {escape(item)}
  • " for item in actions[:4]) export_gate = str(scan.get("export_gate", "pending")).upper() return f""" """ def render_drawer(run: GenerationRun | None = None) -> str: """ Renders the bottom drawer panel with outfit wardrobe and story beats. Returns: str: HTML markup for the bottom drawer section. """ if run: slots = run.outfit.slots beats = run.lore.beats else: slots = [] beats = [] slot_cards = "".join( f"""
    {escape(slot.name.replace("_", " ").title())} {escape(slot.material.replace("_", " "))} {'locked' if slot.locked else 'editable'} / p{slot.edit_priority}
    """ for idx, slot in enumerate(slots[:8]) ) if not slot_cards: slot_cards = "".join( f'
    {label}{mat}editable / p{5 - idx // 2}
    ' for idx, (label, mat) in enumerate([ ("Patent Leather", "jet black"), ("Faux Fur", "ash gray"), ("Lace Mesh", "noir"), ("Crimson Hardware", "polished"), ("Platform Boots", "matte black"), ("Long Coat", "wool blend"), ]) ) beat_cards = "".join( f'
    {escape(beat["id"])} {escape(beat["title"])}{escape(beat["cue"][:80])}checkpointed
    ' for idx, beat in enumerate(beats[:6]) ) if not beat_cards: beat_cards = "".join(f'
    0{i} BeatScene continuity cuecheckpointed
    ' for i in range(1, 7)) return f"""
    Outfit WardrobeCouture slots, locks, LocateAnything regions, and edit priority
    All Categories
    AllPatentLaceHardwareBoots / heelsOuterwearProps
    {slot_cards}
    Lore-to-Video TimelineIdentity, garment meaning, motion cue, and video checkpoint path
    6 Beats24 FPS
    {beat_cards}
    """ def render_status_bar(operator_state: dict | None = None) -> str: space = _space_runtime_status() operator_state = operator_state or {} raw_provider_state = str(operator_state.get("provider_state", "idle")) provider_state = _display_state(raw_provider_state) stop_class = ( "nw-stop-idle" if provider_state == "Idle" else "nw-stop-pass" if raw_provider_state in {"generated", "exported", "export_ready", "checkpointed"} else "nw-stop-active" ) return f"""
    {_metric("Runs", "112")} {_metric("Queue", "2")} {_metric("GPU", "46%", "bar")} {_metric("VRAM", "18.2 / 40 GB", "bar")} {_metric("Temp", "62 C")} {_metric("HF Space", space["hardware"])}
    Auto-saveOn
    {escape(provider_state)}
    """ def render_catalog_table(adult_mode: bool = False) -> str: from .catalog import filter_catalog models, adapters = filter_catalog(adult_mode) model_rows = "".join( f"{escape(model.repo_id)}{escape(model.role)}{model.params_b:.2f}B{escape(model.license)}{'18+' if model.adult_only else 'General'}" for model in models ) adapter_rows = "".join( f"{escape(adapter.repo_id)}{escape(adapter.adapter_for)}{escape(adapter.task)}{'18+' if adapter.adult_only else 'General'}" for adapter in adapters ) return f"""

    HF Model Catalog

    {model_rows}
    RepoRoleParamsLicenseScope

    LoRA / Adapter Shelf

    {adapter_rows}
    RepoAdapter ForTaskScope
    """ def render_dashboard( run: GenerationRun | None = None, adult_mode: bool = False, scan: dict | None = None, relay_status: dict | None = None, active_section: str = "Forge", operator_state: dict | None = None, ) -> str: """ Render the complete Gradio command center dashboard. Returns: str: The full HTML dashboard markup. """ regions = render_dashboard_regions(run, adult_mode, scan, relay_status, active_section, operator_state) return f"""
    {regions["topbar"]}
    {regions["rail"]}
    {regions["workflow"]} {regions["operations"]} {regions["artifacts"]}
    {regions["inspector"]} {regions["providers"]}
    {regions["drawer"]}
    {regions["status"]}
    """ def render_dashboard_regions( run: GenerationRun | None = None, adult_mode: bool = False, scan: dict | None = None, relay_status: dict | None = None, active_section: str = "Forge", operator_state: dict | None = None, ) -> dict[str, str]: """ Assemble all dashboard UI regions into a dictionary of HTML markup. Parameters: run: A generation run or None. adult_mode: Whether to render adult-mode content. scan: Scanner status and findings or None. relay_status: Model relay configuration or None. active_section: The currently active navigation section. operator_state: Operator control state or None. Returns: dict[str, str]: HTML markup strings for each dashboard region. """ return { "topbar": render_topbar(adult_mode, relay_status, scan, operator_state), "rail": render_left_rail(active_section), "command_rail": render_command_rail(active_section), "workflow": render_workflow(run, operator_state), "operations": render_operations_panel(active_section, run, scan, relay_status, adult_mode=adult_mode, operator_state=operator_state), "inspector": render_inspector(run, scan, relay_status, operator_state), "drawer": render_drawer(run), "status": render_status_bar(operator_state), "artifacts": render_artifact_lane(run, scan, operator_state), "providers": render_provider_cards(relay_status, adult_mode), }