Files changed (1) hide show
  1. app.py +177 -94
app.py CHANGED
@@ -1,103 +1,186 @@
1
- import spaces # MUST be imported before any CUDA-touching package (torch/diffusers)
 
 
2
 
3
- import gradio as gr
4
- import numpy as np
5
- import random
6
- import torch
7
- from diffusers import Flux2KleinPipeline
8
-
9
- # ---------------------------------------------------------------------------
10
- # Model: FLUX.2 [klein] 4B
11
- # - Apache-2.0, 4B params, BFL's fastest small model (sub-second, ~13GB VRAM)
12
- # - Unified text-to-image + multi-reference editing
13
- # - Released Jan 2026 (current BFL small-model generation)
14
- # ---------------------------------------------------------------------------
15
- MODEL_REPO_ID = "black-forest-labs/FLUX.2-klein-4B"
16
-
17
- dtype = torch.bfloat16
18
- device = "cuda" if torch.cuda.is_available() else "cpu"
19
-
20
- # Load on cuda at module level. (No enable_model_cpu_offload() on ZeroGPU β€”
21
- # the GPU is only attached inside @spaces.GPU; module-level cuda uses the
22
- # ZeroGPU CUDA-emulation, and offload would conflict.)
23
- pipe = Flux2KleinPipeline.from_pretrained(MODEL_REPO_ID, torch_dtype=dtype).to(device)
24
-
25
- MAX_SEED = np.iinfo(np.int32).max
26
- MAX_IMAGE_SIZE = 2048
27
-
28
-
29
- @spaces.GPU(duration=60)
30
- def infer(
31
- prompt,
32
- seed,
33
- randomize_seed,
34
- width,
35
- height,
36
- num_inference_steps,
37
- guidance_scale,
38
- progress=gr.Progress(track_tqdm=True),
39
- ):
40
- if randomize_seed:
41
- seed = random.randint(0, MAX_SEED)
42
- generator = torch.Generator(device=device).manual_seed(seed)
43
- image = pipe(
44
- prompt=prompt,
45
- width=width,
46
- height=height,
47
- num_inference_steps=num_inference_steps,
48
- guidance_scale=guidance_scale,
49
- generator=generator,
50
- ).images[0]
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "A magical city at twilight, glowing windows, storybook illustration, warm light",
56
- "A cat holding a sign that says hello world",
57
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
58
- ]
59
-
60
- css = """
61
- #col-container { margin: 0 auto; max-width: 640px; }
62
  """
63
 
64
- with gr.Blocks(css=css) as demo:
65
- with gr.Column(elem_id="col-container"):
66
- gr.Markdown("# πŸ–ΌοΈ NEXUS Visual Weaver β€” FLUX.2 [klein] 4B")
67
- with gr.Row():
68
- prompt = gr.Text(
69
- label="Prompt",
70
- show_label=False,
71
- max_lines=1,
72
- placeholder="Enter your prompt",
73
- container=False,
74
- )
75
- run_button = gr.Button("Run", scale=0, variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- result = gr.Image(label="Result", show_label=False)
 
 
 
78
 
79
- with gr.Accordion("Advanced Settings", open=False):
80
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
81
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
82
  with gr.Row():
83
- width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024)
84
- height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024)
 
 
 
 
 
85
  with gr.Row():
86
- num_inference_steps = gr.Slider(
87
- label="Inference steps", minimum=1, maximum=8, step=1, value=4
88
- )
89
- guidance_scale = gr.Slider(
90
- label="Guidance scale", minimum=0.0, maximum=5.0, step=0.1, value=1.0
91
- )
92
-
93
- gr.Examples(examples=examples, inputs=[prompt])
94
-
95
- gr.on(
96
- triggers=[run_button.click, prompt.submit],
97
- fn=infer,
98
- inputs=[prompt, seed, randomize_seed, width, height, num_inference_steps, guidance_scale],
99
- outputs=[result, seed],
100
- )
 
 
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  if __name__ == "__main__":
103
- demo.launch()
 
 
 
 
 
 
 
