Vo Minh Vu commited on
Commit
1a93c67
·
1 Parent(s): 857d4d1

update req

Browse files
Files changed (3) hide show
  1. app.py +3 -14
  2. main.py +0 -171
  3. requirements.txt +1 -1
app.py CHANGED
@@ -1,17 +1,3 @@
1
- import sys, subprocess
2
-
3
- # 1) Try importing; if it fails, install your wheel
4
- try:
5
- import torchmcubes
6
- except ImportError:
7
- subprocess.check_call([
8
- sys.executable, "-m", "pip", "install",
9
- "./wheels/torchmcubes-0.1.0-cp310-cp310-linux_x86_64.whl"
10
- ])
11
- # now it's installed, so re-import
12
- import torchmcubes
13
-
14
- # 2) Now safe to import the rest of your app
15
  import io
16
  import os
17
  import shlex
@@ -35,6 +21,9 @@ from tsr.utils import remove_background, resize_foreground, to_gradio_3d_orienta
35
  # ------------------------------------------------------------
36
  # 1. Model & utils initialization (runs at startup)
37
  # ------------------------------------------------------------
 
 
 
38
  # device
39
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import io
2
  import os
3
  import shlex
 
21
  # ------------------------------------------------------------
22
  # 1. Model & utils initialization (runs at startup)
23
  # ------------------------------------------------------------
24
+ # Install any local wheels (if needed)
25
+
26
+
27
  # device
28
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
29
 
