AnimeOverlord commited on
Commit
9e606d9
·
1 Parent(s): b29a89f

initial commit less goo

Browse files
Files changed (3) hide show
  1. app.py +135 -0
  2. backend/backend.py +99 -0
  3. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import gradio as gr
5
+ import modal
6
+ from fastrtc import WebRTC, get_cloudflare_turn_credentials
7
+
8
+ # Environment control flag to swap pipelines from the HF Space configuration dashboard
9
+ USE_GPU_INFERENCE = os.getenv("USE_GPU_INFERENCE", "false").lower() == "true"
10
+
11
+ # Connect to your deployed serverless backend running on Modal
12
+ try:
13
+ if USE_GPU_INFERENCE:
14
+ print("🚀 Mode: Full GPU FLUX.2 Klein Inference")
15
+ voxel_backend = modal.Function.lookup("flux-klein-voxel-backend", "VoxelModel.process_frame")
16
+ else:
17
+ print("🏎️ Mode: Zero-latency WebRTC Passthrough Demo")
18
+ voxel_backend = modal.Function.lookup("flux-klein-voxel-backend", "demo_stream_frame")
19
+ except Exception as e:
20
+ print(f"⚠️ Could not bind Modal backend function layout: {e}")
21
+ voxel_backend = None
22
+
23
+ def process_video_stream(frame: np.ndarray, prompt: str, strength: float) -> np.ndarray:
24
+ """
25
+ Receives real-time video frames from the browser via WebRTC, compresses them,
26
+ ships them to the Modal GPU cluster, and returns the voxelized matrix.
27
+ """
28
+ if frame is None:
29
+ return None
30
+
31
+ # Fallback state if the backend app isn't active or authenticated yet
32
+ if voxel_backend is None:
33
+ output_frame = frame.copy()
34
+ cv2.putText(output_frame, "ERROR: Backend App Offline", (20, 40),
35
+ cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
36
+ cv2.putText(output_frame, "Check HF Space Secrets for MODAL keys.", (20, 70),
37
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
38
+ return output_frame
39
+
40
+ # Step 1: Compress high-res frames to a lean JPEG byte stream to prevent browser pipe congestion
41
+ success, encoded_image = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 85])
42
+ if not success:
43
+ return frame
44
+
45
+ frame_bytes = encoded_image.tobytes()
46
+
47
+ # Step 2: Route request to serverless GPU infrastructure
48
+ try:
49
+ # Dynamically matches positional signature parameters to prevent signature TypeErrors
50
+ if USE_GPU_INFERENCE:
51
+ processed_bytes = voxel_backend.remote(frame_bytes, prompt, strength)
52
+ else:
53
+ processed_bytes = voxel_backend.remote(frame_bytes)
54
+
55
+ # Step 3: Reconstruction of the returned processed image array
56
+ numpy_buffer = np.frombuffer(processed_bytes, dtype=np.uint8)
57
+ voxel_frame = cv2.imdecode(numpy_buffer, cv2.IMREAD_COLOR)
58
+ return voxel_frame
59
+
60
+ except Exception as err:
61
+ # Handle serverless cold starts visually instead of freezing or crashing the stream
62
+ fallback_frame = frame.copy()
63
+ cv2.putText(fallback_frame, "⚡ Modal Serverless Warm-up (15-30s)...", (20, 40),
64
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)
65
+ cv2.putText(fallback_frame, "Loading FLUX Klein weights into cloud VRAM", (20, 70),
66
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
67
+ return fallback_frame
68
+
69
+ # --- CUSTOM CSS FOR HIGH-TECH SPATIAL AESTHETICS ---
70
+ custom_css = """
71
+ #container { max-width: 1100px; margin: 0 auto; padding-top: 20px; }
72
+ .header-text { text-align: center; margin-bottom: 25px; }
73
+ .header-text h1 { color: #5c8e32; font-family: 'Courier New', Courier, monospace; font-weight: bold; margin-bottom: 5px; }
74
+ .header-text p { color: #666; font-size: 1.1em; }
75
+ """
76
+
77
+ # --- GRADIO INTERFACE ARCHITECTURE ---
78
+ with gr.Blocks(css=custom_css, title="Minecraft Spatial Voxel Filter") as demo:
79
+
80
+ with gr.Div(elem_id="container"):
81
+ with gr.Div(elem_classes="header-text"):
82
+ gr.Markdown("# ⛏️ MINECRAFT SPATIAL VOXEL FILTER ⛏️")
83
+ gr.Markdown("Transform your physical environment into an interactive, real-time 3D blocky landscape running on FLUX.2 Klein.")
84
+
85
+ gr.HTML("<hr style='border: 1px solid #ddd; margin-bottom: 25px;'>")
86
+
87
+ with gr.Row():
88
+ # Left Hand Side: Dynamic Parameters & Controls
89
+ with gr.Column(scale=1):
90
+ gr.Markdown("### 🎛️ Environmental Filters")
91
+
92
+ prompt_input = gr.Textbox(
93
+ value="vanilla minecraft voxel landscape, 3d blocky style, retro game cube aesthetic, highly detailed texture pack",
94
+ label="Biome Environment Blueprint (Prompt)",
95
+ lines=3,
96
+ placeholder="Describe your voxel theme..."
97
+ )
98
+
99
+ with gr.Accordion("Advanced Tuning", open=True):
100
+ denoise_strength = gr.Slider(
101
+ minimum=0.1,
102
+ maximum=1.0,
103
+ step=0.05,
104
+ value=0.55,
105
+ label="Voxelization Denoising Strength"
106
+ )
107
+
108
+ gr.Markdown(
109
+ f"""
110
+ > **💡 Pipeline Status:** Deployed via FastRTC. Current Target Mode: `{"GPU Inference (FLUX)" if USE_GPU_INFERENCE else "CPU Passthrough Demo"}`. Change this via the `USE_GPU_INFERENCE` Space Secret.
111
+ """
112
+ )
113
+
114
+ # Right Hand Side: High-Speed WebRTC Viewport
115
+ with gr.Column(scale=2):
116
+ gr.Markdown("### 📺 Spatial Render Pipeline")
117
+
118
+ # FastRTC custom WebRTC component with auto-configured cloudflare turn discovery
119
+ webrtc_stream = WebRTC(
120
+ label="Live Voxel Viewport",
121
+ modality="video",
122
+ mode="send-receive",
123
+ rtc_configuration=get_cloudflare_turn_credentials
124
+ )
125
+
126
+ # Establish the bidirectional stream wire link
127
+ webrtc_stream.stream(
128
+ fn=process_video_stream,
129
+ inputs=[webrtc_stream, prompt_input, denoise_strength],
130
+ outputs=[webrtc_stream],
131
+ time_limit=150 # Automatically closes connection after inactivity to prevent runaway token spend
132
+ )
133
+
134
+ if __name__ == "__main__":
135
+ demo.launch()
backend/backend.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import modal
4
+
5
+ # Define container environment optimized for lightning-fast image-to-image processing
6
+ image = modal.Image.debian_slim(python_version="3.12").pip_install(
7
+ "diffusers",
8
+ "transformers",
9
+ "accelerate",
10
+ "pillow",
11
+ "torch"
12
+ )
13
+
14
+ app = modal.App("flux-klein-voxel-backend", image=image)
15
+
16
+ # ==============================================================================
17
+ # 🏎️ 1. THE DEMO PIPELINE (Zero Cold-Start / Instant WebRTC Echo Test)
18
+ # ==============================================================================
19
+ @app.function()
20
+ def demo_stream_frame(img_bytes: bytes) -> bytes:
21
+ """
22
+ Decodes the incoming WebRTC frame and returns it instantly.
23
+ Does not spin up a GPU or load a model. Use this to verify that the
24
+ frontend WebRTC connection is 100% functional.
25
+ """
26
+ from PIL import Image, ImageDraw
27
+
28
+ # Unpack the binary stream sent by FastRTC
29
+ input_image = Image.open(io.BytesIO(img_bytes)).convert("RGB")
30
+
31
+ # Optional visual overlay so you know the demo bypass is active
32
+ draw = ImageDraw.Draw(input_image)
33
+ draw.text((20, 20), "🛠️ WEBRTC PASSTHROUGH DEMO ACTIVE", fill=(0, 255, 0))
34
+ draw.text((20, 40), "Inference model bypassed.", fill=(255, 255, 255))
35
+
36
+ # Pack back into high-speed compressed JPEG format
37
+ output_buffer = io.BytesIO()
38
+ input_image.save(output_buffer, format="JPEG", quality=85)
39
+ return output_buffer.getvalue()
40
+
41
+
42
+ # ==============================================================================
43
+ # 🚀 2. THE REAL-TIME VOXEL ENGINE (GPU-Accelerated Inference)
44
+ # ==============================================================================
45
+ @app.cls(
46
+ gpu="A10G",
47
+ secrets=[modal.Secret.from_name("huggingface")],
48
+ concurrency_limit=10 # Scales automatically up to 10 parallel video streams
49
+ )
50
+ class VoxelModel:
51
+
52
+ @modal.enter()
53
+ def load_pipeline(self):
54
+ """Pre-loads model checkpoints into serverless VRAM exactly once upon container initialization"""
55
+ import torch
56
+ from diffusers import DiffusionPipeline
57
+
58
+ # Target your specific fine-tuned space or the base black-forest-labs/FLUX.2-klein-4B
59
+ model_id = "AnimeOverlord/flux2-klein-4b-mc"
60
+ print(f"📦 Spin up sequence initiated. Pulling weights for {model_id}...")
61
+
62
+ # DiffusionPipeline dynamically handles custom fine-tune repo definitions via model_index.json
63
+ self.pipe = DiffusionPipeline.from_pretrained(
64
+ model_id,
65
+ torch_dtype=torch.bfloat16,
66
+ token=os.environ["HF_TOKEN"]
67
+ )
68
+ self.pipe.to("cuda")
69
+
70
+ # Performance Tweaks for low-latency video loops
71
+ self.pipe.enable_attention_slicing()
72
+ print("⚡ Core weights successfully loaded into cloud VRAM.")
73
+
74
+ @modal.function()
75
+ def process_frame(self, img_bytes: bytes, prompt: str, strength: float) -> bytes:
76
+ """Executes targeted frame transformations without saving overhead data to memory"""
77
+ from PIL import Image
78
+ import torch
79
+
80
+ # 1. Unpack compressed binary frame directly from network interface
81
+ input_image = Image.open(io.BytesIO(img_bytes)).convert("RGB")
82
+
83
+ # Hard clamping constraint resolution guarantees predictable frame-rates
84
+ input_image = input_image.resize((512, 512))
85
+
86
+ # 2. Process frame via low-step inference execution
87
+ with torch.inference_mode():
88
+ output_image = self.pipe(
89
+ prompt=prompt,
90
+ image=input_image,
91
+ strength=strength,
92
+ num_inference_steps=4, # Hard locked to match FLUX.2 Klein's step-distilled architecture
93
+ guidance_scale=3.5,
94
+ ).images[0]
95
+
96
+ # 3. Re-pack processing output back to JPEG format for transit
97
+ output_buffer = io.BytesIO()
98
+ output_image.save(output_buffer, format="JPEG", quality=85)
99
+ return output_buffer.getvalue()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio>=5.7.1
2
+ fastrtc>=0.0.34
3
+ opencv-python-headless
4
+ modal
5
+ pillow
6
+ numpy