specimba commited on
Commit
efebf3a
Β·
verified Β·
1 Parent(s): 9b75320

fix: Gradio 6.18 theme Font compat + real Modal wiring + LoRA Lab tab

Browse files
Files changed (1) hide show
  1. app.py +1145 -66
app.py CHANGED
@@ -1,76 +1,1155 @@
1
- """NEXUS Visual Weaver v2.0 β€” Diagnostic Build"""
2
- import gradio as gr
 
 
3
  import os
4
  import sys
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- # Add src to path
7
- ROOT = os.path.dirname(os.path.abspath(__file__))
8
- SRC = os.path.join(ROOT, "src")
9
- if SRC not in sys.path:
10
- sys.path.insert(0, SRC)
11
 
12
- DIAGNOSTIC = []
13
 
14
- def check_imports():
15
- results = []
16
-
17
- # Basic imports
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  try:
19
- import spaces
20
- results.append(("spaces", "OK", ""))
21
  except Exception as e:
22
- results.append(("spaces", "FAIL", str(e)[:100]))
23
-
24
- # Package imports
25
- for mod_name, mod_path in [
26
- ("catalog", "nexus_visual_weaver.catalog"),
27
- ("exporter", "nexus_visual_weaver.exporter"),
28
- ("hf_runtime", "nexus_visual_weaver.hf_runtime"),
29
- ("model_relay", "nexus_visual_weaver.model_relay"),
30
- ("planner", "nexus_visual_weaver.planner"),
31
- ("provider_runtime", "nexus_visual_weaver.provider_runtime"),
32
- ("render", "nexus_visual_weaver.render"),
33
- ("security", "nexus_visual_weaver.security"),
34
- ("styles", "nexus_visual_weaver.styles"),
35
- ]:
36
- try:
37
- __import__(mod_path)
38
- results.append((mod_name, "OK", ""))
39
- except Exception as e:
40
- results.append((mod_name, "FAIL", str(e)[:100]))
41
-
42
- return results
43
-
44
- def run_diagnostics():
45
- results = check_imports()
46
- text = "## Import Diagnostics\n"
47
- all_ok = True
48
- for name, status, error in results:
49
- icon = "βœ…" if status == "OK" else "❌"
50
- text += f"- {icon} **{name}**: {status}"
51
- if error:
52
- text += f" β€” `{error}`"
53
- all_ok = False
54
- text += "\n"
55
-
56
- if all_ok:
57
- text += "\nπŸŽ‰ All imports OK! The Space should work."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  else:
59
- text += "\n⚠️ Some imports failed. Check the errors above."
60
-
61
- return text
62
-
63
- with gr.Blocks(title="NEXUS Visual Weaver v2.0 β€” Diagnostic") as demo:
64
- gr.Markdown("# 🧡 NEXUS Visual Weaver v2.0 β€” Diagnostic Mode")
65
- gr.Markdown("Checking all module imports to find the runtime error...")
66
-
67
- diag_btn = gr.Button("Run Diagnostics", variant="primary")
68
- diag_output = gr.Markdown("Click Run Diagnostics to check...")
69
-
70
- diag_btn.click(fn=run_diagnostics, inputs=[], outputs=diag_output)
71
-
72
- # Auto-run on load
73
- demo.load(fn=run_diagnostics, inputs=[], outputs=diag_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  if __name__ == "__main__":
76
- demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", "7860")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NEXUS Visual Weaver - Build Small Hackathon command center."""
2
+
3
+ from __future__ import annotations
4
+
5
  import os
6
  import sys
7
+ import hashlib
8
+ import secrets
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from urllib.parse import urlparse
12
+
13
+ import gradio as gr
14
+
15
+ ROOT = Path(__file__).resolve().parent
16
+ SRC = ROOT / "src"
17
+ if str(SRC) not in sys.path:
18
+ sys.path.insert(0, str(SRC))
19
+
20
+ try:
21
+ import spaces # type: ignore # noqa: F401
22
+ except Exception: # pragma: no cover - local development does not require Spaces.
23
+ spaces = None
24
+
25
+ from nexus_visual_weaver.catalog import catalog_summary
26
+ from nexus_visual_weaver.exporter import write_export_packet
27
+ from nexus_visual_weaver.hf_runtime import generate_flux_image
28
+ from nexus_visual_weaver.model_relay import WeaverModelRelay
29
+ from nexus_visual_weaver.planner import build_command_center_run
30
+ from nexus_visual_weaver.provider_runtime import judge_with_minicpm, judge_with_nemotron
31
+ from nexus_visual_weaver.render import render_catalog_table, render_command_header, render_dashboard_regions
32
+ from nexus_visual_weaver.security import scan_file
33
+ from nexus_visual_weaver.styles import APP_CSS
34
+
35
+ # FIX: Gradio 6.18 requires Font objects, not bare strings
36
+ APP_THEME = gr.themes.Base(
37
+ primary_hue="rose",
38
+ secondary_hue="cyan",
39
+ neutral_hue="slate",
40
+ radius_size="sm",
41
+ font=gr.themes.Font(google="Inter", weights=["400", "600", "700"]),
42
+ )
43
+
44
+
45
+ DEFAULT_PROMPT = (
46
+ "A Slavic archivist in a rain-slick neon city, wearing a structured black patent "
47
+ "leather long coat with faux fur collar, Chantilly lace neckline, glowing crimson "
48
+ "hardware, platform boots, NEXUS sigils and floating code streams behind her."
49
+ )
50
+
51
+ MODEL_RELAY = WeaverModelRelay()
52
+
53
+ STYLE_MODIFIERS = {
54
+ "Balanced": "balanced editorial lighting, precise garment detail, clean composition",
55
+ "High Fashion": "haute couture editorial styling, premium material finish, runway-grade silhouette",
56
+ "Cinematic": "cinematic rain-lit atmosphere, dramatic lensing, high contrast neon reflections",
57
+ }
58
+
59
+ ASPECT_DIMENSIONS = {
60
+ "Square": (1024, 1024),
61
+ "Portrait": (832, 1216),
62
+ }
63
+
64
+
65
+ def _default_operator_state() -> dict[str, Any]:
66
+ return {
67
+ "provider_state": "idle",
68
+ "checkpoint": "pending",
69
+ "export": "pending",
70
+ "message": "No operator action yet.",
71
+ }
72
+
73
+
74
+ def _zero_gpu_entrypoint(fn: Any) -> Any:
75
+ gpu_decorator = getattr(spaces, "GPU", None) if spaces is not None else None
76
+ if gpu_decorator is None:
77
+ return fn
78
+ return gpu_decorator(duration=300)(fn)
79
+
80
+
81
+ def _relay_snapshot(adult_mode: bool = False) -> dict[str, Any]:
82
+ return MODEL_RELAY.dashboard_snapshot(public_demo=not adult_mode)
83
+
84
+
85
+ def _file_path(uploaded: Any) -> str | None:
86
+ if uploaded is None:
87
+ return None
88
+ if isinstance(uploaded, str):
89
+ return uploaded
90
+ path = getattr(uploaded, "name", None)
91
+ return str(path) if path else None
92
+
93
+
94
+ def _safe_file_hash(path: str | None) -> tuple[str | None, int | None]:
95
+ if not path:
96
+ return None, None
97
+ try:
98
+ target = Path(path)
99
+ sha256 = hashlib.sha256()
100
+ size = 0
101
+ with target.open("rb") as handle:
102
+ while chunk := handle.read(1024 * 1024):
103
+ sha256.update(chunk)
104
+ size += len(chunk)
105
+ except OSError:
106
+ return None, None
107
+ return sha256.hexdigest(), size
108
+
109
+
110
+ def _safe_reference_url_metadata(reference_url: str | None) -> dict[str, Any] | None:
111
+ if not reference_url:
112
+ return None
113
+ parsed = urlparse(reference_url.strip())
114
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
115
+ return {"source": "url", "status": "invalid_url", "message": "Reference URL must be http(s)."}
116
+ url_hash = hashlib.sha256(reference_url.strip().encode("utf-8")).hexdigest()
117
+ return {
118
+ "source": "url",
119
+ "status": "metadata_only",
120
+ "domain": parsed.netloc.lower(),
121
+ "url_hash": url_hash,
122
+ "message": "URL stored as metadata only; Space runtime does not crawl or copy shop images.",
123
+ }
124
+
125
+
126
+ def _reference_metadata(uploaded: Any, reference_url: str | None, scan: dict[str, Any]) -> list[dict[str, Any]]:
127
+ records: list[dict[str, Any]] = []
128
+ path = _file_path(uploaded)
129
+ if path:
130
+ file_hash, size = _safe_file_hash(path)
131
+ records.append(
132
+ {
133
+ "source": "upload",
134
+ "basename": Path(path).name,
135
+ "sha256": file_hash,
136
+ "size_bytes": size,
137
+ "st3gg_status": scan.get("status"),
138
+ "export_gate": scan.get("export_gate"),
139
+ "magic": scan.get("magic"),
140
+ "extension": scan.get("extension"),
141
+ }
142
+ )
143
+ url_record = _safe_reference_url_metadata(reference_url)
144
+ if url_record:
145
+ records.append(url_record)
146
+ return records
147
+
148
+
149
+ def _creator_controls(
150
+ reasoning_mode: str,
151
+ video_preset: str,
152
+ silhouette: str | None = None,
153
+ outerwear: str | None = None,
154
+ upper_body: str | None = None,
155
+ footwear: str | None = None,
156
+ palette: str | None = None,
157
+ hardware: str | None = None,
158
+ locate_focus: list[str] | None = None,
159
+ seed: int | None = None,
160
+ style_strength: str = "High Fashion",
161
+ aspect: str = "Portrait",
162
+ ) -> dict[str, Any]:
163
+ wardrobe = {
164
+ "silhouette": silhouette or "structured long coat",
165
+ "outerwear": outerwear or "black patent leather long coat",
166
+ "upper_body": upper_body or "Chantilly lace neckline",
167
+ "footwear": footwear or "platform boots",
168
+ "palette": palette or "black, crimson, cyan neon",
169
+ "hardware": hardware or "crimson hardware",
170
+ "locked_slots": ["outerwear", "upper_body", "footwear", "jewelry"],
171
+ "locate_focus": locate_focus or ["outerwear", "footwear", "jewelry"],
172
+ }
173
+ return {
174
+ "reasoning_mode": reasoning_mode,
175
+ "video_preset": video_preset,
176
+ "wardrobe": wardrobe,
177
+ "generation": {
178
+ "flux_primary": "black-forest-labs/FLUX.2-klein-9B",
179
+ "flux_sidecar": "black-forest-labs/FLUX.2-klein-4B",
180
+ "lora_policy": "attempt compatible runtime adapter; report loaded/skipped/failed",
181
+ "seed": seed,
182
+ "style_strength": style_strength,
183
+ "aspect": aspect,
184
+ },
185
+ }
186
+
187
+
188
+ def _resolve_seed(seed_value: Any) -> int:
189
+ try:
190
+ if seed_value is None or str(seed_value).strip() == "":
191
+ return secrets.randbelow(1_000_000_000)
192
+ seed = int(float(seed_value))
193
+ except (TypeError, ValueError):
194
+ return secrets.randbelow(1_000_000_000)
195
+ return secrets.randbelow(1_000_000_000) if seed < 0 else seed
196
+
197
+
198
+ def _generation_dimensions(aspect: str | None) -> tuple[int, int]:
199
+ return ASPECT_DIMENSIONS.get(str(aspect or "Portrait"), ASPECT_DIMENSIONS["Portrait"])
200
+
201
+
202
+ def _style_modifier(style_strength: str | None) -> str:
203
+ return STYLE_MODIFIERS.get(str(style_strength or "High Fashion"), STYLE_MODIFIERS["High Fashion"])
204
+
205
+
206
+ def _prompt_with_controls(prompt: str, controls: dict[str, Any]) -> str:
207
+ wardrobe = controls.get("wardrobe", {})
208
+ additions = [
209
+ wardrobe.get("silhouette"),
210
+ wardrobe.get("outerwear"),
211
+ wardrobe.get("upper_body"),
212
+ wardrobe.get("footwear"),
213
+ wardrobe.get("palette"),
214
+ wardrobe.get("hardware"),
215
+ ]
216
+ suffix = ", ".join(str(item) for item in additions if item)
217
+ generation = controls.get("generation", {})
218
+ if not suffix and not generation:
219
+ return prompt
220
+ style = _style_modifier(str(generation.get("style_strength", "High Fashion")))
221
+ prompt = f"{prompt}\nWardrobe controls: {suffix}" if suffix else prompt
222
+ return f"{prompt}\nStyle direction: {style}"
223
+
224
+
225
+ def _generated_output_path(operator_state: dict[str, Any] | None) -> str | None:
226
+ generation = (operator_state or {}).get("generation") or {}
227
+ output_path = generation.get("output_path")
228
+ return str(output_path) if output_path else None
229
+
230
+
231
+ def _authoritative_generated_scan(operator_state: dict[str, Any] | None) -> dict[str, Any]:
232
+ output_path = _generated_output_path(operator_state)
233
+ if output_path:
234
+ return scan_file(output_path)
235
+ stored_scan = (operator_state or {}).get("generated_scan")
236
+ return stored_scan if isinstance(stored_scan, dict) else scan_file(None)
237
+
238
+
239
+ def _checkpoint_seed(checkpoint_id: str) -> int:
240
+ suffix = "".join(char for char in checkpoint_id[-8:] if char in "0123456789abcdefABCDEF")
241
+ if not suffix:
242
+ return 0
243
+ try:
244
+ return int(suffix, 16) % 1_000_000
245
+ except ValueError:
246
+ return 0
247
+
248
+
249
+ def _wardrobe_summary(run: Any) -> str:
250
+ slots = getattr(getattr(run, "outfit", None), "slots", []) or []
251
+ return "; ".join(
252
+ f"{slot.name}: {slot.description}, material={slot.material}, palette={slot.palette}, locked={slot.locked}"
253
+ for slot in slots
254
+ )
255
+
256
+
257
+ SECTIONS = ["Forge", "Wardrobe", "Lore", "Models", "Security", "Runs"]
258
+
259
+
260
+ def _button_updates(run: Any | None, operator_state: dict[str, Any] | None) -> tuple[Any, Any, Any]:
261
+ state = operator_state or {}
262
+ generated = bool(_generated_output_path(state)) and (state.get("generation") or {}).get("status") == "success"
263
+ checkpoint_approved = state.get("checkpoint") == "approved"
264
+ exported = state.get("provider_state") == "exported"
265
+ return (
266
+ gr.update(interactive=generated and not checkpoint_approved and not exported),
267
+ gr.update(interactive=generated and checkpoint_approved and not exported),
268
+ gr.update(interactive=False),
269
+ )
270
+
271
+
272
+ def _dashboard_regions(
273
+ run: Any | None = None,
274
+ adult_mode: bool = False,
275
+ scan: dict[str, Any] | None = None,
276
+ active_section: str = "Forge",
277
+ operator_state: dict[str, Any] | None = None,
278
+ ) -> dict[str, str]:
279
+ return render_dashboard_regions(
280
+ run=run,
281
+ adult_mode=adult_mode,
282
+ scan=scan,
283
+ relay_status=_relay_snapshot(adult_mode),
284
+ active_section=active_section,
285
+ operator_state=operator_state,
286
+ )
287
+
288
+
289
+ # ─── Modal Integration ───
290
+ MODAL_AVAILABLE = False
291
+ try:
292
+ import modal
293
+ MODAL_AVAILABLE = True
294
+ except ImportError:
295
+ pass
296
+
297
+ # LoRA Registry (mirrors modal_nexus_refine_v2.py)
298
+ LORA_ADAPTERS = {
299
+ "garment": {"repo": "NO8D/BodyControl", "desc": "Body/garment shape control", "weight": 0.75},
300
+ "hardware": {"repo": "NO8D/ExpressionControl", "desc": "Expression/hardware detail", "weight": 0.70},
301
+ "realism": {"repo": "fal/realism-detailer", "desc": "Photorealistic detail boost", "weight": 0.60},
302
+ "metallic": {"repo": "ilkerzgi/metallic", "desc": "Metallic material finish", "weight": 0.55},
303
+ "glittering": {"repo": "ilkerzgi/glittering-portrait", "desc": "Glittering portrait effects", "weight": 0.55},
304
+ "embroidery": {"repo": "ilkerzgi/embroidery-patch", "desc": "Embroidery/patch textures", "weight": 0.55},
305
+ }
306
+
307
+ GPU_OPTIONS = {
308
+ "A100-80GB": {"price": 1.80, "modal_gpu": "A100"},
309
+ "A100-40GB": {"price": 1.10, "modal_gpu": "A10G"},
310
+ "L40S": {"price": 1.05, "modal_gpu": "L40S"},
311
+ "T4": {"price": 0.40, "modal_gpu": "T4"},
312
+ }
313
 
314
+ MODAL_COST_TRACKER = {"credits_remaining": 250.88, "total_spent": 0.0, "refinements": 0}
 
 
 
 
315
 
 
316
 
317
+ def _modal_refine_image(image_bytes: bytes, user_addition: str, gpu_type: str = "A100-80GB",
318
+ strength: float = 0.58, steps: int = 32, guidance_scale: float = 3.8,
319
+ seed: int = -1, lora_adapters: list[str] | None = None,
320
+ negative_prompt: str = "blurry, low quality, deformed, extra limbs") -> tuple[bytes | None, str]:
321
+ """Real Modal refinement call β€” wires to nexus-couture-refine-v2 on Modal."""
322
+ if not MODAL_AVAILABLE:
323
+ return None, "❌ Modal not installed. Add 'modal' to requirements.txt"
324
+
325
+ try:
326
+ fn = modal.Function.lookup("nexus-couture-refine-v2", "refine_couture")
327
+ result_bytes = fn.remote(
328
+ image_bytes=image_bytes,
329
+ user_addition=user_addition,
330
+ strength=strength,
331
+ steps=steps,
332
+ guidance_scale=guidance_scale,
333
+ seed=seed,
334
+ lora_adapters=lora_adapters or ["garment"],
335
+ negative_prompt=negative_prompt,
336
+ gpu_type=gpu_type,
337
+ )
338
+ # Update cost tracker
339
+ gpu_info = GPU_OPTIONS.get(gpu_type, GPU_OPTIONS["A100-80GB"])
340
+ est_cost = round(gpu_info["price"] * (steps / 60), 4) # rough: steps/60 hours
341
+ MODAL_COST_TRACKER["total_spent"] += est_cost
342
+ MODAL_COST_TRACKER["credits_remaining"] -= est_cost
343
+ MODAL_COST_TRACKER["refinements"] += 1
344
+ return result_bytes, f"βœ… Modal refinement complete on {gpu_type} (est. ${est_cost:.4f})"
345
+ except Exception as e:
346
+ return None, f"❌ Modal error: {str(e)[:200]}"
347
+
348
+
349
+ def _modal_health_check() -> dict[str, Any]:
350
+ """Check Modal connectivity and GPU availability."""
351
+ if not MODAL_AVAILABLE:
352
+ return {"status": "unavailable", "message": "Modal package not installed"}
353
  try:
354
+ fn = modal.Function.lookup("nexus-couture-refine-v2", "check_modal_health")
355
+ return fn.remote()
356
  except Exception as e:
357
+ return {"status": "error", "message": str(e)[:200]}
358
+
359
+
360
+ @_zero_gpu_entrypoint
361
+ def run_weave(
362
+ prompt: str,
363
+ reasoning_mode: str,
364
+ video_preset: str,
365
+ adult_mode: bool,
366
+ upload: Any,
367
+ active_section: str,
368
+ silhouette: str | None = None,
369
+ outerwear: str | None = None,
370
+ upper_body: str | None = None,
371
+ footwear: str | None = None,
372
+ palette: str | None = None,
373
+ hardware: str | None = None,
374
+ reference_url: str | None = None,
375
+ seed_value: Any = -1,
376
+ style_strength: str = "High Fashion",
377
+ aspect: str = "Portrait",
378
+ ):
379
+ prompt = prompt.strip() or DEFAULT_PROMPT
380
+ resolved_seed = _resolve_seed(seed_value)
381
+ width, height = _generation_dimensions(aspect)
382
+ controls = _creator_controls(
383
+ reasoning_mode=reasoning_mode,
384
+ video_preset=video_preset,
385
+ silhouette=silhouette,
386
+ outerwear=outerwear,
387
+ upper_body=upper_body,
388
+ footwear=footwear,
389
+ palette=palette,
390
+ hardware=hardware,
391
+ seed=resolved_seed,
392
+ style_strength=style_strength,
393
+ aspect=aspect,
394
+ )
395
+ controlled_prompt = _prompt_with_controls(prompt, controls)
396
+ reference_scan = scan_file(_file_path(upload))
397
+ reference_metadata = _reference_metadata(upload, reference_url, reference_scan)
398
+ run = build_command_center_run(
399
+ prompt=controlled_prompt,
400
+ mode=reasoning_mode,
401
+ video_preset=video_preset,
402
+ adult_mode=adult_mode,
403
+ creator_controls=controls,
404
+ reference_metadata=reference_metadata,
405
+ )
406
+ generation = generate_flux_image(
407
+ run.refined_prompt.refined,
408
+ seed=resolved_seed,
409
+ width=width,
410
+ height=height,
411
+ adult_mode=adult_mode,
412
+ )
413
+ generated_scan = scan_file(generation.output_path) if generation.output_path else scan_file(None)
414
+ minicpm = judge_with_minicpm(
415
+ prompt=run.refined_prompt.refined,
416
+ image_path=generation.output_path,
417
+ scan=generated_scan,
418
+ wardrobe_summary=_wardrobe_summary(run),
419
+ )
420
+ nemotron = judge_with_nemotron(
421
+ prompt=run.refined_prompt.refined,
422
+ run_packet=run.to_dict(),
423
+ minicpm_result=minicpm.to_dict(),
424
+ )
425
+ if generation.status == "success":
426
+ provider_state = "generated"
427
+ elif generation.status in {"disabled", "missing_runtime", "no_cuda", "error"}:
428
+ provider_state = generation.provider_state
429
+ else:
430
+ provider_state = "checkpointed"
431
+ operator_state = {
432
+ "provider_state": provider_state,
433
+ "checkpoint": "pending_review",
434
+ "export": generated_scan.get("export_gate", "pending"),
435
+ "message": generation.message or "Image run complete. Human checkpoint required before export.",
436
+ "generation": generation.to_dict(),
437
+ "creator_controls": controls,
438
+ "reference_metadata": reference_metadata,
439
+ "reference_scan": reference_scan,
440
+ "generated_scan": generated_scan,
441
+ "minicpm_judge": minicpm.to_dict(),
442
+ "nemotron_evidence": nemotron.to_dict(),
443
+ }
444
+ regions = _dashboard_regions(
445
+ run=run,
446
+ adult_mode=adult_mode,
447
+ scan=generated_scan,
448
+ active_section=active_section,
449
+ operator_state=operator_state,
450
+ )
451
+ catalog = render_catalog_table(adult_mode=adult_mode)
452
+ return (
453
+ regions["topbar"],
454
+ regions["command_rail"],
455
+ regions["workflow"],
456
+ regions["operations"],
457
+ regions["inspector"],
458
+ regions["drawer"],
459
+ regions["status"],
460
+ regions["artifacts"],
461
+ regions["providers"],
462
+ catalog,
463
+ run.to_dict(),
464
+ catalog_summary(adult_mode),
465
+ generated_scan,
466
+ run,
467
+ generated_scan,
468
+ operator_state,
469
+ *_button_updates(run, operator_state),
470
+ )
471
+
472
+
473
+ def toggle_adult_visibility(
474
+ adult_mode: bool,
475
+ active_section: str,
476
+ upload: Any,
477
+ ) -> tuple[Any, ...]:
478
+ scan = scan_file(_file_path(upload))
479
+ operator_state = {
480
+ **_default_operator_state(),
481
+ "message": "Adult catalog visibility changed. ST3GG, consent, and export gates remain active.",
482
+ }
483
+ regions = _dashboard_regions(adult_mode=adult_mode, scan=scan, active_section=active_section, operator_state=operator_state)
484
+ return (
485
+ regions["topbar"],
486
+ regions["command_rail"],
487
+ regions["operations"],
488
+ regions["inspector"],
489
+ regions["artifacts"],
490
+ regions["providers"],
491
+ render_catalog_table(adult_mode=adult_mode),
492
+ catalog_summary(adult_mode),
493
+ scan,
494
+ operator_state,
495
+ )
496
+
497
+
498
+ def refresh_section(
499
+ active_section: str,
500
+ adult_mode: bool,
501
+ run: Any | None,
502
+ scan: dict[str, Any] | None,
503
+ operator_state: dict[str, Any] | None,
504
+ ) -> tuple[str, str, str, str, str, dict[str, Any]]:
505
+ scan = scan or scan_file(None)
506
+ regions = _dashboard_regions(
507
+ run=run,
508
+ adult_mode=adult_mode,
509
+ scan=scan,
510
+ active_section=active_section,
511
+ operator_state=operator_state or _default_operator_state(),
512
+ )
513
+ return regions["command_rail"], regions["operations"], regions["inspector"], regions["artifacts"], regions["providers"], scan
514
+
515
+
516
+ def _render_stateful(
517
+ run: Any | None,
518
+ adult_mode: bool,
519
+ scan: dict[str, Any] | None,
520
+ active_section: str,
521
+ operator_state: dict[str, Any],
522
+ ) -> tuple[Any, ...]:
523
+ scan = scan or scan_file(None)
524
+ regions = _dashboard_regions(
525
+ run=run,
526
+ adult_mode=adult_mode,
527
+ scan=scan,
528
+ active_section=active_section,
529
+ operator_state=operator_state,
530
+ )
531
+ return (
532
+ regions["topbar"],
533
+ regions["command_rail"],
534
+ regions["workflow"],
535
+ regions["operations"],
536
+ regions["inspector"],
537
+ regions["drawer"],
538
+ regions["status"],
539
+ regions["artifacts"],
540
+ regions["providers"],
541
+ render_catalog_table(adult_mode=adult_mode),
542
+ run.to_dict() if hasattr(run, "to_dict") else {},
543
+ catalog_summary(adult_mode),
544
+ scan,
545
+ operator_state,
546
+ *_button_updates(run, operator_state),
547
+ )
548
+
549
+
550
+ def scan_reference(
551
+ run: Any | None,
552
+ adult_mode: bool,
553
+ upload: Any,
554
+ active_section: str,
555
+ operator_state: dict[str, Any] | None,
556
+ reference_url: str | None = None,
557
+ ) -> tuple[Any, ...]:
558
+ state = operator_state or _default_operator_state()
559
+ reference_path = _file_path(upload)
560
+ reference_scan = scan_file(reference_path)
561
+ reference_metadata = _reference_metadata(upload, reference_url, reference_scan)
562
+ generated_scan = _authoritative_generated_scan(state)
563
+ minicpm = None
564
+ if run is not None and reference_path:
565
+ minicpm = judge_with_minicpm(
566
+ prompt=getattr(getattr(run, "refined_prompt", None), "refined", DEFAULT_PROMPT),
567
+ image_path=reference_path,
568
+ scan=reference_scan,
569
+ wardrobe_summary=_wardrobe_summary(run),
570
+ )
571
+ next_state = {
572
+ **state,
573
+ **({"reference_judge": minicpm.to_dict()} if minicpm else {}),
574
+ "reference_metadata": reference_metadata,
575
+ "reference_scan": reference_scan,
576
+ "reference_export_gate": reference_scan.get("export_gate", "pending"),
577
+ "export": state.get("export", generated_scan.get("export_gate", "pending")),
578
+ "message": (
579
+ "Reference scan complete. Generated artifact export gate is unchanged."
580
+ if reference_scan.get("export_gate") == "clear"
581
+ else "Reference scan requires review. Generated artifact export gate is unchanged."
582
+ ),
583
+ }
584
+ rendered = _render_stateful(run, adult_mode, generated_scan, active_section, next_state)
585
+ return (*rendered, generated_scan)
586
+
587
+
588
+ def approve_checkpoint(
589
+ run: Any | None,
590
+ adult_mode: bool,
591
+ scan: dict[str, Any] | None,
592
+ active_section: str,
593
+ operator_state: dict[str, Any] | None,
594
+ ) -> tuple[Any, ...]:
595
+ state = operator_state or _default_operator_state()
596
+ scan = _authoritative_generated_scan(state)
597
+ if run is None:
598
+ next_state = {**_default_operator_state(), "provider_state": "blocked", "message": "No run exists yet. Generate an image first."}
599
+ elif not _generated_output_path(state):
600
+ next_state = {
601
+ **state,
602
+ "provider_state": "blocked",
603
+ "checkpoint": "pending",
604
+ "message": "Checkpoint blocked: no generated artifact exists yet.",
605
+ }
606
+ else:
607
+ export_state = scan.get("export_gate", "pending")
608
+ next_state = {
609
+ **state,
610
+ "provider_state": "export_ready" if export_state == "clear" else "checkpointed",
611
+ "checkpoint": "approved",
612
+ "generated_scan": scan,
613
+ "export": export_state,
614
+ "message": (
615
+ "Checkpoint approved. Export is ready after clear ST3GG scan."
616
+ if export_state == "clear"
617
+ else "Checkpoint approved. Add an override reason and click Prepare Audit Export to write an audit packet."
618
+ ),
619
+ }
620
+ return _render_stateful(run, adult_mode, scan, active_section, next_state)
621
+
622
+
623
+ def export_packet(
624
+ run: Any | None,
625
+ adult_mode: bool,
626
+ scan: dict[str, Any] | None,
627
+ active_section: str,
628
+ operator_state: dict[str, Any] | None,
629
+ override_reason: str | None = None,
630
+ ) -> tuple[Any, ...]:
631
+ state = operator_state or _default_operator_state()
632
+ scan = _authoritative_generated_scan(state)
633
+ override_reason = (override_reason or "").strip()
634
+ if run is None:
635
+ next_state = {**state, "provider_state": "blocked", "export": "blocked", "message": "Export waits for review: generate an image before preparing an audit packet."}
636
+ elif state.get("checkpoint") != "approved":
637
+ next_state = {**state, "provider_state": "blocked", "export": "blocked", "message": "Export gate active: approve the human checkpoint before release."}
638
+ elif not _generated_output_path(state):
639
+ next_state = {**state, "provider_state": "blocked", "export": "blocked", "message": "Export waits for review: generate an artifact before preparing evidence."}
640
+ elif scan.get("export_gate") != "clear" and not override_reason:
641
+ next_state = {**state, "provider_state": "blocked", "export": scan.get("export_gate", "blocked"), "message": "Export gate active: ST3GG is not clear. Add an explicit override reason to write an audit packet."}
642
  else:
643
+ export_state = "clear" if scan.get("export_gate") == "clear" else "override"
644
+ override_applies = scan.get("export_gate") != "clear" and bool(override_reason)
645
+ export_operator_state = {
646
+ **state,
647
+ **({"st3gg_override_reason": override_reason} if override_applies else {}),
648
+ "export": export_state,
649
+ }
650
+ export = write_export_packet(run=run, scan=scan, operator_state=export_operator_state, adult_mode=adult_mode)
651
+ next_state = {
652
+ **export_operator_state,
653
+ "provider_state": "exported",
654
+ "export": export_state,
655
+ "export_packet": {"path": export["path"]},
656
+ "message": f"Governed export packet prepared: {export['path']}" if export_state == "clear" else f"ST3GG override audit packet prepared: {export['path']}",
657
+ }
658
+ return _render_stateful(run, adult_mode, scan, active_section, next_state)
659
+
660
+
661
+ def stop_provider_job(
662
+ run: Any | None,
663
+ adult_mode: bool,
664
+ scan: dict[str, Any] | None,
665
+ active_section: str,
666
+ operator_state: dict[str, Any] | None,
667
+ ) -> tuple[Any, ...]:
668
+ scan = scan or scan_file(None)
669
+ next_state = {
670
+ **(operator_state or _default_operator_state()),
671
+ "provider_state": "stopped",
672
+ "message": "Provider handoff stopped. Local run packet and evidence remain available.",
673
+ }
674
+ return _render_stateful(run, adult_mode, scan, active_section, next_state)
675
+
676
+
677
+ def reset_demo(
678
+ adult_mode: bool,
679
+ active_section: str,
680
+ ) -> tuple[Any, ...]:
681
+ scan = scan_file(None)
682
+ operator_state = _default_operator_state()
683
+ regions = _dashboard_regions(adult_mode=adult_mode, scan=scan, active_section=active_section, operator_state=operator_state)
684
+ return (
685
+ regions["topbar"],
686
+ regions["command_rail"],
687
+ regions["workflow"],
688
+ regions["operations"],
689
+ regions["inspector"],
690
+ regions["drawer"],
691
+ regions["status"],
692
+ regions["artifacts"],
693
+ regions["providers"],
694
+ render_catalog_table(adult_mode=adult_mode),
695
+ {},
696
+ catalog_summary(adult_mode),
697
+ scan,
698
+ None,
699
+ scan,
700
+ operator_state,
701
+ gr.update(interactive=False),
702
+ gr.update(interactive=False),
703
+ gr.update(interactive=False),
704
+ )
705
+
706
+
707
+ # ─── Modal Tab Handlers ───
708
+
709
+ def modal_refine_handler(input_image, user_addition, gpu_type, strength, steps, guidance, seed, lora_choices, negative_prompt):
710
+ """Handle Modal refinement from the Space UI."""
711
+ if input_image is None:
712
+ return None, "❌ No input image provided"
713
+ from PIL import Image as PILImage
714
+ from io import BytesIO
715
+ buf = BytesIO()
716
+ if isinstance(input_image, str):
717
+ img = PILImage.open(input_image)
718
+ else:
719
+ img = PILImage.open(input_image)
720
+ img.save(buf, format="PNG")
721
+ image_bytes = buf.getvalue()
722
+
723
+ result_bytes, message = _modal_refine_image(
724
+ image_bytes=image_bytes,
725
+ user_addition=user_addition,
726
+ gpu_type=gpu_type,
727
+ strength=strength,
728
+ steps=int(steps),
729
+ guidance_scale=guidance_scale,
730
+ seed=int(seed),
731
+ lora_adapters=lora_choices if lora_choices else ["garment"],
732
+ negative_prompt=negative_prompt,
733
+ )
734
+ if result_bytes:
735
+ result_img = PILImage.open(BytesIO(result_bytes))
736
+ cost_info = f"Credits remaining: ${MODAL_COST_TRACKER['credits_remaining']:.2f} | Refinements: {MODAL_COST_TRACKER['refinements']}"
737
+ return result_img, f"{message}\n{cost_info}"
738
+ return None, message
739
+
740
+
741
+ def modal_health_handler():
742
+ """Check Modal connectivity."""
743
+ result = _modal_health_check()
744
+ if result.get("status") == "healthy":
745
+ return f"βœ… Modal connected\nGPU: {result.get('gpu', 'N/A')}\nVRAM: {result.get('gpu_memory_gb', 0)}GB\nLoRAs: {', '.join(result.get('lora_registry', []))}"
746
+ elif result.get("status") == "unavailable":
747
+ return f"⚠️ {result.get('message', 'Modal not available')}"
748
+ else:
749
+ return f"❌ Modal error: {result.get('message', 'Unknown')}"
750
+
751
+
752
+ initial_operator_state = _default_operator_state()
753
+ initial_regions = _dashboard_regions(scan=scan_file(None), operator_state=initial_operator_state)
754
+
755
+ with gr.Blocks(title="NEXUS Visual Weaver", css=APP_CSS, theme=APP_THEME) as demo:
756
+ active_run_state = gr.State(None)
757
+ scan_state = gr.State(scan_file(None))
758
+ operator_state = gr.State(initial_operator_state)
759
+ topbar_html = gr.HTML(initial_regions["topbar"], container=False, visible=False)
760
+
761
+ with gr.Tabs():
762
+ # ═══ Tab 1: Studio (existing creator workbench) ═══
763
+ with gr.Tab("🧡 Studio"):
764
+ with gr.Row(elem_id="nw-creator-workbench", elem_classes=["nw-creator-workbench"]):
765
+ with gr.Column(scale=5, min_width=520, elem_id="nw-creator-panel"):
766
+ gr.Markdown("### Create Couture Image")
767
+ gr.Markdown("Describe the look, choose wardrobe controls, then generate. Reference upload is optional.")
768
+ prompt = gr.Textbox(
769
+ value=DEFAULT_PROMPT,
770
+ label="Describe the look",
771
+ lines=4,
772
+ max_lines=6,
773
+ )
774
+
775
+ with gr.Row():
776
+ seed_value = gr.Number(value=-1, precision=0, label="Seed (-1 randomizes)")
777
+ style_strength = gr.Dropdown(
778
+ ["Balanced", "High Fashion", "Cinematic"],
779
+ value="High Fashion",
780
+ label="Style Strength",
781
+ )
782
+ aspect = gr.Dropdown(["Portrait", "Square"], value="Portrait", label="Aspect")
783
+ with gr.Row(elem_classes=["nw-primary-actions"]):
784
+ run_btn = gr.Button("Generate Image", variant="primary", scale=2)
785
+ reset_btn = gr.Button("Reset", scale=1)
786
+
787
+ with gr.Row():
788
+ silhouette = gr.Dropdown(
789
+ ["structured long coat", "fitted gothic bodice", "layered tactical silhouette"],
790
+ value="structured long coat",
791
+ label="Silhouette",
792
+ )
793
+ outerwear = gr.Dropdown(
794
+ ["black patent leather long coat", "faux fur collar coat", "tailored rain slicker"],
795
+ value="black patent leather long coat",
796
+ label="Outerwear",
797
+ )
798
+ with gr.Row():
799
+ upper_body = gr.Dropdown(
800
+ ["Chantilly lace neckline", "black mesh layer", "structured corset bodice"],
801
+ value="Chantilly lace neckline",
802
+ label="Upper Body",
803
+ )
804
+ footwear = gr.Dropdown(
805
+ ["platform boots", "patent leather heels", "armored couture boots"],
806
+ value="platform boots",
807
+ label="Footwear",
808
+ )
809
+ with gr.Row():
810
+ palette = gr.Dropdown(
811
+ ["black, crimson, cyan neon", "obsidian, pearl, crimson", "graphite, magenta, cold blue"],
812
+ value="black, crimson, cyan neon",
813
+ label="Palette",
814
+ )
815
+ hardware = gr.Dropdown(
816
+ ["crimson hardware", "silver occult buckles", "holographic NEXUS sigils"],
817
+ value="crimson hardware",
818
+ label="Hardware",
819
+ )
820
+
821
+ with gr.Accordion("Advanced: scan external file", open=False):
822
+ gr.Markdown("Optional. Generate directly unless you need ST3GG to inspect an uploaded reference or output file.")
823
+ with gr.Row():
824
+ reasoning_mode = gr.Radio(["Strict", "Frontier"], value="Strict", label="Reasoning Mode")
825
+ video_preset = gr.Dropdown(["Wan2.2 I2V", "LTX-2.3"], value="Wan2.2 I2V", label="Video preset (deferred)")
826
+ with gr.Row():
827
+ adult_mode = gr.Checkbox(
828
+ value=False,
829
+ label="Adult Mode 18+ catalog scope",
830
+ info="Off by default. Never disables security, consent, or export gates.",
831
+ )
832
+ reference_url = gr.Textbox(
833
+ label="Reference URL (metadata only)",
834
+ placeholder="https://shop.example/reference-garment",
835
+ )
836
+ upload = gr.File(label="Optional file for ST3GG scan", file_count="single", type="filepath")
837
+ with gr.Row():
838
+ scan_btn = gr.Button("Scan Uploaded File", scale=1)
839
+ stop_btn = gr.Button("Stop Job", variant="stop", interactive=False, scale=1)
840
+
841
+ with gr.Column(scale=4, min_width=460, elem_id="nw-output-panel"):
842
+ gr.Markdown("### Output")
843
+ artifact_html = gr.HTML(initial_regions["artifacts"], container=False)
844
+ with gr.Row(elem_id="nw-checkpoint-actions", elem_classes=["nw-checkpoint-actions"]):
845
+ checkpoint_btn = gr.Button("Approve Checkpoint", scale=1, interactive=False)
846
+ export_btn = gr.Button("Prepare Audit Export", scale=1, interactive=False)
847
+ override_reason = gr.Textbox(
848
+ label="ST3GG Override Reason",
849
+ placeholder="Required only when ST3GG asks for review; explain why this audit packet may be written.",
850
+ lines=2,
851
+ max_lines=3,
852
+ )
853
+ gr.Markdown("Generation is not export. Every artifact stays behind ST3GG review and human checkpoint.")
854
+
855
+ # ═══ Tab 2: Modal Refinement ═══
856
+ with gr.Tab("⚑ Modal"):
857
+ gr.Markdown("## ⚑ Modal GPU Refinement")
858
+ gr.Markdown("Send a generated image to Modal for FLUX.1-Kontext-dev refinement with multi-LoRA on dedicated GPU.")
859
+
860
+ with gr.Row():
861
+ with gr.Column(scale=1):
862
+ modal_input_image = gr.Image(label="Input Image (from Studio or upload)", type="filepath")
863
+ modal_user_addition = gr.Textbox(
864
+ label="Additional prompt text",
865
+ placeholder="glowing crimson buckles, wet pavement reflection",
866
+ value="",
867
+ )
868
+ modal_gpu = gr.Dropdown(
869
+ choices=list(GPU_OPTIONS.keys()),
870
+ value="A100-80GB",
871
+ label="GPU Type",
872
+ )
873
+ modal_loras = gr.CheckboxGroup(
874
+ choices=list(LORA_ADAPTERS.keys()),
875
+ value=["garment", "realism"],
876
+ label="LoRA Adapters",
877
+ )
878
+ with gr.Row():
879
+ modal_strength = gr.Slider(0.1, 1.0, value=0.58, step=0.02, label="Strength")
880
+ modal_steps = gr.Slider(10, 64, value=32, step=2, label="Steps")
881
+ with gr.Row():
882
+ modal_guidance = gr.Slider(1.0, 15.0, value=3.8, step=0.2, label="Guidance Scale")
883
+ modal_seed = gr.Number(value=-1, precision=0, label="Seed (-1 random)")
884
+ modal_negative = gr.Textbox(
885
+ label="Negative Prompt",
886
+ value="blurry, low quality, deformed, extra limbs, bad anatomy, watermark, text",
887
+ )
888
+ with gr.Row():
889
+ modal_refine_btn = gr.Button("🎨 Refine on Modal", variant="primary")
890
+ modal_health_btn = gr.Button("πŸ” Health Check", variant="secondary")
891
+
892
+ with gr.Column(scale=1):
893
+ modal_output_image = gr.Image(label="Refined Output")
894
+ modal_status = gr.Textbox(label="Status", lines=3, interactive=False)
895
+ modal_cost_display = gr.Markdown(
896
+ f"**Credits Remaining:** ${MODAL_COST_TRACKER['credits_remaining']:.2f} | "
897
+ f"**Spent:** ${MODAL_COST_TRACKER['total_spent']:.4f} | "
898
+ f"**Refinements:** {MODAL_COST_TRACKER['refinements']}"
899
+ )
900
+
901
+ # Wire Modal handlers
902
+ modal_refine_btn.click(
903
+ fn=modal_refine_handler,
904
+ inputs=[modal_input_image, modal_user_addition, modal_gpu, modal_strength,
905
+ modal_steps, modal_guidance, modal_seed, modal_loras, modal_negative],
906
+ outputs=[modal_output_image, modal_status],
907
+ )
908
+ modal_health_btn.click(
909
+ fn=modal_health_handler,
910
+ inputs=[],
911
+ outputs=[modal_status],
912
+ )
913
+
914
+ # ═══ Tab 3: LoRA Lab ═══
915
+ with gr.Tab("πŸ§ͺ LoRA Lab"):
916
+ gr.Markdown("## πŸ§ͺ LoRA Training Lab")
917
+ gr.Markdown("Train custom LoRA adapters on Modal GPU. Connect a dataset repo and configure training parameters.")
918
+
919
+ with gr.Row():
920
+ with gr.Column(scale=1):
921
+ lora_dataset_repo = gr.Textbox(
922
+ label="Dataset Repo (HF)",
923
+ value="specimba/nexus-couture-training",
924
+ placeholder="username/dataset-name",
925
+ )
926
+ lora_output_name = gr.Textbox(label="Output Adapter Name", value="nexus-couture-v1")
927
+ with gr.Row():
928
+ lora_rank = gr.Slider(4, 64, value=16, step=4, label="Rank")
929
+ lora_lr = gr.Textbox(label="Learning Rate", value="1e-4")
930
+ with gr.Row():
931
+ lora_steps = gr.Slider(100, 3000, value=800, step=100, label="Training Steps")
932
+ lora_batch = gr.Slider(1, 16, value=4, step=1, label="Batch Size")
933
+ lora_push = gr.Checkbox(label="Push to Hub after training", value=False)
934
+ lora_hub_repo = gr.Textbox(
935
+ label="Hub Repo (if pushing)",
936
+ value="build-small-hackathon/nexus-couture-lora",
937
+ )
938
+ lora_train_btn = gr.Button("πŸš€ Start Training on Modal", variant="primary")
939
+
940
+ with gr.Column(scale=1):
941
+ lora_train_status = gr.Textbox(label="Training Status", lines=8, interactive=False)
942
+ gr.Markdown("### Available LoRA Adapters")
943
+ lora_catalog_md = "\n".join(
944
+ f"- **{k}**: {v['desc']} (`{v['repo']}`, weight={v['weight']})"
945
+ for k, v in LORA_ADAPTERS.items()
946
+ )
947
+ gr.Markdown(lora_catalog_md)
948
+
949
+ def lora_train_handler(dataset_repo, output_name, rank, lr, steps, batch, push, hub_repo):
950
+ if not MODAL_AVAILABLE:
951
+ return "❌ Modal not installed"
952
+ try:
953
+ fn = modal.Function.lookup("nexus-couture-lora-trainer", "train_nexus_couture_lora")
954
+ # Training is async - we just trigger it
955
+ fn.remote(
956
+ dataset_repo=dataset_repo,
957
+ output_name=output_name,
958
+ rank=int(rank),
959
+ steps=int(steps),
960
+ learning_rate=float(lr),
961
+ batch_size=int(batch),
962
+ push_to_hub=push,
963
+ hub_repo=hub_repo,
964
+ )
965
+ return f"βœ… Training triggered on Modal!\nDataset: {dataset_repo}\nOutput: {output_name}\nRank: {rank}, Steps: {steps}, LR: {lr}"
966
+ except Exception as e:
967
+ return f"❌ Training error: {str(e)[:300]}"
968
+
969
+ lora_train_btn.click(
970
+ fn=lora_train_handler,
971
+ inputs=[lora_dataset_repo, lora_output_name, lora_rank, lora_lr,
972
+ lora_steps, lora_batch, lora_push, lora_hub_repo],
973
+ outputs=[lora_train_status],
974
+ )
975
+
976
+ # ═══ Tab 4: Technical Evidence (existing accordions moved here) ═══
977
+ with gr.Tab("πŸ” Evidence"):
978
+ with gr.Accordion("Run Anatomy", open=False):
979
+ with gr.Row(elem_id="nw-workspace", elem_classes=["nw-workspace"]):
980
+ with gr.Column(scale=1, min_width=160, elem_id="nw-native-rail"):
981
+ section_nav = gr.Radio(SECTIONS, value="Forge", label="Technical Section", elem_id="nw-section-nav")
982
+ command_rail_html = gr.HTML(initial_regions["command_rail"], container=False)
983
+ with gr.Column(scale=5, min_width=620, elem_id="nw-main-column"):
984
+ workflow_html = gr.HTML(initial_regions["workflow"], container=False)
985
+
986
+ with gr.Accordion("Wardrobe Evidence", open=False):
987
+ operations_html = gr.HTML(initial_regions["operations"], container=False)
988
+ drawer_html = gr.HTML(initial_regions["drawer"], container=False)
989
+
990
+ with gr.Accordion("Technical Evidence", open=False):
991
+ status_html = gr.HTML(initial_regions["status"], container=False)
992
+ inspector_html = gr.HTML(initial_regions["inspector"], container=False)
993
+ with gr.Accordion("Provider Diagnostics", open=False):
994
+ provider_html = gr.HTML(initial_regions["providers"], container=False)
995
+
996
+ with gr.Accordion("Catalog, run record, and security evidence", open=False):
997
+ catalog_html = gr.HTML(render_catalog_table(False), container=False)
998
+ with gr.Row():
999
+ run_json = gr.JSON(label="GenerationRun")
1000
+ catalog_json = gr.JSON(label="Catalog Summary")
1001
+ scan_json = gr.JSON(label="ST3GG Scan")
1002
+
1003
+ dashboard_outputs = [
1004
+ topbar_html,
1005
+ command_rail_html,
1006
+ workflow_html,
1007
+ operations_html,
1008
+ inspector_html,
1009
+ drawer_html,
1010
+ status_html,
1011
+ artifact_html,
1012
+ provider_html,
1013
+ catalog_html,
1014
+ run_json,
1015
+ catalog_json,
1016
+ scan_json,
1017
+ ]
1018
+
1019
+ stateful_outputs = dashboard_outputs + [active_run_state, scan_state, operator_state, checkpoint_btn, export_btn, stop_btn]
1020
+ operator_outputs = dashboard_outputs + [operator_state, checkpoint_btn, export_btn, stop_btn]
1021
+
1022
+ run_click = run_btn.click(
1023
+ fn=run_weave,
1024
+ inputs=[
1025
+ prompt,
1026
+ reasoning_mode,
1027
+ video_preset,
1028
+ adult_mode,
1029
+ upload,
1030
+ section_nav,
1031
+ silhouette,
1032
+ outerwear,
1033
+ upper_body,
1034
+ footwear,
1035
+ palette,
1036
+ hardware,
1037
+ reference_url,
1038
+ seed_value,
1039
+ style_strength,
1040
+ aspect,
1041
+ ],
1042
+ outputs=stateful_outputs,
1043
+ api_name="run_active_weave",
1044
+ concurrency_limit=1,
1045
+ concurrency_id="flux-gpu",
1046
+ )
1047
+ run_submit = prompt.submit(
1048
+ fn=run_weave,
1049
+ inputs=[
1050
+ prompt,
1051
+ reasoning_mode,
1052
+ video_preset,
1053
+ adult_mode,
1054
+ upload,
1055
+ section_nav,
1056
+ silhouette,
1057
+ outerwear,
1058
+ upper_body,
1059
+ footwear,
1060
+ palette,
1061
+ hardware,
1062
+ reference_url,
1063
+ seed_value,
1064
+ style_strength,
1065
+ aspect,
1066
+ ],
1067
+ outputs=stateful_outputs,
1068
+ api_name=False,
1069
+ concurrency_limit=1,
1070
+ concurrency_id="flux-gpu",
1071
+ )
1072
+ adult_mode.change(
1073
+ fn=toggle_adult_visibility,
1074
+ inputs=[adult_mode, section_nav, upload],
1075
+ outputs=[
1076
+ topbar_html,
1077
+ command_rail_html,
1078
+ operations_html,
1079
+ inspector_html,
1080
+ artifact_html,
1081
+ provider_html,
1082
+ catalog_html,
1083
+ catalog_json,
1084
+ scan_json,
1085
+ operator_state,
1086
+ ],
1087
+ api_name="toggle_adult_catalog",
1088
+ queue=False,
1089
+ )
1090
+ section_nav.change(
1091
+ fn=refresh_section,
1092
+ inputs=[section_nav, adult_mode, active_run_state, scan_state, operator_state],
1093
+ outputs=[command_rail_html, operations_html, inspector_html, artifact_html, provider_html, scan_json],
1094
+ api_name=False,
1095
+ queue=False,
1096
+ )
1097
+ scan_btn.click(
1098
+ fn=scan_reference,
1099
+ inputs=[active_run_state, adult_mode, upload, section_nav, operator_state, reference_url],
1100
+ outputs=dashboard_outputs + [operator_state, checkpoint_btn, export_btn, stop_btn, scan_state],
1101
+ api_name="scan_reference",
1102
+ queue=False,
1103
+ )
1104
+ checkpoint_btn.click(
1105
+ fn=approve_checkpoint,
1106
+ inputs=[active_run_state, adult_mode, scan_state, section_nav, operator_state],
1107
+ outputs=operator_outputs,
1108
+ api_name="approve_checkpoint",
1109
+ queue=False,
1110
+ )
1111
+ export_btn.click(
1112
+ fn=export_packet,
1113
+ inputs=[active_run_state, adult_mode, scan_state, section_nav, operator_state, override_reason],
1114
+ outputs=operator_outputs,
1115
+ api_name="prepare_export_packet",
1116
+ queue=False,
1117
+ )
1118
+ stop_btn.click(
1119
+ fn=stop_provider_job,
1120
+ inputs=[active_run_state, adult_mode, scan_state, section_nav, operator_state],
1121
+ outputs=operator_outputs,
1122
+ api_name="stop_provider_job",
1123
+ queue=False,
1124
+ cancels=[run_click, run_submit],
1125
+ )
1126
+ reset_btn.click(
1127
+ fn=reset_demo,
1128
+ inputs=[adult_mode, section_nav],
1129
+ outputs=stateful_outputs,
1130
+ api_name="reset_demo_state",
1131
+ queue=False,
1132
+ cancels=[run_click, run_submit],
1133
+ )
1134
+ demo.load(
1135
+ fn=lambda: (render_catalog_table(False), catalog_summary(False), scan_file(None), scan_file(None), _default_operator_state()),
1136
+ outputs=[catalog_html, catalog_json, scan_json, scan_state, operator_state],
1137
+ api_name=False,
1138
+ )
1139
+
1140
 
1141
  if __name__ == "__main__":
1142
+ if hasattr(sys.stdout, "reconfigure"):
1143
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
1144
+ if hasattr(sys.stderr, "reconfigure"):
1145
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
1146
+
1147
+ demo.launch(
1148
+ server_name="0.0.0.0",
1149
+ server_port=int(os.environ.get("NEXUS_PORT", os.environ.get("PORT", "7860"))),
1150
+ quiet=True,
1151
+ mcp_server=True,
1152
+ ssr_mode=False,
1153
+ css=APP_CSS,
1154
+ theme=APP_THEME,
1155
+ )