main.py DELETED
@@ -1,171 +0,0 @@
1
- import io
2
- import os
3
- import shlex
4
- import subprocess
5
- import tempfile
6
- import zipfile
7
- from functools import partial
8
-
9
- from fastapi import FastAPI, File, UploadFile, Form, HTTPException
10
- from fastapi.responses import StreamingResponse
11
- from fastapi.middleware.cors import CORSMiddleware
12
-
13
- import numpy as np
14
- import rembg
15
- import torch
16
- from PIL import Image
17
-
18
- from tsr.system import TSR
19
- from tsr.utils import remove_background, resize_foreground, to_gradio_3d_orientation
20
-
21
- # ------------------------------------------------------------
22
- # 1. Model & utils initialization (runs at startup)
23
- # ------------------------------------------------------------
24
- # Install any local wheels (if needed)
25
- subprocess.run(
26
- shlex.split(
27
- "pip install wheel/torchmcubes-0.1.0-cp310-cp310-linux_x86_64.whl"
28
- ),
29
- check=False,
30
- )
31
-
32
- # device
33
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
34
-
35
- # load model
36
- model = TSR.from_pretrained(
37
- "stabilityai/TripoSR",
38
- config_name="config.yaml",
39
- weight_name="model.ckpt",
40
- )
41
- model.renderer.set_chunk_size(131072)
42
- model.to(device)
43
-
44
- # background removal
45
- rembg_session = rembg.new_session()
46
-
47
-
48
- def check_input_image(image: Image.Image):
49
- if image is None:
50
- raise HTTPException(status_code=400, detail="No image uploaded!")
51
-
52
-
53
- def preprocess(
54
- input_image: Image.Image, do_remove_background: bool, foreground_ratio: float
55
- ) -> Image.Image:
56
- """
57
- Mimics the Gradio preprocess(...) function.
58
- """
59
- def fill_background(image: Image.Image) -> Image.Image:
60
- arr = np.array(image).astype(np.float32) / 255.0
61
- arr = arr[:, :, :3] * arr[:, :, 3:4] + (1 - arr[:, :, 3:4]) * 0.5
62
- out = (arr * 255.0).astype(np.uint8)
63
- return Image.fromarray(out)
64
-
65
- if do_remove_background:
66
- image = input_image.convert("RGB")
67
- image = remove_background(image, rembg_session)
68
- image = resize_foreground(image, foreground_ratio)
69
- image = fill_background(image)
70
- else:
71
- image = input_image
72
- if image.mode == "RGBA":
73
- image = fill_background(image)
74
-
75
- return image
76
-
77
-
78
- def generate(
79
- image: Image.Image, mc_resolution: int, formats=["obj", "glb"]
80
- ) -> tuple[str, str]:
81
- """
82
- Mimics the Gradio generate(...) function.
83
- Returns paths to .obj and .glb on disk.
84
- """
85
- # 1. inference
86
- scene_codes = model(image, device=device)
87
- mesh = model.extract_mesh(scene_codes, resolution=mc_resolution)[0]
88
- mesh = to_gradio_3d_orientation(mesh)
89
-
90
- # 2. export GLB
91
- glb_tmp = tempfile.NamedTemporaryFile(suffix=".glb", delete=False)
92
- mesh.export(glb_tmp.name)
93
-
94
- # 3. export OBJ (flip x-axis so OBJ is not mirrored)
95
- obj_tmp = tempfile.NamedTemporaryFile(suffix=".obj", delete=False)
96
- mesh.apply_scale([-1, 1, 1])
97
- mesh.export(obj_tmp.name)
98
-
99
- return obj_tmp.name, glb_tmp.name
100
-
101
-
102
- # ------------------------------------------------------------
103
- # 2. FastAPI app
104
- # ------------------------------------------------------------
105
- app = FastAPI(title="TripoSR FastAPI Demo")
106
-
107
- # If you need CORS (e.g. calling from a browser-based front-end)
108
- app.add_middleware(
109
- CORSMiddleware,
110
- allow_origins=["*"],
111
- allow_methods=["POST", "GET", "OPTIONS"],
112
- allow_headers=["*"],
113
- )
114
-
115
-
116
- @app.post("/generate", response_class=StreamingResponse)
117
- async def generate_endpoint(
118
- image_file: UploadFile = File(...),
119
- do_remove_background: bool = Form(True),
120
- foreground_ratio: float = Form(0.85),
121
- mc_resolution: int = Form(256),
122
- ):
123
- """
124
- 1. Read & validate image
125
- 2. Preprocess
126
- 3. Generate mesh
127
- 4. Package processed image + .obj + .glb into a ZIP
128
- """
129
- # 1) Read image bytes
130
- contents = await image_file.read()
131
- try:
132
- pil_img = Image.open(io.BytesIO(contents))
133
- except Exception:
134
- raise HTTPException(status_code=400, detail="Invalid image file")
135
-
136
- check_input_image(pil_img)
137
-
138
- # 2) Preprocess
139
- processed = preprocess(pil_img, do_remove_background, foreground_ratio)
140
-
141
- # 3) Generate mesh
142
- obj_path, glb_path = generate(processed, mc_resolution)
143
-
144
- # 4) Create in-memory ZIP
145
- zip_buffer = io.BytesIO()
146
- with zipfile.ZipFile(zip_buffer, mode="w") as zf:
147
- # processed image
148
- buf = io.BytesIO()
149
- processed.save(buf, format="PNG")
150
- zf.writestr("processed.png", buf.getvalue())
151
-
152
- # .obj
153
- with open(obj_path, "rb") as f:
154
- zf.writestr(os.path.basename(obj_path), f.read())
155
-
156
- # .glb
157
- with open(glb_path, "rb") as f:
158
- zf.writestr(os.path.basename(glb_path), f.read())
159
-
160
- zip_buffer.seek(0)
161
-
162
- # Cleanup temp files
163
- os.remove(obj_path)
164
- os.remove(glb_path)
165
-
166
- headers = {
167
- "Content-Disposition": 'attachment; filename="tripo_output.zip"'
168
- }
169
- return StreamingResponse(
170
- zip_buffer, media_type="application/zip", headers=headers
171
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -8,6 +8,6 @@ rembg
8
  huggingface-hub
9
  gradio
10
  onnxruntime
11
-
12
  fastapi
13
  uvicorn[standard]
 
8
  huggingface-hub
9
  gradio
10
  onnxruntime
11
+ ./wheel/torchmcubes-0.1.0-cp310-cp310-linux_x86_64.whl
12
  fastapi
13
  uvicorn[standard]