1
+ """
2
+ integrated_nexus_app.py
3
+ NEXUS Visual Weaver - Integrated App (Phase A + HF MCP Bridge)
4
 
5
+ This is the main Gradio application for the hackathon Space.
6
+ It combines:
7
+ - Phase A: Orchestration + Governance Checkpoint UI
8
+ - HF MCP Bridge: Authentication + Repository tools exposed as MCP tools
9
+
10
+ Launch with mcp_server=True for agent integration.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  """
12
 
13
+ import gradio as gr
14
+ from nexus_hf_mcp_bridge import nexus_hf_bridge
15
+
16
+
17
+ # ============================================================
18
+ # Phase A - Original Orchestration Logic (Stub for now)
19
+ # ============================================================
20
+
21
+ def run_refine_and_plan(prompt: str, mode: str):
22
+ """Phase A orchestration stub."""
23
+ return {
24
+ "input_prompt": prompt,
25
+ "reasoning_mode": mode,
26
+ "selected_backbone": "flux_klein_9b" if "image" in prompt.lower() else "ltx_2.3",
27
+ "plan_summary": f"Plan generated for: {prompt[:80]}...",
28
+ "next_step": "Run judgment checkpoint or use HF Bridge"
29
+ }
30
+
31
+
32
+ def run_judgment_checkpoint(plan: dict):
33
+ """Phase A governance checkpoint stub."""
34
+ return {
35
+ "checkpoint_id": "phase_a_checkpoint",
36
+ "trust_score": 82,
37
+ "recommendation": "proceed",
38
+ "justification": "Phase A governance stub. Real thermodynamic detectors coming in next phase.",
39
+ "local_mode": True
40
+ }
41
+
42
+
43
+ # ============================================================
44
+ # HF MCP Bridge UI Functions
45
+ # ============================================================
46
+
47
+ def hf_authenticate():
48
+ """Trigger HF OAuth Device Code flow."""
49
+ result = nexus_hf_bridge.tool_authenticate()
50
+ return result
51
+
52
+
53
+ def hf_create_or_update_file(repo_id: str, path_in_repo: str, content: str):
54
+ """Create or update a file in a Hugging Face repo via the bridge."""
55
+ if not repo_id or not path_in_repo or not content:
56
+ return {"status": "error", "message": "Please fill all fields."}
57
+
58
+ result = nexus_hf_bridge.tool_create_or_update_file(
59
+ repo_id=repo_id,
60
+ path_in_repo=path_in_repo,
61
+ content=content
62
+ )
63
+ return result
64
+
65
+
66
+ def hf_list_files(repo_id: str):
67
+ """List files in a repository."""
68
+ if not repo_id:
69
+ return {"status": "error", "message": "Please provide a repository ID."}
70
+
71
+ result = nexus_hf_bridge.tool_list_repo_files(repo_id=repo_id)
72
+ return result
73
+
74
+
75
+ # ============================================================
76
+ # Gradio UI
77
+ # ============================================================
78
+
79
+ with gr.Blocks(
80
+ title="NEXUS Visual Weaver",
81
+ theme=gr.themes.Soft(),
82
+ css="""
83
+ .nexus-header { font-size: 2.1rem; font-weight: 700; }
84
+ .section-box { border: 1px solid #374151; border-radius: 10px; padding: 16px; margin-top: 10px; }
85
+ """
86
+ ) as demo:
87
+
88
+ gr.HTML("""
89
+ <div style="text-align: center; margin-bottom: 1rem;">
90
+ <h1 class="nexus-header">NEXUS Visual Weaver</h1>
91
+ <span style="background:#1f2937; color:#93c5fd; padding:2px 10px; border-radius:9999px; font-size:0.75rem;">
92
+ Phase A + HF MCP Bridge
93
+ </span>
94
+ </div>
95
+ """)
96
+
97
+ with gr.Tabs():
98
+ # ===================== TAB 1: Phase A Orchestration =====================
99
+ with gr.Tab("πŸŽ›οΈ Orchestration (Phase A)"):
100
+ with gr.Row():
101
+ with gr.Column(scale=3):
102
+ prompt = gr.Textbox(
103
+ label="Creative Direction",
104
+ placeholder="A Slavic model in patent leather trench coat with crimson hardware...",
105
+ lines=5
106
+ )
107
+ mode = gr.Radio(
108
+ ["Strict (High Fidelity)", "Frontier (Creative Exploration)"],
109
+ value="Strict (High Fidelity)",
110
+ label="Reasoning Mode"
111
+ )
112
+ with gr.Column(scale=2):
113
+ gr.Markdown("### Current Status")
114
+ gr.Markdown("- Phase A orchestration active\n- HF MCP Bridge ready\n- Governance layer: Stub mode")
115
+
116
+ with gr.Row():
117
+ refine_btn = gr.Button("πŸ”„ Refine & Create Plan", variant="primary")
118
+ judge_btn = gr.Button("βš–οΈ Run Judgment Checkpoint", variant="secondary")
119
+
120
+ with gr.Row():
121
+ plan_output = gr.JSON(label="Orchestration Plan")
122
+ checkpoint_output = gr.JSON(label="Governance Checkpoint")
123
+
124
+ refine_btn.click(run_refine_and_plan, inputs=[prompt, mode], outputs=plan_output)
125
+ judge_btn.click(run_judgment_checkpoint, inputs=[plan_output], outputs=checkpoint_output)
126
 
