Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -194,250 +194,6 @@ def image_to_3d(image, seed, num_inference_steps=30, guidance_scale=7.0, simplif
|
|
194 |
logger.error(f"Error in image_to_3d: {str(e)}\n{traceback.format_exc()}")
|
195 |
raise
|
196 |
|
197 |
-
@spaces.GPU(duration=3)
|
198 |
-
@torch.no_grad()
|
199 |
-
def run_texture(image, mesh_path, seed, req=None):
|
200 |
-
try:
|
201 |
-
log_gpu_memory()
|
202 |
-
height, width = 512, 512
|
203 |
-
cameras = get_orthogonal_camera(
|
204 |
-
elevation_deg=[0, 0, 0, 89.99],
|
205 |
-
distance=[1.8] * NUM_VIEWS,
|
206 |
-
left=-0.55,
|
207 |
-
right=0.55,
|
208 |
-
bottom=-0.55,
|
209 |
-
top=0.55,
|
210 |
-
azimuth_deg=[x - 90 for x in [0, 90, 180, 180]],
|
211 |
-
device=DEVICE,
|
212 |
-
)
|
213 |
-
ctx = NVDiffRastContextWrapper(device=DEVICE, context_type="cuda")
|
214 |
-
mesh = load_mesh(mesh_path, rescale=True, device=DEVICE)
|
215 |
-
with autocast():
|
216 |
-
render_out = render(
|
217 |
-
ctx,
|
218 |
-
mesh,
|
219 |
-
cameras,
|
220 |
-
height=height,
|
221 |
-
width=width,
|
222 |
-
render_attr=False,
|
223 |
-
normal_background=0.0,
|
224 |
-
)
|
225 |
-
control_images = (
|
226 |
-
torch.cat(
|
227 |
-
[(render_out.pos + 0.5).clamp(0, 1), (render_out.normal / 2 + 0.5).clamp(0, 1)],
|
228 |
-
dim=-1,
|
229 |
-
)
|
230 |
-
.permute(0, 3, 1, 2)
|
231 |
-
.to(DEVICE)
|
232 |
-
)
|
233 |
-
del render_out
|
234 |
-
image = Image.open(image)
|
235 |
-
birefnet.to(DEVICE, dtype=DTYPE)
|
236 |
-
with autocast():
|
237 |
-
image = remove_bg_fn(image)
|
238 |
-
birefnet.to("cpu")
|
239 |
-
image = preprocess_image(image, height, width)
|
240 |
-
pipe_kwargs = {"generator": torch.Generator(device=DEVICE).manual_seed(seed)} if seed != -1 else {}
|
241 |
-
mv_adapter_pipe.to(DEVICE, dtype=DTYPE)
|
242 |
-
Tijdens het genereren van de code is er een probleem opgetreden dat de voltooiing heeft onderbroken. De code is incompleet en eindigt abrupt. Hier is de gedeeltelijk gegenereerde code tot aan het punt van onderbreking:
|
243 |
-
|
244 |
-
<xaiArtifact artifact_id="639c400c-2c7c-4b65-a385-eeaa3fdd5602" artifact_version_id="167946b5-d0b3-4e41-92c2-87163e0ff287" title="app.py" contentType="text/python">
|
245 |
-
import spaces
|
246 |
-
import os
|
247 |
-
import gradio as gr
|
248 |
-
import numpy as np
|
249 |
-
import torch
|
250 |
-
from torch.cuda.amp import autocast
|
251 |
-
import trimesh
|
252 |
-
import random
|
253 |
-
from PIL import Image
|
254 |
-
from transformers import AutoModelForImageSegmentation
|
255 |
-
from torchvision import transforms
|
256 |
-
from huggingface_hub import hf_hub_download, snapshot_download
|
257 |
-
import subprocess
|
258 |
-
import shutil
|
259 |
-
import base64
|
260 |
-
import logging
|
261 |
-
import time
|
262 |
-
import traceback
|
263 |
-
import requests
|
264 |
-
|
265 |
-
# Set up logging
|
266 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
267 |
-
logger = logging.getLogger(__name__)
|
268 |
-
|
269 |
-
# Install additional dependencies
|
270 |
-
try:
|
271 |
-
subprocess.run("pip install spandrel==0.4.1 --no-deps", shell=True, check=True)
|
272 |
-
except Exception as e:
|
273 |
-
logger.error(f"Failed to install spandrel: {str(e)}\n{traceback.format_exc()}")
|
274 |
-
raise
|
275 |
-
|
276 |
-
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
277 |
-
DTYPE = torch.float16
|
278 |
-
|
279 |
-
logger.info(f"Using device: {DEVICE}")
|
280 |
-
|
281 |
-
DEFAULT_FACE_NUMBER = 20000 # Reduced for memory efficiency
|
282 |
-
MAX_SEED = np.iinfo(np.int32).max
|
283 |
-
TRIPOSG_REPO_URL = "https://github.com/VAST-AI-Research/TripoSG.git"
|
284 |
-
MV_ADAPTER_REPO_URL = "https://github.com/huanngzh/MV-Adapter.git"
|
285 |
-
|
286 |
-
RMBG_PRETRAINED_MODEL = "checkpoints/RMBG-1.4"
|
287 |
-
TRIPOSG_PRETRAINED_MODEL = "checkpoints/TripoSG"
|
288 |
-
|
289 |
-
TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")
|
290 |
-
os.makedirs(TMP_DIR, exist_ok=True)
|
291 |
-
|
292 |
-
TRIPOSG_CODE_DIR = "./triposg"
|
293 |
-
if not os.path.exists(TRIPOSG_CODE_DIR):
|
294 |
-
logger.info(f"Cloning TripoSG repository to {TRIPOSG_CODE_DIR}")
|
295 |
-
os.system(f"git clone {TRIPOSG_REPO_URL} {TRIPOSG_CODE_DIR}")
|
296 |
-
|
297 |
-
MV_ADAPTER_CODE_DIR = "./mv_adapter"
|
298 |
-
if not os.path.exists(MV_ADAPTER_CODE_DIR):
|
299 |
-
logger.info(f"Cloning MV-Adapter repository to {MV_ADAPTER_CODE_DIR}")
|
300 |
-
os.system(f"git clone {MV_ADAPTER_REPO_URL} {MV_ADAPTER_CODE_DIR} && cd {MV_ADAPTER_CODE_DIR} && git checkout 7d37a97e9bc223cdb8fd26a76bd8dd46504c7c3d")
|
301 |
-
|
302 |
-
import sys
|
303 |
-
sys.path.append(TRIPOSG_CODE_DIR)
|
304 |
-
sys.path.append(os.path.join(TRIPOSG_CODE_DIR, "scripts"))
|
305 |
-
sys.path.append(MV_ADAPTER_CODE_DIR)
|
306 |
-
sys.path.append(os.path.join(MV_ADAPTER_CODE_DIR, "scripts"))
|
307 |
-
|
308 |
-
try:
|
309 |
-
from image_process import prepare_image
|
310 |
-
from briarmbg import BriaRMBG
|
311 |
-
snapshot_download("briaai/RMBG-1.4", local_dir=RMBG_PRETRAINED_MODEL)
|
312 |
-
rmbg_net = BriaRMBG.from_pretrained(RMBG_PRETRAINED_MODEL).to(DEVICE, dtype=DTYPE)
|
313 |
-
rmbg_net.eval()
|
314 |
-
from triposg.pipelines.pipeline_triposg import TripoSGPipeline
|
315 |
-
snapshot_download("VAST-AI/TripoSG", local_dir=TRIPOSG_PRETRAINED_MODEL)
|
316 |
-
triposg_pipe = TripoSGPipeline.from_pretrained(TRIPOSG_PRETRAINED_MODEL).to(DEVICE, dtype=DTYPE)
|
317 |
-
except Exception as e:
|
318 |
-
logger.error(f"Failed to load TripoSG models: {str(e)}\n{traceback.format_exc()}")
|
319 |
-
raise
|
320 |
-
|
321 |
-
try:
|
322 |
-
NUM_VIEWS = 4 # Reduced for memory efficiency
|
323 |
-
from inference_ig2mv_sdxl import prepare_pipeline, preprocess_image, remove_bg
|
324 |
-
from mvadapter.utils import get_orthogonal_camera, tensor_to_image, make_image_grid
|
325 |
-
from mvadapter.utils.render import NVDiffRastContextWrapper, load_mesh, render
|
326 |
-
mv_adapter_pipe = prepare_pipeline(
|
327 |
-
base_model="stabilityai/stable-diffusion-xl-base-1.0",
|
328 |
-
vae_model="madebyollin/sdxl-vae-fp16-fix",
|
329 |
-
unet_model=None,
|
330 |
-
lora_model=None,
|
331 |
-
adapter_path="huanngzh/mv-adapter",
|
332 |
-
scheduler=None,
|
333 |
-
num_views=NUM_VIEWS,
|
334 |
-
device=DEVICE,
|
335 |
-
dtype=torch.float16,
|
336 |
-
)
|
337 |
-
birefnet = AutoModelForImageSegmentation.from_pretrained(
|
338 |
-
"ZhengPeng7/BiRefNet", trust_remote_code=True
|
339 |
-
).to(DEVICE, dtype=DTYPE)
|
340 |
-
transform_image = transforms.Compose(
|
341 |
-
[
|
342 |
-
transforms.Resize((512, 512)), # Reduced resolution
|
343 |
-
transforms.ToTensor(),
|
344 |
-
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
345 |
-
]
|
346 |
-
)
|
347 |
-
remove_bg_fn = lambda x: remove_bg(x, birefnet, transform_image, DEVICE)
|
348 |
-
except Exception as e:
|
349 |
-
logger.error(f"Failed to load MV-Adapter models: {str(e)}\n{traceback.format_exc()}")
|
350 |
-
raise
|
351 |
-
|
352 |
-
try:
|
353 |
-
if not os.path.exists("checkpoints/RealESRGAN_x2plus.pth"):
|
354 |
-
hf_hub_download("dtarnow/UPscaler", filename="RealESRGAN_x2plus.pth", local_dir="checkpoints")
|
355 |
-
if not os.path.exists("checkpoints/big-lama.pt"):
|
356 |
-
subprocess.run("wget -P checkpoints/ https://github.com/Sanster/models/releases/download/add_big_lama/big-lama.pt", shell=True, check=True)
|
357 |
-
except Exception as e:
|
358 |
-
logger.error(f"Failed to download checkpoints: {str(e)}\n{traceback.format_exc()}")
|
359 |
-
raise
|
360 |
-
|
361 |
-
def log_gpu_memory():
|
362 |
-
if torch.cuda.is_available():
|
363 |
-
allocated = torch.cuda.memory_allocated() / 1024**3
|
364 |
-
reserved = torch.cuda.memory_reserved() / 1024**3
|
365 |
-
logger.info(f"GPU Memory: Allocated {allocated:.2f} GB, Reserved {reserved:.2f} GB")
|
366 |
-
|
367 |
-
def get_random_hex():
|
368 |
-
random_bytes = os.urandom(8)
|
369 |
-
random_hex = random_bytes.hex()
|
370 |
-
return random_hex
|
371 |
-
|
372 |
-
def retry_on_failure(func, max_attempts=3, delay=1):
|
373 |
-
for attempt in range(max_attempts):
|
374 |
-
try:
|
375 |
-
return func()
|
376 |
-
except RuntimeError as e:
|
377 |
-
logger.warning(f"Attempt {attempt + 1} failed: {str(e)}\n{traceback.format_exc()}")
|
378 |
-
if attempt == max_attempts - 1:
|
379 |
-
raise
|
380 |
-
time.sleep(delay)
|
381 |
-
|
382 |
-
@spaces.GPU(duration=2)
|
383 |
-
@torch.no_grad()
|
384 |
-
def run_segmentation(image):
|
385 |
-
try:
|
386 |
-
log_gpu_memory()
|
387 |
-
if isinstance(image, dict):
|
388 |
-
image_path = image.get("path") or image.get("url")
|
389 |
-
if not image_path:
|
390 |
-
raise ValueError("Invalid image input: no path or URL provided")
|
391 |
-
if image_path.startswith("http"):
|
392 |
-
temp_image_path = os.path.join(TMP_DIR, f"input_{get_random_hex()}.png")
|
393 |
-
image_path = download_image(image_path, temp_image_path)
|
394 |
-
elif isinstance(image, str) and image.startswith("http"):
|
395 |
-
temp_image_path = os.path.join(TMP_DIR, f"input_{get_random_hex()}.png")
|
396 |
-
image_path = download_image(image, temp_image_path)
|
397 |
-
else:
|
398 |
-
image_path = image
|
399 |
-
if not isinstance(image, (str, bytes)) or (isinstance(image, str) and not os.path.exists(image)):
|
400 |
-
raise ValueError(f"Expected str (path/URL), bytes, or FileData dict, got {type(image)}")
|
401 |
-
|
402 |
-
with autocast():
|
403 |
-
image_seg = prepare_image(image_path, bg_color=np.array([1.0, 1.0, 1.0]), rmbg_net=rmbg_net)
|
404 |
-
rmbg_net.to("cpu")
|
405 |
-
torch.cuda.empty_cache()
|
406 |
-
log_gpu_memory()
|
407 |
-
return image_seg
|
408 |
-
except Exception as e:
|
409 |
-
logger.error(f"Error in run_segmentation: {str(e)}\n{traceback.format_exc()}")
|
410 |
-
raise
|
411 |
-
|
412 |
-
@spaces.GPU(duration=3)
|
413 |
-
@torch.no_grad()
|
414 |
-
def image_to_3d(image, seed, num_inference_steps=30, guidance_scale=7.0, simplify=True, target_face_num=DEFAULT_FACE_NUMBER, req=None):
|
415 |
-
try:
|
416 |
-
log_gpu_memory()
|
417 |
-
triposg_pipe.to(DEVICE, dtype=DTYPE)
|
418 |
-
with autocast():
|
419 |
-
outputs = triposg_pipe(
|
420 |
-
image=image,
|
421 |
-
generator=torch.Generator(device=triposg_pipe.device).manual_seed(seed),
|
422 |
-
num_inference_steps=num_inference_steps,
|
423 |
-
guidance_scale=guidance_scale
|
424 |
-
).samples[0]
|
425 |
-
mesh = trimesh.Trimesh(outputs[0].astype(np.float32), np.ascontiguousarray(outputs[1]))
|
426 |
-
if simplify:
|
427 |
-
from utils import simplify_mesh
|
428 |
-
mesh = simplify_mesh(mesh, target_face_num)
|
429 |
-
save_dir = os.path.join(TMP_DIR, str(req.session_hash) if req else "examples")
|
430 |
-
os.makedirs(save_dir, exist_ok=True)
|
431 |
-
mesh_path = os.path.join(save_dir, f"polygenixai_{get_random_hex()}.glb")
|
432 |
-
mesh.export(mesh_path)
|
433 |
-
triposg_pipe.to("cpu")
|
434 |
-
torch.cuda.empty_cache()
|
435 |
-
log_gpu_memory()
|
436 |
-
return mesh_path
|
437 |
-
except Exception as e:
|
438 |
-
logger.error(f"Error in image_to_3d: {str(e)}\n{traceback.format_exc()}")
|
439 |
-
raise
|
440 |
-
|
441 |
@spaces.GPU(duration=3)
|
442 |
@torch.no_grad()
|
443 |
def run_texture(image, mesh_path, seed, req=None):
|
@@ -646,4 +402,203 @@ try:
|
|
646 |
logger.info("Gradio API interface initialized successfully")
|
647 |
except Exception as e:
|
648 |
logger.error(f"Failed to initialize Gradio API interface: {str(e)}\n{traceback.format_exc()}")
|
649 |
-
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
logger.error(f"Error in image_to_3d: {str(e)}\n{traceback.format_exc()}")
|
195 |
raise
|
196 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
197 |
@spaces.GPU(duration=3)
|
198 |
@torch.no_grad()
|
199 |
def run_texture(image, mesh_path, seed, req=None):
|
|
|
402 |
logger.info("Gradio API interface initialized successfully")
|
403 |
except Exception as e:
|
404 |
logger.error(f"Failed to initialize Gradio API interface: {str(e)}\n{traceback.format_exc()}")
|
405 |
+
raise
|
406 |
+
|
407 |
+
HEADER = """
|
408 |
+
# 🌌 PolyGenixAI: Craft 3D Worlds with Cosmic Precision
|
409 |
+
## Unleash Infinite Creativity with AI-Powered 3D Generation by AnvilInteractive Solutions
|
410 |
+
<p style="font-size: 1.1em; color: #A78BFA;">By <a href="https://www.anvilinteractive.com/" style="color: #A78BFA; text-decoration: none; font-weight: bold;">AnvilInteractive Solutions</a></p>
|
411 |
+
## 🚀 Launch Your Creation:
|
412 |
+
1. **Upload an Image** (clear, single-object images shine brightest)
|
413 |
+
2. **Choose a Style Filter** to infuse your unique vision
|
414 |
+
3. Click **Generate 3D Model** to sculpt your mesh
|
415 |
+
4. Click **Apply Texture** to bring your model to life
|
416 |
+
5. **Download GLB** to share your masterpiece
|
417 |
+
<p style="font-size: 0.9em; margin-top: 10px; color: #D1D5DB;">Powered by cutting-edge AI and multi-view technology from AnvilInteractive Solutions. Join our <a href="https://www.anvilinteractive.com/community" style="color: #A78BFA; text-decoration: none;">PolyGenixAI Community</a> to connect with creators and spark inspiration.</p>
|
418 |
+
<style>
|
419 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
|
420 |
+
body {
|
421 |
+
background-color: #1A1A1A !important;
|
422 |
+
font-family: 'Inter', sans-serif !important;
|
423 |
+
color: #D1D5DB !important;
|
424 |
+
}
|
425 |
+
.gr-panel {
|
426 |
+
background-color: #2D2D2D !important;
|
427 |
+
border: 1px solid #7C3AED !important;
|
428 |
+
border-radius: 12px !important;
|
429 |
+
padding: 20px !important;
|
430 |
+
box-shadow: 0 4px 10px rgba(124, 58, 237, 0.2) !important;
|
431 |
+
}
|
432 |
+
.gr-button-primary {
|
433 |
+
background: linear-gradient(45deg, #7C3AED, #A78BFA) !important;
|
434 |
+
color: white !important;
|
435 |
+
border: none !important;
|
436 |
+
border-radius: 8px !important;
|
437 |
+
padding: 12px 24px !important;
|
438 |
+
font-weight: 600 !important;
|
439 |
+
transition: transform 0.2s, box-shadow 0.2s !important;
|
440 |
+
}
|
441 |
+
.gr-button-primary:hover {
|
442 |
+
transform: translateY(-2px) !important;
|
443 |
+
box-shadow: 0 4px 12px rgba(124, 58, 237, 0.5) !important;
|
444 |
+
}
|
445 |
+
.gr-button-secondary {
|
446 |
+
background-color: #4B4B4B !important;
|
447 |
+
color: #D1D5DB !important;
|
448 |
+
border: 1px solid #A78BFA !important;
|
449 |
+
border-radius: 8px !important;
|
450 |
+
padding: 10px 20px !important;
|
451 |
+
transition: transform 0.2s !important;
|
452 |
+
}
|
453 |
+
.gr-button-secondary:hover {
|
454 |
+
transform: translateY(-1px) !important;
|
455 |
+
background-color: #6B6B6B !important;
|
456 |
+
}
|
457 |
+
.gr-accordion {
|
458 |
+
background-color: #2D2D2D !important;
|
459 |
+
border-radius: 8px !important;
|
460 |
+
border: 1px solid #7C3AED !important;
|
461 |
+
}
|
462 |
+
.gr-tab {
|
463 |
+
background-color: #2D2D2D !important;
|
464 |
+
color: #A78BFA !important;
|
465 |
+
border: 1px solid #7C3AED !important;
|
466 |
+
border-radius: 8px !important;
|
467 |
+
margin: 5px !important;
|
468 |
+
}
|
469 |
+
.gr-tab:hover, .gr-tab-selected {
|
470 |
+
background: linear-gradient(45deg, #7C3AED, #A78BFA) !important;
|
471 |
+
color: white !important;
|
472 |
+
}
|
473 |
+
.gr-slider input[type=range]::-webkit-slider-thumb {
|
474 |
+
background-color: #7C3AED !important;
|
475 |
+
border: 2px solid #A78BFA !important;
|
476 |
+
}
|
477 |
+
.gr-dropdown {
|
478 |
+
background-color: #2D2D2D !important;
|
479 |
+
color: #D1D5DB !important;
|
480 |
+
border: 1px solid #A78BFA !important;
|
481 |
+
border-radius: 8px !important;
|
482 |
+
}
|
483 |
+
h1, h3 {
|
484 |
+
color: #A78BFA !important;
|
485 |
+
text-shadow: 0 0 10px rgba(124, 58, 237, 0.5) !important;
|
486 |
+
}
|
487 |
+
</style>
|
488 |
+
"""
|
489 |
+
|
490 |
+
try:
|
491 |
+
logger.info("Initializing Gradio Blocks interface")
|
492 |
+
with gr.Blocks(title="PolyGenixAI", css="body { background-color: #1A1A1A; } .gr-panel { background-color: #2D2D2D; }") as demo:
|
493 |
+
gr.Markdown(HEADER)
|
494 |
+
with gr.Tabs(elem_classes="gr-tab"):
|
495 |
+
with gr.Tab("Create 3D Model"):
|
496 |
+
with gr.Row():
|
497 |
+
with gr.Column(scale=1):
|
498 |
+
image_prompts = gr.Image(label="Upload Image", type="filepath", height=300, elem_classes="gr-panel")
|
499 |
+
seg_image = gr.Image(label="Preview Segmentation", type="pil", format="png", interactive=False, height=300, elem_classes="gr-panel")
|
500 |
+
with gr.Accordion("Style & Settings", open=True, elem_classes="gr-accordion"):
|
501 |
+
style_filter = gr.Dropdown(
|
502 |
+
choices=["None", "Realistic", "Fantasy", "Cartoon", "Sci-Fi", "Vintage", "Cosmic", "Neon"],
|
503 |
+
label="Style Filter",
|
504 |
+
value="None",
|
505 |
+
info="Select a style to inspire your 3D model (optional)",
|
506 |
+
elem_classes="gr-dropdown"
|
507 |
+
)
|
508 |
+
seed = gr.Slider(
|
509 |
+
label="Seed",
|
510 |
+
minimum=0,
|
511 |
+
maximum=MAX_SEED,
|
512 |
+
step=1,
|
513 |
+
value=0,
|
514 |
+
elem_classes="gr-slider"
|
515 |
+
)
|
516 |
+
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
|
517 |
+
num_inference_steps = gr.Slider(
|
518 |
+
label="Inference Steps",
|
519 |
+
minimum=8,
|
520 |
+
maximum=50,
|
521 |
+
step=1,
|
522 |
+
value=30,
|
523 |
+
info="Higher steps enhance detail but increase processing time",
|
524 |
+
elem_classes="gr-slider"
|
525 |
+
)
|
526 |
+
guidance_scale = gr.Slider(
|
527 |
+
label="Guidance Scale",
|
528 |
+
minimum=0.0,
|
529 |
+
maximum=20.0,
|
530 |
+
step=0.1,
|
531 |
+
value=7.0,
|
532 |
+
info="Controls adherence to input image",
|
533 |
+
elem_classes="gr-slider"
|
534 |
+
)
|
535 |
+
reduce_face = gr.Checkbox(label="Simplify Mesh", value=True)
|
536 |
+
target_face_num = gr.Slider(
|
537 |
+
maximum=100000,
|
538 |
+
minimum=10000,
|
539 |
+
value=DEFAULT_FACE_NUMBER,
|
540 |
+
label="Target Face Number",
|
541 |
+
info="Adjust mesh complexity for performance",
|
542 |
+
elem_classes="gr-slider"
|
543 |
+
)
|
544 |
+
gen_button = gr.Button("Generate 3D Model", variant="primary", elem_classes="gr-button-primary")
|
545 |
+
gen_texture_button = gr.Button("Apply Texture", variant="secondary", interactive=False, elem_classes="gr-button-secondary")
|
546 |
+
with gr.Column(scale=1):
|
547 |
+
model_output = gr.Model3D(label="3D Model Preview", interactive=False, height=400, elem_classes="gr-panel")
|
548 |
+
textured_model_output = gr.Model3D(label="Textured 3D Model", interactive=False, height=400, elem_classes="gr-panel")
|
549 |
+
download_button = gr.Button("Download GLB", variant="secondary", elem_classes="gr-button-secondary")
|
550 |
+
with gr.Tab("Cosmic Gallery"):
|
551 |
+
gr.Markdown("### Discover Stellar Creations")
|
552 |
+
gr.Examples(
|
553 |
+
examples=[
|
554 |
+
f"{TRIPOSG_CODE_DIR}/assets/example_data/{image}"
|
555 |
+
for image in os.listdir(f"{TRIPOSG_CODE_DIR}/assets/example_data")
|
556 |
+
],
|
557 |
+
fn=run_full_api,
|
558 |
+
inputs=[image_prompts],
|
559 |
+
outputs=[seg_image, model_output, textured_model_output],
|
560 |
+
cache_examples=True,
|
561 |
+
)
|
562 |
+
gr.Markdown("Connect with creators in our <a href='https://www.anvilinteractive.com/community' style='color: #A78BFA; text-decoration: none;'>PolyGenixAI Cosmic Community</a>!")
|
563 |
+
gen_button.click(
|
564 |
+
run_segmentation,
|
565 |
+
inputs=[image_prompts],
|
566 |
+
outputs=[seg_image]
|
567 |
+
).then(
|
568 |
+
get_random_seed,
|
569 |
+
inputs=[randomize_seed, seed],
|
570 |
+
outputs=[seed],
|
571 |
+
).then(
|
572 |
+
image_to_3d,
|
573 |
+
inputs=[
|
574 |
+
seg_image,
|
575 |
+
seed,
|
576 |
+
num_inference_steps,
|
577 |
+
guidance_scale,
|
578 |
+
reduce_face,
|
579 |
+
target_face_num
|
580 |
+
],
|
581 |
+
outputs=[model_output]
|
582 |
+
).then(
|
583 |
+
lambda: gr.Button(interactive=True), outputs=[gen_texture_button]
|
584 |
+
)
|
585 |
+
gen_texture_button.click(
|
586 |
+
run_texture,
|
587 |
+
inputs=[image_prompts, model_output, seed],
|
588 |
+
outputs=[textured_model_output]
|
589 |
+
)
|
590 |
+
demo.load(start_session)
|
591 |
+
demo.unload(end_session)
|
592 |
+
logger.info("Gradio Blocks interface initialized successfully")
|
593 |
+
except Exception as e:
|
594 |
+
logger.error(f"Failed to initialize Gradio Blocks interface: {str(e)}\n{traceback.format_exc()}")
|
595 |
+
raise
|
596 |
+
|
597 |
+
if __name__ == "__main__":
|
598 |
+
try:
|
599 |
+
logger.info("Launching Gradio application")
|
600 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)
|
601 |
+
logger.info("Gradio application launched successfully")
|
602 |
+
except Exception as e:
|
603 |
+
logger.error(f"Failed to launch Gradio application: {str(e)}\n{traceback.format_exc()}")
|
604 |
+
raise
|