andre-2112 commited on
Commit
ddfbfeb
·
verified ·
1 Parent(s): fec0939

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +55 -0
handler.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import base64
3
+ import io
4
+ import tempfile
5
+ from PIL import Image
6
+ # Note: The import might change to 'trellis.2' or stay 'trellis' depending on how they packaged the V2 repo.
7
+ # Standard import usually resolves to the installed package name 'trellis' even for v2.
8
+ from trellis.pipelines import TrellisImageTo3DPipeline
9
+ from trellis.utils import postprocessing_utils
10
+
11
+ class EndpointHandler:
12
+ def __init__(self, path=""):
13
+ print("Loading Trellis 2 Model...")
14
+ # The CORRECT Model ID for V2 (4 Billion parameters)
15
+ self.pipeline = TrellisImageTo3DPipeline.from_pretrained(
16
+ "microsoft/TRELLIS.2-4B",
17
+ torch_dtype=torch.float16,
18
+ use_safetensors=True
19
+ )
20
+ self.pipeline.cuda()
21
+ print("Trellis 2 Loaded!")
22
+
23
+ def __call__(self, data):
24
+ # 1. Parse Input
25
+ inputs = data.pop("inputs", data)
26
+ if isinstance(inputs, dict) and "image" in inputs:
27
+ inputs = inputs["image"]
28
+
29
+ if isinstance(inputs, str):
30
+ image_data = base64.b64decode(inputs)
31
+ image = Image.open(io.BytesIO(image_data)).convert("RGB")
32
+ else:
33
+ image = inputs
34
+
35
+ # 2. Inference
36
+ outputs = self.pipeline.run(image, seed=42, formats=["mesh"])
37
+
38
+ # 3. Export to GLB
39
+ video_content = postprocessing_utils.to_glb(
40
+ outputs['mesh'][0],
41
+ simplify=0.95,
42
+ texture_size=1024
43
+ )
44
+
45
+ # 4. Handle Output
46
+ if isinstance(video_content, str):
47
+ with open(video_content, "rb") as f: glb_bytes = f.read()
48
+ elif isinstance(video_content, bytes):
49
+ glb_bytes = video_content
50
+ else:
51
+ with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
52
+ outputs['mesh'][0].export(tmp.name, file_type='glb')
53
+ with open(tmp.name, "rb") as f: glb_bytes = f.read()
54
+
55
+ return {"glb": base64.b64encode(glb_bytes).decode('utf-8')}