127
+ # ===================== TAB 2: HF MCP Bridge =====================
128
+ with gr.Tab("πŸ€– HF MCP Bridge"):
129
+ gr.Markdown("## Hugging Face MCP Bridge")
130
+ gr.Markdown("Authenticate once, then use the tools below. All operations go through the sovereign bridge.")
131
 
 
 
 
132
  with gr.Row():
133
+ auth_btn = gr.Button("πŸ” Authenticate with Hugging Face (Device Code)", variant="primary", scale=1)
134
+ auth_status = gr.JSON(label="Authentication Status")
135
+
136
+ auth_btn.click(hf_authenticate, outputs=auth_status)
137
+
138
+ gr.Markdown("---")
139
+
140
  with gr.Row():
141
+ with gr.Column():
142
+ repo_id = gr.Textbox(label="Repository ID", placeholder="username/my-model")
143
+ path_in_repo = gr.Textbox(label="Path in Repository", placeholder="README.md or folder/file.txt")
144
+ content = gr.Textbox(label="File Content", lines=8, placeholder="Write your content here...")
145
+ update_btn = gr.Button("πŸ“ Create / Update File", variant="primary")
146
+ update_result = gr.JSON(label="Result")
147
+
148
+ with gr.Column():
149
+ list_repo = gr.Textbox(label="Repository ID to List")
150
+ list_btn = gr.Button("πŸ“‚ List Files")
151
+ list_result = gr.JSON(label="Repository Files")
152
+
153
+ update_btn.click(
154
+ hf_create_or_update_file,
155
+ inputs=[repo_id, path_in_repo, content],
156
+ outputs=update_result
157
+ )
158
 
159
+ list_btn.click(
160
+ hf_list_files,
161
+ inputs=[list_repo],
162
+ outputs=list_result
163
+ )
164
+
165
+ # ===================== TAB 3: System =====================
166
+ with gr.Tab("πŸ“Š System"):
167
+ gr.Markdown("### NEXUS Visual Weaver Status")
168
+ gr.Markdown("""
169
+ - **Phase A**: Orchestration + Governance Checkpoint (active)
170
+ - **HF MCP Bridge**: Authentication + Repository tools (integrated)
171
+ - **MCP Server**: Enabled (`mcp_server=True`)
172
+ - **OAuth App**: X - GROK integration for HF
173
+ - **Next**: Thermodynamic governance layer + Zapier MCP integration
174
+ """)
175
+
176
+ # ============================================================
177
+ # Launch
178
+ # ============================================================
179
  if __name__ == "__main__":
180
+ demo.launch(
181
+ server_name="0.0.0.0",
182
+ server_port=7860,
183
+ show_api=True,
184
+ mcp_server=True, # Important for MCP tools
185
+ ssr_mode=False
186
+ )