Spaces:
Running
on
Zero
Running
on
Zero
custom api endpoints
Browse files
app.py
CHANGED
|
@@ -17,11 +17,24 @@ from trellis.utils import render_utils, postprocessing_utils
|
|
| 17 |
import traceback
|
| 18 |
import sys
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
MAX_SEED = np.iinfo(np.int32).max
|
| 22 |
TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
|
| 23 |
os.makedirs(TMP_DIR, exist_ok=True)
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
def start_session(req: gr.Request):
|
| 27 |
user_dir = os.path.join(TMP_DIR, str(req.session_hash))
|
|
@@ -201,6 +214,80 @@ def extract_gaussian(state: dict, req: gr.Request) -> Tuple[str, str]:
|
|
| 201 |
return gaussian_path, gaussian_path
|
| 202 |
|
| 203 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
with gr.Blocks(delete_cache=(600, 600)) as demo:
|
| 205 |
gr.Markdown("""
|
| 206 |
## Text to 3D Asset with [TRELLIS](https://trellis3d.github.io/)
|
|
@@ -293,8 +380,30 @@ with gr.Blocks(delete_cache=(600, 600)) as demo:
|
|
| 293 |
)
|
| 294 |
|
| 295 |
|
| 296 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 298 |
pipeline = TrellisTextTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-text-xlarge")
|
| 299 |
pipeline.cuda()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
demo.launch()
|
|
|
|
| 17 |
import traceback
|
| 18 |
import sys
|
| 19 |
|
| 20 |
+
# --- FastAPI / Threading Imports ---
|
| 21 |
+
import threading
|
| 22 |
+
import uvicorn
|
| 23 |
+
import logging
|
| 24 |
+
from fastapi import FastAPI, HTTPException
|
| 25 |
+
from pydantic import BaseModel
|
| 26 |
+
|
| 27 |
|
| 28 |
MAX_SEED = np.iinfo(np.int32).max
|
| 29 |
TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
|
| 30 |
os.makedirs(TMP_DIR, exist_ok=True)
|
| 31 |
|
| 32 |
+
# --- Global Pipeline Variable ---
|
| 33 |
+
pipeline = None
|
| 34 |
+
|
| 35 |
+
# --- Logging Setup ---
|
| 36 |
+
logging.basicConfig(level=logging.INFO)
|
| 37 |
+
logger = logging.getLogger(__name__)
|
| 38 |
|
| 39 |
def start_session(req: gr.Request):
|
| 40 |
user_dir = os.path.join(TMP_DIR, str(req.session_hash))
|
|
|
|
| 214 |
return gaussian_path, gaussian_path
|
| 215 |
|
| 216 |
|
| 217 |
+
# --- FastAPI App Setup ---
|
| 218 |
+
api_app = FastAPI()
|
| 219 |
+
|
| 220 |
+
class GenerateRequest(BaseModel):
|
| 221 |
+
prompt: str
|
| 222 |
+
seed: int = 0 # Default seed
|
| 223 |
+
mesh_simplify: float = 0.95 # Default simplify factor
|
| 224 |
+
texture_size: int = 1024 # Default texture size
|
| 225 |
+
# Add other generation parameters if needed
|
| 226 |
+
|
| 227 |
+
@api_app.post("/api/generate-sync")
|
| 228 |
+
@spaces.GPU(duration=300) # Allow longer duration for API calls
|
| 229 |
+
async def generate_sync_api(request_data: GenerateRequest):
|
| 230 |
+
global pipeline # Access the globally initialized pipeline
|
| 231 |
+
if pipeline is None:
|
| 232 |
+
logger.error("API Error: Pipeline not initialized")
|
| 233 |
+
raise HTTPException(status_code=503, detail="Pipeline not ready")
|
| 234 |
+
|
| 235 |
+
prompt = request_data.prompt
|
| 236 |
+
seed = request_data.seed
|
| 237 |
+
mesh_simplify = request_data.mesh_simplify
|
| 238 |
+
texture_size = request_data.texture_size
|
| 239 |
+
# Extract other params if added to GenerateRequest
|
| 240 |
+
|
| 241 |
+
logger.info(f"API /generate-sync received prompt: {prompt}")
|
| 242 |
+
|
| 243 |
+
try:
|
| 244 |
+
# --- Determine a unique temporary directory for this API call ---
|
| 245 |
+
api_call_hash = f"api_sync_{np.random.randint(100000)}"
|
| 246 |
+
user_dir = os.path.join(TMP_DIR, api_call_hash)
|
| 247 |
+
os.makedirs(user_dir, exist_ok=True)
|
| 248 |
+
logger.info(f"API using temp dir: {user_dir}")
|
| 249 |
+
|
| 250 |
+
# --- Stage 1: Run the text-to-3D pipeline ---
|
| 251 |
+
logger.info("API running pipeline...")
|
| 252 |
+
# Use default values for parameters not exposed in the simple API for now
|
| 253 |
+
outputs = pipeline.run(
|
| 254 |
+
prompt,
|
| 255 |
+
seed=seed,
|
| 256 |
+
formats=["gaussian", "mesh"],
|
| 257 |
+
sparse_structure_sampler_params={"steps": 25, "cfg_strength": 7.5},
|
| 258 |
+
slat_sampler_params={"steps": 25, "cfg_strength": 7.5},
|
| 259 |
+
)
|
| 260 |
+
gs = outputs['gaussian'][0]
|
| 261 |
+
mesh = outputs['mesh'][0]
|
| 262 |
+
logger.info("API pipeline finished.")
|
| 263 |
+
torch.cuda.empty_cache()
|
| 264 |
+
|
| 265 |
+
# --- Stage 2: Extract GLB ---
|
| 266 |
+
logger.info("API extracting GLB...")
|
| 267 |
+
glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)
|
| 268 |
+
glb_path = os.path.join(user_dir, 'generated_sync.glb')
|
| 269 |
+
glb.export(glb_path)
|
| 270 |
+
logger.info(f"API GLB exported to: {glb_path}")
|
| 271 |
+
torch.cuda.empty_cache()
|
| 272 |
+
|
| 273 |
+
# Return the absolute path within the container
|
| 274 |
+
return {"status": "success", "glb_path": os.path.abspath(glb_path)}
|
| 275 |
+
|
| 276 |
+
except Exception as e:
|
| 277 |
+
logger.error(f"API /generate-sync error: {str(e)}", exc_info=True)
|
| 278 |
+
# Clean up temp dir on error if it exists
|
| 279 |
+
if os.path.exists(user_dir):
|
| 280 |
+
try:
|
| 281 |
+
shutil.rmtree(user_dir)
|
| 282 |
+
except Exception as cleanup_e:
|
| 283 |
+
logger.error(f"API Error cleaning up dir {user_dir}: {cleanup_e}")
|
| 284 |
+
raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")
|
| 285 |
+
# Note: We don't automatically clean up the user_dir on success,
|
| 286 |
+
# as the file needs to be accessible for download by the calling server.
|
| 287 |
+
# A separate cleanup mechanism might be needed eventually.
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
# --- Gradio Blocks Definition ---
|
| 291 |
with gr.Blocks(delete_cache=(600, 600)) as demo:
|
| 292 |
gr.Markdown("""
|
| 293 |
## Text to 3D Asset with [TRELLIS](https://trellis3d.github.io/)
|
|
|
|
| 380 |
)
|
| 381 |
|
| 382 |
|
| 383 |
+
# --- Functions to Run FastAPI in Background ---
|
| 384 |
+
def run_api():
|
| 385 |
+
"""Run the FastAPI server."""
|
| 386 |
+
uvicorn.run(api_app, host="0.0.0.0", port=8000) # Run on port 8000
|
| 387 |
+
|
| 388 |
+
def start_api_thread():
|
| 389 |
+
"""Start the API server in a background thread."""
|
| 390 |
+
api_thread = threading.Thread(target=run_api, daemon=True)
|
| 391 |
+
api_thread.start()
|
| 392 |
+
logger.info("Started FastAPI server thread on port 8000")
|
| 393 |
+
return api_thread
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
# Launch the Gradio app and FastAPI server
|
| 397 |
if __name__ == "__main__":
|
| 398 |
+
logger.info("Initializing Trellis Pipeline...")
|
| 399 |
+
# Make pipeline global so API endpoint can access it
|
| 400 |
pipeline = TrellisTextTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-text-xlarge")
|
| 401 |
pipeline.cuda()
|
| 402 |
+
logger.info("Trellis Pipeline Initialized.")
|
| 403 |
+
|
| 404 |
+
# Start the background API server
|
| 405 |
+
start_api_thread()
|
| 406 |
+
|
| 407 |
+
# Launch the Gradio interface (blocking call)
|
| 408 |
+
logger.info("Launching Gradio Demo...")
|
| 409 |
demo.launch()
|