ysharma HF Staff commited on
Commit
a6e05a5
Β·
verified Β·
1 Parent(s): e3a4717

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +576 -421
app.py CHANGED
@@ -1,106 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
  import torch
5
  import base64
 
6
  from io import BytesIO
7
  from PIL import Image
8
- from diffusers import FlowMatchEulerDiscreteScheduler, QwenImageEditPlusPipeline
9
 
10
  MAX_SEED = np.iinfo(np.int32).max
 
 
11
 
12
- # --- Model Loading ---
13
- dtype = torch.bfloat16
14
- device = "cuda" if torch.cuda.is_available() else "cpu"
15
-
16
- # Initialize pipe as None - will be loaded when needed
 
 
 
 
 
 
 
 
17
  pipe = None
18
 
19
  def load_model():
20
- """Load the model only when needed to avoid initialization errors."""
21
  global pipe
22
  if pipe is None:
23
  pipe = QwenImageEditPlusPipeline.from_pretrained(
24
  "Qwen/Qwen-Image-Edit-2511",
25
- torch_dtype=dtype
26
  ).to(device)
27
 
28
- # Load the lightning LoRA for fast inference
29
  pipe.load_lora_weights(
30
  "lightx2v/Qwen-Image-Edit-2511-Lightning",
31
  weight_name="Qwen-Image-Edit-2511-Lightning-4steps-V1.0-bf16.safetensors",
32
- adapter_name="lightning"
33
  )
34
-
35
- # Load the multi-angles LoRA
36
  pipe.load_lora_weights(
37
  "fal/Qwen-Image-Edit-2511-Multiple-Angles-LoRA",
38
  weight_name="qwen-image-edit-2511-multiple-angles-lora.safetensors",
39
- adapter_name="angles"
40
  )
41
-
42
  pipe.set_adapters(["lightning", "angles"], adapter_weights=[1.0, 1.0])
43
  return pipe
44
 
45
- # --- Camera Parameter Mappings ---
 
46
  AZIMUTH_MAP = {
47
  0: "front view",
48
- 45: "front-right quarter view",
49
  90: "right side view",
50
  135: "back-right quarter view",
51
  180: "back view",
52
  225: "back-left quarter view",
53
- 270: "left side view",
54
- 315: "front-left quarter view"
55
  }
56
-
57
  ELEVATION_MAP = {
58
  -30: "low-angle shot",
59
- 0: "eye-level shot",
60
  30: "elevated shot",
61
- 60: "high-angle shot"
62
  }
63
-
64
  DISTANCE_MAP = {
65
  0.6: "close-up",
66
  1.0: "medium shot",
67
- 1.8: "wide shot"
68
  }
69
 
 
 
 
 
70
  def snap_to_nearest(value, steps):
71
- """Snap value to nearest step."""
72
  return min(steps, key=lambda x: abs(x - value))
73
 
 
74
  def build_camera_prompt(azimuth, elevation, distance):
75
- """Build camera prompt from parameters."""
76
- azimuth_steps = [0, 45, 90, 135, 180, 225, 270, 315]
77
- elevation_steps = [-30, 0, 30, 60]
78
- distance_steps = [0.6, 1.0, 1.8]
79
-
80
- az_snap = snap_to_nearest(azimuth, azimuth_steps)
81
- el_snap = snap_to_nearest(elevation, elevation_steps)
82
- dist_snap = snap_to_nearest(distance, distance_steps)
83
-
84
- az_name = AZIMUTH_MAP[az_snap]
85
- el_name = ELEVATION_MAP[el_snap]
86
- dist_name = DISTANCE_MAP[dist_snap]
87
-
88
- return f"<sks> {az_name} {el_name} {dist_name}"
89
-
90
- def infer_camera_edit(image, azimuth, elevation, distance, seed, randomize_seed, guidance_scale, num_inference_steps, height, width):
91
- """Generate new camera view using the Qwen model."""
 
 
 
 
 
 
 
 
 
92
  if randomize_seed:
93
  seed = random.randint(0, MAX_SEED)
94
-
95
  generator = torch.Generator(device=device).manual_seed(seed)
96
-
97
- # Build the camera prompt
98
- prompt = build_camera_prompt(azimuth, elevation, distance)
99
-
100
- # Load model if not already loaded
101
- model = load_model()
102
-
103
- # Generate the new view
104
  result = model(
105
  image=image,
106
  prompt=prompt,
@@ -108,386 +143,506 @@ def infer_camera_edit(image, azimuth, elevation, distance, seed, randomize_seed,
108
  width=width,
109
  guidance_scale=guidance_scale,
110
  num_inference_steps=num_inference_steps,
111
- generator=generator
112
  ).images[0]
113
-
114
  return result, seed, prompt
115
 
116
- def create_camera_control_app():
117
- """Create the complete camera control app."""
118
-
119
- with gr.Blocks(title="Camera Control with Directional Arrows") as demo:
120
- gr.Markdown("# πŸ“Έ Camera Control with Directional Arrows")
121
- gr.Markdown("Upload an image and use arrows to control camera angles for 3D view generation")
122
-
123
- with gr.Row():
124
- # Left column: Image upload and controls
125
- with gr.Column(scale=1):
126
- image = gr.Image(label="Upload Image", type="pil", height=400)
127
-
128
- # Camera parameter inputs (visible for debugging)
129
- js_azimuth = gr.Textbox("0", visible=True, elem_id="js-azimuth", label="Azimuth")
130
- js_elevation = gr.Textbox("0", visible=True, elem_id="js-elevation", label="Elevation")
131
- js_distance = gr.Textbox("1.0", visible=True, elem_id="js-distance", label="Distance")
132
-
133
- # Generation settings
134
- with gr.Accordion("βš™οΈ Generation Settings", open=False):
135
- seed = gr.Slider(minimum=0, maximum=MAX_SEED, step=1, value=42, label="Seed")
136
- randomize_seed = gr.Checkbox(True, label="Randomize seed")
137
- guidance_scale = gr.Slider(minimum=1, maximum=20, step=0.1, value=7.5, label="Guidance scale")
138
- num_inference_steps = gr.Slider(minimum=1, maximum=50, step=1, value=4, label="Number of inference steps")
139
-
140
- def update_dimensions_on_upload(input_image):
141
- if input_image is None:
142
- return 1024, 1024
143
-
144
- original_width, original_height = input_image.size
145
- aspect_ratio = original_width / original_height
146
-
147
- if aspect_ratio > 1:
148
- # Landscape
149
- new_width = 1024
150
- new_height = round(1024 / aspect_ratio / 32) * 32
151
- else:
152
- # Portrait or square
153
- new_height = 1024
154
- new_width = round(1024 * aspect_ratio / 32) * 32
155
-
156
- # Ensure minimum size
157
- new_width = max(256, min(1024, new_width))
158
- new_height = max(256, min(1024, new_height))
159
-
160
- return new_width, new_height
161
-
162
- height = gr.Slider(minimum=256, maximum=1024, step=32, value=1024, label="Height")
163
- width = gr.Slider(minimum=256, maximum=1024, step=32, value=1024, label="Width")
164
-
165
- prompt_display = gr.Textbox(
166
- label="Current Camera Prompt",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  value="<sks> front view eye-level shot medium shot",
168
- interactive=False
 
 
169
  )
170
-
171
- # Right column: Interactive image view
172
- with gr.Column(scale=1):
173
- gr.Markdown("### 🎯 Interactive Image View")
174
- gr.Markdown("*Upload an image, then hover to see controls and click arrows to generate new views*")
175
-
176
- # Interactive HTML component using working pattern
177
- result_display = gr.HTML(
178
- value="""
179
- <div style="width: 100%; height: 500px; background: #f8f8f8; border: 2px solid #e0e0e0; border-radius: 12px;
180
- position: relative; display: flex; align-items: center; justify-content: center;">
181
- <div style="text-align: center; color: #999;">
182
- <div style="font-size: 48px; margin-bottom: 10px;">πŸ“Έ</div>
183
- <p>Upload an image on the left to begin</p>
184
- <p>Then hover here to see camera controls</p>
185
- </div>
186
- </div>
187
- """,
188
- elem_id="result-display"
 
189
  )
190
-
191
- # Debug output
192
- debug_output = gr.Textbox(label="Debug Output", visible=True)
193
-
194
- # Functions for handling interactions (inside Blocks context)
195
- def show_uploaded_image_with_arrows(uploaded_image):
196
- """Show uploaded image with working arrow controls."""
197
- if uploaded_image is None:
198
- return gr.update(value="""
199
- <div style="width: 100%; height: 500px; background: #f8f8f8; border: 2px solid #e0e0e0; border-radius: 12px;
200
- position: relative; display: flex; align-items: center; justify-content: center;">
201
- <div style="text-align: center; color: #999;">
202
- <div style="font-size: 48px; margin-bottom: 10px;">πŸ“Έ</div>
203
- <p>Upload an image on the left to begin</p>
204
- <p>Then hover here to see camera controls</p>
205
- </div>
206
- </div>
207
- """)
208
-
209
- # Convert to data URL
210
- buffered = BytesIO()
211
- uploaded_image.save(buffered, format="PNG")
212
- img_str = base64.b64encode(buffered.getvalue()).decode()
213
- data_url = f"data:image/png;base64,{img_str}"
214
-
215
- print(f"DEBUG: Converting image to data URL. Image size: {uploaded_image.size}, Data URL length: {len(data_url)}")
216
- print(f"DEBUG: Data URL starts with: {data_url[:100]}...")
217
-
218
- # Add timestamp to prevent caching
219
- import time
220
- timestamp = int(time.time() * 1000) # milliseconds
221
- print(f"DEBUG: Updating HTML with timestamp {timestamp}")
222
-
223
- return gr.update(value=f"""
224
- <div style="width: 100%; height: 500px; background: #f8f8f8; border: 2px solid #e0e0e0; border-radius: 12px;
225
- position: relative; display: flex; align-items: center; justify-content: center;"
226
- onmouseenter="this.querySelector('#arrow-controls').style.opacity='1'"
227
- onmouseleave="this.querySelector('#arrow-controls').style.opacity='0'">
228
-
229
- <!-- Image with timestamp to prevent caching -->
230
- <img src="{data_url}" style="max-width: 100%; max-height: 100%; object-fit: contain;" data-timestamp="{timestamp}">
231
-
232
- <!-- Arrow controls -->
233
- <div id="arrow-controls" style="position: absolute; inset: 0; opacity: 0; transition: opacity 0.3s ease; z-index: 10;">
234
-
235
- <!-- Left Arrow -->
236
- <button onclick="
237
- console.log('Left arrow clicked');
238
- var azInputElement = document.getElementById('js-azimuth');
239
- console.log('azInputElement:', azInputElement);
240
- if (!azInputElement) {{ console.error('js-azimuth element not found'); return; }}
241
-
242
- // Try multiple selectors for Gradio textbox input
243
- var azInput = azInputElement.querySelector('input') ||
244
- azInputElement.querySelector('textarea') ||
245
- azInputElement.querySelector('[contenteditable]') ||
246
- azInputElement.querySelector('.gr-textbox input') ||
247
- azInputElement.querySelector('input[type=text]');
248
-
249
- console.log('azInput:', azInput);
250
- console.log('All inputs in element:', azInputElement.querySelectorAll('input, textarea'));
251
-
252
- if (!azInput) {{
253
- console.error('No input found. Element HTML:', azInputElement.innerHTML);
254
- console.error('Trying to find any input in the container...');
255
- var allInputs = document.querySelectorAll('#js-azimuth input, #js-azimuth textarea');
256
- console.log('All matching inputs:', allInputs);
257
- if (allInputs.length > 0) azInput = allInputs[0];
258
- }}
259
-
260
- if (!azInput) {{ console.error('Still no input found'); return; }}
261
-
262
- var currentAz = parseInt(azInput.value) || 0;
263
- var newAz = (currentAz - 45 + 360) % 360;
264
- console.log('Setting azimuth from', currentAz, 'to', newAz);
265
- azInput.value = newAz;
266
- azInput.dispatchEvent(new Event('input', {{bubbles: true}}));
267
- azInput.dispatchEvent(new Event('change', {{bubbles: true}}));
268
- var statusAz = document.getElementById('status-az');
269
- if (statusAz) statusAz.textContent = newAz;
270
- "
271
- style="position: absolute; left: 20px; top: 50%; transform: translateY(-50%);
272
- width: 60px; height: 60px; background: rgba(0,255,136,0.9); border: none;
273
- border-radius: 50%; color: white; font-size: 24px; cursor: pointer;
274
- box-shadow: 0 4px 12px rgba(0,0,0,0.3); transition: transform 0.2s;"
275
- onmouseover="this.style.transform += ' scale(1.1)'"
276
- onmouseout="this.style.transform = this.style.transform.replace(' scale(1.1)', '')"
277
- title="Rotate Left">
278
- ←
279
- </button>
280
-
281
- <!-- Right Arrow -->
282
- <button onclick="
283
- console.log('Right arrow clicked');
284
- var azInputElement = document.getElementById('js-azimuth');
285
- if (!azInputElement) {{ console.error('js-azimuth element not found'); return; }}
286
- var azInput = azInputElement.querySelector('input') || azInputElement.querySelector('textarea');
287
- if (!azInput) {{ console.error('input within js-azimuth not found'); return; }}
288
- var currentAz = parseInt(azInput.value) || 0;
289
- var newAz = (currentAz + 45) % 360;
290
- console.log('Setting azimuth from', currentAz, 'to', newAz);
291
- azInput.value = newAz;
292
- azInput.dispatchEvent(new Event('input', {{bubbles: true}}));
293
- azInput.dispatchEvent(new Event('change', {{bubbles: true}}));
294
- var statusAz = document.getElementById('status-az');
295
- if (statusAz) statusAz.textContent = newAz;
296
- "
297
- style="position: absolute; right: 20px; top: 50%; transform: translateY(-50%);
298
- width: 60px; height: 60px; background: rgba(0,255,136,0.9); border: none;
299
- border-radius: 50%; color: white; font-size: 24px; cursor: pointer;
300
- box-shadow: 0 4px 12px rgba(0,0,0,0.3); transition: transform 0.2s;"
301
- onmouseover="this.style.transform += ' scale(1.1)'"
302
- onmouseout="this.style.transform = this.style.transform.replace(' scale(1.1)', '')"
303
- title="Rotate Right">
304
- β†’
305
- </button>
306
-
307
- <!-- Up Arrow -->
308
- <button onclick="
309
- console.log('Up arrow clicked');
310
- var elInputElement = document.getElementById('js-elevation');
311
- if (!elInputElement) {{ console.error('js-elevation element not found'); return; }}
312
- var elInput = elInputElement.querySelector('input') || elInputElement.querySelector('textarea');
313
- if (!elInput) {{ console.error('input within js-elevation not found'); return; }}
314
- var currentEl = parseInt(elInput.value) || 0;
315
- var newEl = Math.min(60, currentEl + 30);
316
- console.log('Setting elevation from', currentEl, 'to', newEl);
317
- elInput.value = newEl;
318
- elInput.dispatchEvent(new Event('input', {{bubbles: true}}));
319
- elInput.dispatchEvent(new Event('change', {{bubbles: true}}));
320
- var statusEl = document.getElementById('status-el');
321
- if (statusEl) statusEl.textContent = newEl;
322
- "
323
- style="position: absolute; top: 20px; left: 50%; transform: translateX(-50%);
324
- width: 60px; height: 60px; background: rgba(255,105,180,0.9); border: none;
325
- border-radius: 50%; color: white; font-size: 24px; cursor: pointer;
326
- box-shadow: 0 4px 12px rgba(0,0,0,0.3); transition: transform 0.2s;"
327
- onmouseover="this.style.transform += ' scale(1.1)'"
328
- onmouseout="this.style.transform = this.style.transform.replace(' scale(1.1)', '')"
329
- title="Look Up">
330
- ↑
331
- </button>
332
-
333
- <!-- Down Arrow -->
334
- <button onclick="
335
- console.log('Down arrow clicked');
336
- var elInputElement = document.getElementById('js-elevation');
337
- if (!elInputElement) {{ console.error('js-elevation element not found'); return; }}
338
- var elInput = elInputElement.querySelector('input') || elInputElement.querySelector('textarea');
339
- if (!elInput) {{ console.error('input within js-elevation not found'); return; }}
340
- var currentEl = parseInt(elInput.value) || 0;
341
- var newEl = Math.max(-30, currentEl - 30);
342
- console.log('Setting elevation from', currentEl, 'to', newEl);
343
- elInput.value = newEl;
344
- elInput.dispatchEvent(new Event('input', {{bubbles: true}}));
345
- elInput.dispatchEvent(new Event('change', {{bubbles: true}}));
346
- var statusEl = document.getElementById('status-el');
347
- if (statusEl) statusEl.textContent = newEl;
348
- "
349
- style="position: absolute; bottom: 80px; left: 50%; transform: translateX(-50%);
350
- width: 60px; height: 60px; background: rgba(255,105,180,0.9); border: none;
351
- border-radius: 50%; color: white; font-size: 24px; cursor: pointer;
352
- box-shadow: 0 4px 12px rgba(0,0,0,0.3); transition: transform 0.2s;"
353
- onmouseover="this.style.transform += ' scale(1.1)'"
354
- onmouseout="this.style.transform = this.style.transform.replace(' scale(1.1)', '')"
355
- title="Look Down">
356
- ↓
357
- </button>
358
-
359
- <!-- Zoom Controls -->
360
- <div style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);
361
- display: flex; gap: 15px;">
362
-
363
- <button onclick="
364
- console.log('Zoom out clicked');
365
- var distInputElement = document.getElementById('js-distance');
366
- if (!distInputElement) {{ console.error('js-distance element not found'); return; }}
367
- var distInput = distInputElement.querySelector('input') || distInputElement.querySelector('textarea');
368
- if (!distInput) {{ console.error('input within js-distance not found'); return; }}
369
- var currentDist = parseFloat(distInput.value) || 1.0;
370
- var newDist = Math.min(1.8, currentDist + 0.4);
371
- console.log('Setting distance from', currentDist, 'to', newDist);
372
- distInput.value = newDist.toFixed(1);
373
- distInput.dispatchEvent(new Event('input', {{bubbles: true}}));
374
- distInput.dispatchEvent(new Event('change', {{bubbles: true}}));
375
- var statusDist = document.getElementById('status-dist');
376
- if (statusDist) statusDist.textContent = newDist.toFixed(1);
377
- "
378
- style="width: 55px; height: 55px; background: rgba(255,165,0,0.9); border: none;
379
- border-radius: 50%; color: white; font-size: 24px; cursor: pointer;
380
- box-shadow: 0 4px 12px rgba(0,0,0,0.3); transition: transform 0.2s;"
381
- onmouseover="this.style.transform = 'scale(1.1)'"
382
- onmouseout="this.style.transform = ''"
383
- title="Zoom Out">
384
- βˆ’
385
- </button>
386
-
387
- <button onclick="
388
- console.log('Zoom in clicked');
389
- var distInputElement = document.getElementById('js-distance');
390
- if (!distInputElement) {{ console.error('js-distance element not found'); return; }}
391
- var distInput = distInputElement.querySelector('input') || distInputElement.querySelector('textarea');
392
- if (!distInput) {{ console.error('input within js-distance not found'); return; }}
393
- var currentDist = parseFloat(distInput.value) || 1.0;
394
- var newDist = Math.max(0.6, currentDist - 0.4);
395
- console.log('Setting distance from', currentDist, 'to', newDist);
396
- distInput.value = newDist.toFixed(1);
397
- distInput.dispatchEvent(new Event('input', {{bubbles: true}}));
398
- distInput.dispatchEvent(new Event('change', {{bubbles: true}}));
399
- var statusDist = document.getElementById('status-dist');
400
- if (statusDist) statusDist.textContent = newDist.toFixed(1);
401
- "
402
- style="width: 55px; height: 55px; background: rgba(255,165,0,0.9); border: none;
403
- border-radius: 50%; color: white; font-size: 24px; cursor: pointer;
404
- box-shadow: 0 4px 12px rgba(0,0,0,0.3); transition: transform 0.2s;"
405
- onmouseover="this.style.transform = 'scale(1.1)'"
406
- onmouseout="this.style.transform = ''"
407
- title="Zoom In">
408
- +
409
- </button>
410
- </div>
411
-
412
- <!-- Status Display -->
413
- <div style="position: absolute; top: 15px; right: 15px; background: rgba(0,0,0,0.85);
414
- color: white; padding: 10px 14px; border-radius: 8px; font-family: monospace;
415
- font-size: 13px; box-shadow: 0 4px 12px rgba(0,0,0,0.4);">
416
- <div>Az: <span id="status-az">0</span>Β° | El: <span id="status-el">0</span>Β° | Dist: <span id="status-dist">1.0</span></div>
417
- </div>
418
- </div>
419
- </div>
420
- """)
421
-
422
- def handle_parameter_change(az, el, dist, input_image, seed_val, randomize_seed_val, guidance_val, steps_val, h_val, w_val):
423
- """Handle camera parameter changes and generate new view."""
424
- try:
425
- azimuth = float(az)
426
- elevation = float(el)
427
- distance = float(dist)
428
-
429
- # Build prompt
430
- prompt = build_camera_prompt(azimuth, elevation, distance)
431
-
432
- if input_image is not None:
433
- # Generate new image using the actual Qwen model
434
- generated_image, final_seed, final_prompt = infer_camera_edit(
435
- image=input_image,
436
- azimuth=azimuth,
437
- elevation=elevation,
438
- distance=distance,
439
- seed=seed_val,
440
- randomize_seed=randomize_seed_val,
441
- guidance_scale=guidance_val,
442
- num_inference_steps=steps_val,
443
- height=int(h_val),
444
- width=int(w_val)
445
- )
446
-
447
- # Update the HTML display with the generated image
448
- updated_html = show_uploaded_image_with_arrows(generated_image)
449
- return updated_html, prompt, f"Generated view: Az={azimuth}Β°, El={elevation}Β°, Dist={distance}, Seed={final_seed}"
450
-
451
- return gr.update(), prompt, f"Parameters updated: Az={azimuth}Β°, El={elevation}Β°, Dist={distance}"
452
-
453
- except Exception as e:
454
- return gr.update(), f"Error: {str(e)}", f"Error processing parameters: {str(e)}"
455
-
456
- # Update dimensions when image is uploaded
457
- image.upload(
458
- fn=update_dimensions_on_upload,
459
- inputs=[image],
460
- outputs=[width, height]
461
- )
462
-
463
- # Image upload handler
464
- image.upload(
465
- fn=show_uploaded_image_with_arrows,
466
- inputs=[image],
467
- outputs=[result_display]
468
- )
469
-
470
- # Parameter change handlers (triggered by arrow clicks)
471
- js_azimuth.change(
472
- fn=handle_parameter_change,
473
- inputs=[js_azimuth, js_elevation, js_distance, image, seed, randomize_seed, guidance_scale, num_inference_steps, height, width],
474
- outputs=[result_display, prompt_display, debug_output]
475
  )
476
-
477
- js_elevation.change(
478
- fn=handle_parameter_change,
479
- inputs=[js_azimuth, js_elevation, js_distance, image, seed, randomize_seed, guidance_scale, num_inference_steps, height, width],
480
- outputs=[result_display, prompt_display, debug_output]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
481
  )
482
-
483
- js_distance.change(
484
- fn=handle_parameter_change,
485
- inputs=[js_azimuth, js_elevation, js_distance, image, seed, randomize_seed, guidance_scale, num_inference_steps, height, width],
486
- outputs=[result_display, prompt_display, debug_output]
 
 
 
 
 
487
  )
488
-
489
  return demo
490
 
 
491
  if __name__ == "__main__":
492
- demo = create_camera_control_app()
493
- demo.launch()
 
 
 
 
 
 
1
+ # third
2
+
3
+ """
4
+ 3D Camera View Generator
5
+ - Qwen Image Edit + Lightning LoRA + Multi-Angle LoRA
6
+ - gr.HTML custom component (Gradio 6)
7
+ - ZeroGPU (HuggingFace Spaces)
8
+
9
+ Fixes vs previous version
10
+ ──────────────────────────
11
+ 1. Removed CameraViewComponent subclass entirely.
12
+ Gradio calls inspect.getfile() on subclasses during registration; when the
13
+ code runs in a Jupyter / IPython cell there is no source file, so it raises
14
+ OSError: source code not available. Plain gr.HTML with a dict value avoids
15
+ this path completely β€” Gradio 6 accepts Any as value.
16
+
17
+ 2. Moved `theme` and `css` from gr.Blocks() to demo.launch() as required by
18
+ Gradio 6.0 (the Blocks constructor no longer accepts those kwargs).
19
+
20
+ 3. Removed `from gradio.data_classes import GradioModel` β€” no longer needed.
21
+ """
22
+
23
  import gradio as gr
24
  import numpy as np
25
  import random
26
  import torch
27
  import base64
28
+ import spaces
29
  from io import BytesIO
30
  from PIL import Image
31
+ from diffusers import QwenImageEditPlusPipeline
32
 
33
  MAX_SEED = np.iinfo(np.int32).max
34
+ dtype = torch.bfloat16
35
+ device = "cuda" if torch.cuda.is_available() else "cpu"
36
 
37
+ # ── Model (lazy-loaded inside @spaces.GPU) ─────────────────────────────────────
38
+ #
39
+ # HOW MODEL LOADING WORKS ON ZEROGPU
40
+ # ────────────────────────────────────
41
+ # β€’ Weights are downloaded to the HF cache on disk the first time
42
+ # from_pretrained() is called (happens inside the @spaces.GPU window).
43
+ # β€’ They are NOT loaded into GPU VRAM at app startup β€” only when the first
44
+ # @spaces.GPU-decorated function actually runs.
45
+ # β€’ After the first call `pipe` stays alive in CPU process memory, so
46
+ # subsequent requests skip the download and just run inference.
47
+ # β€’ ZeroGPU allocates an H200 for the duration of the decorated function
48
+ # then releases it, so nothing holds the GPU between user requests.
49
+ #
50
  pipe = None
51
 
52
  def load_model():
 
53
  global pipe
54
  if pipe is None:
55
  pipe = QwenImageEditPlusPipeline.from_pretrained(
56
  "Qwen/Qwen-Image-Edit-2511",
57
+ torch_dtype=dtype,
58
  ).to(device)
59
 
 
60
  pipe.load_lora_weights(
61
  "lightx2v/Qwen-Image-Edit-2511-Lightning",
62
  weight_name="Qwen-Image-Edit-2511-Lightning-4steps-V1.0-bf16.safetensors",
63
+ adapter_name="lightning",
64
  )
 
 
65
  pipe.load_lora_weights(
66
  "fal/Qwen-Image-Edit-2511-Multiple-Angles-LoRA",
67
  weight_name="qwen-image-edit-2511-multiple-angles-lora.safetensors",
68
+ adapter_name="angles",
69
  )
 
70
  pipe.set_adapters(["lightning", "angles"], adapter_weights=[1.0, 1.0])
71
  return pipe
72
 
73
+
74
+ # ── Camera parameter tables ────────────────────────────────────────────────────
75
  AZIMUTH_MAP = {
76
  0: "front view",
77
+ 45: "front-right quarter view",
78
  90: "right side view",
79
  135: "back-right quarter view",
80
  180: "back view",
81
  225: "back-left quarter view",
82
+ 270: "left side view",
83
+ 315: "front-left quarter view",
84
  }
 
85
  ELEVATION_MAP = {
86
  -30: "low-angle shot",
87
+ 0: "eye-level shot",
88
  30: "elevated shot",
89
+ 60: "high-angle shot",
90
  }
 
91
  DISTANCE_MAP = {
92
  0.6: "close-up",
93
  1.0: "medium shot",
94
+ 1.8: "wide shot",
95
  }
96
 
97
+ # Default viewer state β€” plain dict, no custom class needed
98
+ DEFAULT_CAM_VALUE = {"img": "", "az": 0.0, "el": 0.0, "dist": 1.0}
99
+
100
+
101
  def snap_to_nearest(value, steps):
 
102
  return min(steps, key=lambda x: abs(x - value))
103
 
104
+
105
  def build_camera_prompt(azimuth, elevation, distance):
106
+ az = snap_to_nearest(azimuth, list(AZIMUTH_MAP.keys()))
107
+ el = snap_to_nearest(elevation, list(ELEVATION_MAP.keys()))
108
+ dist = snap_to_nearest(distance, list(DISTANCE_MAP.keys()))
109
+ return f"<sks> {AZIMUTH_MAP[az]} {ELEVATION_MAP[el]} {DISTANCE_MAP[dist]}"
110
+
111
+
112
+ def pil_to_data_url(img: Image.Image) -> str:
113
+ buf = BytesIO()
114
+ fmt = getattr(img, "format", None)
115
+ if fmt and fmt.upper() == "WEBP":
116
+ img.save(buf, format="WEBP")
117
+ mime = "image/webp"
118
+ else:
119
+ img.save(buf, format="PNG")
120
+ mime = "image/png"
121
+ b64 = base64.b64encode(buf.getvalue()).decode()
122
+ return f"data:{mime};base64,{b64}"
123
+
124
+
125
+ # ── Inference ──────────────────────────────────────────────────────────────────
126
+ @spaces.GPU(duration=120)
127
+ def infer_camera_edit(
128
+ image, azimuth, elevation, distance,
129
+ seed, randomize_seed, guidance_scale,
130
+ num_inference_steps, height, width,
131
+ ):
132
  if randomize_seed:
133
  seed = random.randint(0, MAX_SEED)
134
+
135
  generator = torch.Generator(device=device).manual_seed(seed)
136
+ prompt = build_camera_prompt(azimuth, elevation, distance)
137
+ model = load_model()
138
+
 
 
 
 
 
139
  result = model(
140
  image=image,
141
  prompt=prompt,
 
143
  width=width,
144
  guidance_scale=guidance_scale,
145
  num_inference_steps=num_inference_steps,
146
+ generator=generator,
147
  ).images[0]
148
+
149
  return result, seed, prompt
150
 
151
+
152
+ # ── gr.HTML templates ──────────────────────────────────────────────────────────
153
+ # Using plain gr.HTML (no subclass) with a dict value.
154
+ #
155
+ # Gradio 6 passes the dict as `value` to the template; all keys (img, az, el,
156
+ # dist) are accessible as value.img, value.az, etc. in both ${} and {{}} syntax.
157
+ #
158
+ # BUG FIX: multi-line ${} β†’ Handlebars {{#if}} for the img/empty conditional.
159
+ # BUG FIX: onmouseenter/onmouseleave removed from markup; hover via CSS :hover.
160
+
161
+ HTML_TEMPLATE = """
162
+ <div class="cv-wrap">
163
+ {{#if value.img}}
164
+ <img class="cv-img" src="{{value.img}}">
165
+ <div class="cv-scanline"></div>
166
+ {{else}}
167
+ <div class="cv-empty">
168
+ <div class="cv-reticle"><div class="cv-reticle-inner"></div></div>
169
+ <p class="cv-empty-title">No image loaded</p>
170
+ <p class="cv-empty-sub">Upload an image on the left, then hover here to orbit</p>
171
+ </div>
172
+ {{/if}}
173
+
174
+ <div class="cv-hud">
175
+ <div class="cv-readout">
176
+ <span class="cv-lbl">AZ</span><span class="cv-val">${value.az}&deg;</span>
177
+ <span class="cv-sep">&middot;</span>
178
+ <span class="cv-lbl">EL</span><span class="cv-val">${value.el}&deg;</span>
179
+ <span class="cv-sep">&middot;</span>
180
+ <span class="cv-lbl">DIST</span><span class="cv-val">${value.dist}&times;</span>
181
+ </div>
182
+ <div class="cv-controls">
183
+ <div class="cv-dpad">
184
+ <button class="cv-btn cv-up" data-action="el-plus" title="Elevate">&#9650;</button>
185
+ <button class="cv-btn cv-left" data-action="az-minus" title="Rotate Left">&#9664;</button>
186
+ <div class="cv-dot"></div>
187
+ <button class="cv-btn cv-right" data-action="az-plus" title="Rotate Right">&#9654;</button>
188
+ <button class="cv-btn cv-down" data-action="el-minus" title="Lower">&#9660;</button>
189
+ </div>
190
+ <div class="cv-zoom">
191
+ <button class="cv-zbtn" data-action="dist-minus" title="Zoom In">&#xFF0B;</button>
192
+ <button class="cv-zbtn" data-action="dist-plus" title="Zoom Out">&#xFF0D;</button>
193
+ </div>
194
+ </div>
195
+ </div>
196
+ </div>
197
+ """
198
+
199
+ CSS_TEMPLATE = """
200
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
201
+
202
+ .cv-wrap {
203
+ position: relative;
204
+ width: 100%; height: 540px;
205
+ background: #08080f;
206
+ border: 1px solid rgba(34,211,238,0.15);
207
+ border-radius: 18px;
208
+ overflow: hidden;
209
+ display: flex; align-items: center; justify-content: center;
210
+ font-family: 'IBM Plex Mono', 'Courier New', monospace;
211
+ }
212
+
213
+ .cv-img {
214
+ max-width: 100%; max-height: 100%;
215
+ object-fit: contain; border-radius: 4px; display: block;
216
+ }
217
+
218
+ .cv-scanline {
219
+ position: absolute; inset: 0;
220
+ background: repeating-linear-gradient(
221
+ to bottom,
222
+ transparent 0px, transparent 3px,
223
+ rgba(0,0,0,0.05) 3px, rgba(0,0,0,0.05) 4px
224
+ );
225
+ pointer-events: none; border-radius: inherit;
226
+ }
227
+
228
+ .cv-empty {
229
+ text-align: center; user-select: none;
230
+ display: flex; flex-direction: column; align-items: center; gap: 10px;
231
+ }
232
+ .cv-reticle {
233
+ width: 72px; height: 72px;
234
+ border: 2px solid rgba(34,211,238,0.3); border-radius: 50%;
235
+ display: flex; align-items: center; justify-content: center;
236
+ position: relative; margin-bottom: 4px;
237
+ }
238
+ .cv-reticle::before, .cv-reticle::after {
239
+ content: ''; position: absolute; background: rgba(34,211,238,0.25);
240
+ }
241
+ .cv-reticle::before { width: 1px; height: 100%; }
242
+ .cv-reticle::after { width: 100%; height: 1px; }
243
+ .cv-reticle-inner {
244
+ width: 12px; height: 12px; border-radius: 50%;
245
+ background: rgba(34,211,238,0.6); z-index: 1;
246
+ }
247
+ .cv-empty-title {
248
+ font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase;
249
+ color: rgba(255,255,255,0.45);
250
+ }
251
+ .cv-empty-sub {
252
+ font-size: 11px; color: rgba(255,255,255,0.2);
253
+ max-width: 240px; line-height: 1.6;
254
+ }
255
+
256
+ /* HUD: hidden by default, shown on CSS :hover β€” survives template re-renders */
257
+ .cv-hud {
258
+ position: absolute; bottom: 16px; right: 16px;
259
+ display: flex; flex-direction: column; align-items: flex-end; gap: 8px;
260
+ opacity: 0; transition: opacity 0.2s ease; pointer-events: auto;
261
+ }
262
+ .cv-wrap:hover .cv-hud { opacity: 1; }
263
+
264
+ .cv-readout {
265
+ display: flex; align-items: center; gap: 6px;
266
+ background: rgba(5,5,15,0.88); border: 1px solid rgba(34,211,238,0.3);
267
+ border-radius: 8px; padding: 5px 14px;
268
+ font-size: 11px; letter-spacing: 0.08em; white-space: nowrap;
269
+ backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
270
+ }
271
+ .cv-lbl { color: rgba(34,211,238,0.5); font-size: 9px; text-transform: uppercase; }
272
+ .cv-val { color: #22d3ee; font-weight: 600; }
273
+ .cv-sep { color: rgba(255,255,255,0.15); }
274
+
275
+ .cv-controls {
276
+ display: flex; align-items: center; gap: 10px;
277
+ background: rgba(5,5,15,0.82); border: 1px solid rgba(255,255,255,0.07);
278
+ border-radius: 14px; padding: 10px 12px;
279
+ backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
280
+ }
281
+
282
+ .cv-dpad {
283
+ display: grid;
284
+ grid-template-columns: repeat(3, 36px);
285
+ grid-template-rows: repeat(3, 36px);
286
+ gap: 3px;
287
+ }
288
+ .cv-btn {
289
+ width: 36px; height: 36px;
290
+ border: 1px solid rgba(255,255,255,0.08); border-radius: 8px;
291
+ background: rgba(255,255,255,0.05); color: rgba(255,255,255,0.65);
292
+ font-size: 11px; cursor: pointer;
293
+ display: flex; align-items: center; justify-content: center;
294
+ transition: background .12s, border-color .12s, transform .1s, color .12s;
295
+ padding: 0; line-height: 1;
296
+ }
297
+ .cv-btn:hover {
298
+ background: rgba(34,211,238,0.2); border-color: rgba(34,211,238,0.5);
299
+ color: #22d3ee; transform: scale(1.12);
300
+ }
301
+ .cv-btn:active { transform: scale(0.9); }
302
+
303
+ .cv-up { grid-column:2; grid-row:1; }
304
+ .cv-left { grid-column:1; grid-row:2; }
305
+ .cv-dot {
306
+ grid-column:2; grid-row:2; width:36px; height:36px; border-radius:50%;
307
+ background: rgba(34,211,238,0.07); border: 1px solid rgba(34,211,238,0.12);
308
+ }
309
+ .cv-right { grid-column:3; grid-row:2; }
310
+ .cv-down { grid-column:2; grid-row:3; }
311
+
312
+ .cv-zoom { display: flex; flex-direction: column; gap: 4px; }
313
+ .cv-zbtn {
314
+ width: 36px; height: 42px;
315
+ border: 1px solid rgba(255,255,255,0.08); border-radius: 8px;
316
+ background: rgba(255,255,255,0.05); color: rgba(255,255,255,0.65);
317
+ font-size: 16px; font-weight: 500; cursor: pointer;
318
+ display: flex; align-items: center; justify-content: center;
319
+ transition: background .12s, border-color .12s, transform .1s, color .12s;
320
+ padding: 0; line-height: 1;
321
+ }
322
+ .cv-zbtn:hover {
323
+ background: rgba(251,191,36,0.2); border-color: rgba(251,191,36,0.5);
324
+ color: #fbbf24; transform: scale(1.12);
325
+ }
326
+ .cv-zbtn:active { transform: scale(0.9); }
327
+ """
328
+
329
+ # BUG FIX: distance uses shiftDist() to jump between the exact snap points
330
+ # [0.6, 1.0, 1.8] instead of a fixed Β±0.4 offset.
331
+ JS_ON_LOAD = """
332
+ const DIST_STEPS = [0.6, 1.0, 1.8];
333
+
334
+ function snapDist(d) {
335
+ return DIST_STEPS.reduce((p, c) => Math.abs(c - d) < Math.abs(p - d) ? c : p);
336
+ }
337
+ function shiftDist(d, dir) {
338
+ const idx = DIST_STEPS.indexOf(snapDist(Number(d)));
339
+ return DIST_STEPS[Math.max(0, Math.min(DIST_STEPS.length - 1, idx + dir))];
340
+ }
341
+
342
+ // Delegated click listener β€” attached once, survives template re-renders.
343
+ element.addEventListener('click', function(e) {
344
+ const btn = e.target.closest('[data-action]');
345
+ if (!btn) return;
346
+
347
+ const v = Object.assign({}, props.value);
348
+ let az = Number(v.az) || 0;
349
+ let el = Number(v.el) || 0;
350
+ let dist = Number(v.dist) || 1.0;
351
+
352
+ switch (btn.dataset.action) {
353
+ case 'az-minus': az = (az - 45 + 360) % 360; break;
354
+ case 'az-plus': az = (az + 45) % 360; break;
355
+ case 'el-plus': el = Math.min(60, el + 30); break;
356
+ case 'el-minus': el = Math.max(-30, el - 30); break;
357
+ case 'dist-minus': dist = shiftDist(dist, -1); break;
358
+ case 'dist-plus': dist = shiftDist(dist, +1); break;
359
+ }
360
+
361
+ props.value = { ...v, az, el, dist };
362
+ trigger('submit');
363
+ });
364
+ """
365
+
366
+
367
+ # ── Global Gradio CSS ──────────────────────────────────────────────────────────
368
+ GLOBAL_CSS = """
369
+ @import url('https://fonts.googleapis.com/css2?family=Oxanium:wght@300;400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap');
370
+
371
+ body,
372
+ .gradio-container,
373
+ .gradio-container > .main,
374
+ footer { background: #06060d !important; }
375
+
376
+ .gradio-container {
377
+ font-family: 'Oxanium', sans-serif !important;
378
+ max-width: 1120px !important;
379
+ margin: 0 auto !important;
380
+ padding: 0 20px 40px !important;
381
+ }
382
+
383
+ .app-heading {
384
+ text-align: center;
385
+ padding: 36px 0 16px;
386
+ }
387
+ .app-heading h1 {
388
+ font-family: 'Oxanium', sans-serif;
389
+ font-size: clamp(28px, 4vw, 44px);
390
+ font-weight: 700;
391
+ letter-spacing: -0.025em;
392
+ background: linear-gradient(125deg, #22d3ee 0%, #818cf8 55%, #c084fc 100%);
393
+ -webkit-background-clip: text;
394
+ -webkit-text-fill-color: transparent;
395
+ background-clip: text;
396
+ line-height: 1.1;
397
+ margin: 0 0 10px;
398
+ }
399
+ .app-heading p {
400
+ font-family: 'IBM Plex Mono', monospace;
401
+ font-size: 11px;
402
+ color: rgba(255,255,255,0.28);
403
+ letter-spacing: 0.14em;
404
+ text-transform: uppercase;
405
+ }
406
+
407
+ .gradio-container .block,
408
+ .gradio-container .form {
409
+ background: rgba(255,255,255,0.025) !important;
410
+ border: 1px solid rgba(255,255,255,0.06) !important;
411
+ border-radius: 14px !important;
412
+ box-shadow: none !important;
413
+ }
414
+
415
+ label > span,
416
+ .label-wrap span {
417
+ font-family: 'IBM Plex Mono', monospace !important;
418
+ font-size: 10px !important;
419
+ text-transform: uppercase !important;
420
+ letter-spacing: 0.1em !important;
421
+ color: rgba(255,255,255,0.32) !important;
422
+ }
423
+
424
+ textarea,
425
+ input[type=text],
426
+ input[type=number] {
427
+ background: rgba(255,255,255,0.04) !important;
428
+ border: 1px solid rgba(255,255,255,0.08) !important;
429
+ color: rgba(255,255,255,0.8) !important;
430
+ border-radius: 8px !important;
431
+ font-family: 'IBM Plex Mono', monospace !important;
432
+ font-size: 11px !important;
433
+ }
434
+ textarea:focus, input:focus {
435
+ border-color: rgba(34,211,238,0.4) !important;
436
+ box-shadow: 0 0 0 2px rgba(34,211,238,0.06) !important;
437
+ }
438
+
439
+ input[type=range] { accent-color: #22d3ee !important; }
440
+
441
+ .accordion > button,
442
+ details > summary {
443
+ background: rgba(255,255,255,0.03) !important;
444
+ border-radius: 8px !important;
445
+ color: rgba(255,255,255,0.5) !important;
446
+ font-family: 'IBM Plex Mono', monospace !important;
447
+ font-size: 11px !important;
448
+ letter-spacing: 0.06em !important;
449
+ }
450
+
451
+ input[type=checkbox] { accent-color: #22d3ee; }
452
+
453
+ .gradio-container h3 {
454
+ font-family: 'Oxanium', sans-serif;
455
+ font-size: 12px; font-weight: 600;
456
+ letter-spacing: 0.1em; text-transform: uppercase;
457
+ color: rgba(255,255,255,0.35);
458
+ margin-bottom: 6px;
459
+ }
460
+
461
+ .status-box textarea {
462
+ color: rgba(34,211,238,0.8) !important;
463
+ font-size: 11px !important;
464
+ }
465
+
466
+ .section-divider {
467
+ border: none;
468
+ border-top: 1px solid rgba(255,255,255,0.05);
469
+ margin: 8px 0;
470
+ }
471
+
472
+ .gallery-item { border-radius: 8px !important; overflow: hidden; }
473
+ """
474
+
475
+ GRADIO_THEME = gr.themes.Base(
476
+ primary_hue="cyan",
477
+ neutral_hue="slate",
478
+ font=["Oxanium", "sans-serif"],
479
+ )
480
+
481
+
482
+ # ── App ────────────────────────────────────────────────────────────────────────
483
+ def create_app():
484
+
485
+ # FIX: theme and css are now passed to launch(), not gr.Blocks()
486
+ with gr.Blocks(title="3D Camera View Generator") as demo:
487
+
488
+ gr.HTML("""
489
+ <div class="app-heading">
490
+ <h1>3D Camera View Generator</h1>
491
+ <p>Qwen Image Edit &nbsp;&middot;&nbsp; Lightning LoRA &nbsp;&middot;&nbsp; Multi-Angle LoRA</p>
492
+ </div>
493
+ """)
494
+
495
+ with gr.Row(equal_height=False):
496
+
497
+ # ── Left column ──────────────────────────────────────────────────
498
+ with gr.Column(scale=4, min_width=300):
499
+ image_input = gr.Image(
500
+ label="Source Image",
501
+ type="pil",
502
+ height=340,
503
+ )
504
+
505
+ prompt_box = gr.Textbox(
506
+ label="Active Camera Prompt",
507
  value="<sks> front view eye-level shot medium shot",
508
+ interactive=False,
509
+ lines=1,
510
+ elem_classes=["status-box"],
511
  )
512
+
513
+ with gr.Accordion("βš™ Generation Settings", open=False):
514
+ seed_slider = gr.Slider(0, MAX_SEED, value=42, step=1, label="Seed")
515
+ rand_seed_cb = gr.Checkbox(True, label="Randomise seed each generation")
516
+ guidance_sl = gr.Slider(1.0, 20.0, value=7.5, step=0.1, label="Guidance Scale")
517
+ steps_sl = gr.Slider(1, 50, value=4, step=1, label="Inference Steps")
518
+ width_sl = gr.Slider(256, 1024, value=1024, step=32, label="Width (px)")
519
+ height_sl = gr.Slider(256, 1024, value=1024, step=32, label="Height (px)")
520
+
521
+ # ── Right column ─────────────────────────────────────────────────
522
+ with gr.Column(scale=5, min_width=400):
523
+ gr.Markdown("### Camera View β€” hover to reveal orbit controls")
524
+
525
+ # FIX: plain gr.HTML with dict value β€” no subclass, no inspect error
526
+ cam_view = gr.HTML(
527
+ value=DEFAULT_CAM_VALUE,
528
+ html_template=HTML_TEMPLATE,
529
+ css_template=CSS_TEMPLATE,
530
+ js_on_load=JS_ON_LOAD,
531
+ apply_default_css=False,
532
  )
533
+
534
+ status_box = gr.Textbox(
535
+ label="Status",
536
+ value="Ready β€” upload an image to begin",
537
+ interactive=False,
538
+ lines=1,
539
+ elem_classes=["status-box"],
540
+ )
541
+
542
+ gr.HTML('<hr class="section-divider">')
543
+ gr.Markdown("### Generated Views")
544
+
545
+ gallery_state = gr.State([])
546
+ gallery = gr.Gallery(
547
+ label="",
548
+ show_label=False,
549
+ columns=6,
550
+ height=190,
551
+ object_fit="cover",
552
+ allow_preview=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
553
  )
554
+
555
+ # ── Helpers ──────────────────────────────────────────────────────────
556
+
557
+ def _coerce_view(v):
558
+ """Extract (az, el, dist) safely from a dict or default."""
559
+ if isinstance(v, dict):
560
+ return float(v.get("az", 0)), float(v.get("el", 0)), float(v.get("dist", 1.0))
561
+ return 0.0, 0.0, 1.0
562
+
563
+ def _auto_dimensions(img):
564
+ if img is None:
565
+ return 1024, 1024
566
+ w, h = img.size
567
+ ar = w / h
568
+ if ar > 1:
569
+ nw = 1024
570
+ nh = round(1024 / ar / 32) * 32
571
+ else:
572
+ nh = 1024
573
+ nw = round(1024 * ar / 32) * 32
574
+ return max(256, min(1024, nw)), max(256, min(1024, nh))
575
+
576
+ # ── Event handlers ────────────────────────────────────────────────────
577
+
578
+ # BUG FIX: single upload handler (was two concurrent handlers β†’ race condition)
579
+ def on_image_upload(img, current_view):
580
+ nw, nh = _auto_dimensions(img)
581
+ if img is None:
582
+ return DEFAULT_CAM_VALUE.copy(), nw, nh, "No image"
583
+ az, el, dist = _coerce_view(current_view)
584
+ return (
585
+ {"img": pil_to_data_url(img), "az": az, "el": el, "dist": dist},
586
+ nw,
587
+ nh,
588
+ "Image loaded β€” hover the viewer and click an arrow to generate",
589
+ )
590
+
591
+ def on_camera_submit(
592
+ current_view, src_img,
593
+ seed_val, rand_seed, guidance, steps, h, w,
594
+ gallery_imgs,
595
+ ):
596
+ try:
597
+ az, el, dist = _coerce_view(current_view)
598
+ prompt = build_camera_prompt(az, el, dist)
599
+
600
+ if src_img is None:
601
+ return current_view, prompt, "⚠ Upload an image first", gallery_imgs, gallery_imgs
602
+
603
+ gen_img, final_seed, final_prompt = infer_camera_edit(
604
+ image=src_img,
605
+ azimuth=az, elevation=el, distance=dist,
606
+ seed=seed_val, randomize_seed=rand_seed,
607
+ guidance_scale=guidance,
608
+ num_inference_steps=int(steps),
609
+ height=int(h), width=int(w),
610
+ )
611
+
612
+ new_view = {"img": pil_to_data_url(gen_img), "az": az, "el": el, "dist": dist}
613
+ gallery_imgs = list(gallery_imgs) + [gen_img]
614
+ status = f"βœ“ {final_prompt} | seed {final_seed}"
615
+
616
+ return new_view, final_prompt, status, gallery_imgs, gallery_imgs
617
+
618
+ except Exception as exc:
619
+ return current_view, "", f"βœ— {str(exc)}", gallery_imgs, gallery_imgs
620
+
621
+ image_input.upload(
622
+ fn=on_image_upload,
623
+ inputs=[image_input, cam_view],
624
+ outputs=[cam_view, width_sl, height_sl, status_box],
625
  )
626
+
627
+ cam_view.submit(
628
+ fn=on_camera_submit,
629
+ inputs=[
630
+ cam_view, image_input,
631
+ seed_slider, rand_seed_cb, guidance_sl, steps_sl,
632
+ height_sl, width_sl,
633
+ gallery_state,
634
+ ],
635
+ outputs=[cam_view, prompt_box, status_box, gallery_state, gallery],
636
  )
637
+
638
  return demo
639
 
640
+
641
  if __name__ == "__main__":
642
+ demo = create_app()
643
+ # FIX: theme and css passed to launch() as required by Gradio 6.0
644
+ demo.launch(
645
+ debug=True,
646
+ theme=GRADIO_THEME,
647
+ css=GLOBAL_CSS,
648
+ )