aiqtech commited on
Commit
079e30e
ยท
verified ยท
1 Parent(s): 36dc32d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -40
app.py CHANGED
@@ -32,39 +32,26 @@ MAX_SEED = np.iinfo(np.int32).max
32
  TMP_DIR = "/tmp/Trellis-demo"
33
  os.makedirs(TMP_DIR, exist_ok=True)
34
 
35
- def free_memory():
36
- """๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์ •๋ฆฌํ•˜๋Š” ์œ ํ‹ธ๋ฆฌํ‹ฐ ํ•จ์ˆ˜"""
37
- import gc
38
- gc.collect()
39
-
40
- @spaces.GPU
41
- def free_gpu_memory():
42
- """GPU ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์ •๋ฆฌํ•˜๋Š” ์œ ํ‹ธ๋ฆฌํ‹ฐ ํ•จ์ˆ˜"""
43
- if torch.cuda.is_available():
44
- torch.cuda.empty_cache()
45
-
46
  def initialize_models():
47
  global pipeline, translator, flux_pipe
48
 
49
  try:
50
- # Trellis ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™” (CPU ๋ชจ๋“œ๋กœ)
51
  pipeline = TrellisImageTo3DPipeline.from_pretrained(
52
- "JeffreyXiang/TRELLIS-image-large",
53
- low_cpu_mem_usage=True
54
  )
55
 
56
  # ๋ฒˆ์—ญ๊ธฐ ์ดˆ๊ธฐํ™”
57
  translator = translation_pipeline(
58
  "translation",
59
  model="Helsinki-NLP/opus-mt-ko-en",
60
- device="cpu",
61
- model_kwargs={"low_cpu_mem_usage": True}
62
  )
63
 
64
  # Flux ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™”
65
  flux_pipe = FluxPipeline.from_pretrained(
66
  "black-forest-labs/FLUX.1-dev",
67
- low_cpu_mem_usage=True
68
  )
69
 
70
  print("Models initialized successfully")
@@ -74,6 +61,42 @@ def initialize_models():
74
  print(f"Model initialization error: {str(e)}")
75
  return False
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  def translate_if_korean(text):
78
  if any(ord('๊ฐ€') <= ord(char) <= ord('ํžฃ') for char in text):
79
  translated = translator(text)[0]['translation_text']
@@ -143,10 +166,6 @@ def unpack_state(state: dict) -> Tuple[Gaussian, edict, str]:
143
  def image_to_3d(trial_id: str, seed: int, randomize_seed: bool, ss_guidance_strength: float,
144
  ss_sampling_steps: int, slat_guidance_strength: float, slat_sampling_steps: int):
145
  try:
146
- if torch.cuda.is_available():
147
- pipeline.to("cuda")
148
- pipeline.to(torch.float16)
149
-
150
  if randomize_seed:
151
  seed = np.random.randint(0, MAX_SEED)
152
 
@@ -162,22 +181,24 @@ def image_to_3d(trial_id: str, seed: int, randomize_seed: bool, ss_guidance_stre
162
  Image.LANCZOS
163
  )
164
 
165
- with torch.cuda.amp.autocast():
166
- with torch.no_grad():
167
- outputs = pipeline.run(
168
- input_image,
169
- seed=seed,
170
- formats=["gaussian", "mesh"],
171
- preprocess_image=False,
172
- sparse_structure_sampler_params={
173
- "steps": min(ss_sampling_steps, 15),
174
- "cfg_strength": ss_guidance_strength,
175
- },
176
- slat_sampler_params={
177
- "steps": min(slat_sampling_steps, 15),
178
- "cfg_strength": slat_guidance_strength,
179
- }
180
- )
 
 
181
 
182
  video = render_utils.render_video(outputs['gaussian'][0], num_frames=30)['color']
183
  video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=30)['normal']
@@ -190,14 +211,15 @@ def image_to_3d(trial_id: str, seed: int, randomize_seed: bool, ss_guidance_stre
190
 
191
  state = pack_state(outputs['gaussian'][0], outputs['mesh'][0], trial_id)
192
 
193
- # CPU ๋ชจ๋“œ๋กœ ๋Œ์•„๊ฐ€๊ธฐ
194
- pipeline.to("cpu")
195
 
196
  return state, video_path
197
 
198
  except Exception as e:
199
  print(f"Error in image_to_3d: {str(e)}")
200
- pipeline.to("cpu")
 
201
  raise e
202
 
203
  @spaces.GPU
 
32
  TMP_DIR = "/tmp/Trellis-demo"
33
  os.makedirs(TMP_DIR, exist_ok=True)
34
 
 
 
 
 
 
 
 
 
 
 
 
35
  def initialize_models():
36
  global pipeline, translator, flux_pipe
37
 
38
  try:
39
+ # Trellis ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™” (๊ธฐ๋ณธ CPU ๋ชจ๋“œ)
40
  pipeline = TrellisImageTo3DPipeline.from_pretrained(
41
+ "JeffreyXiang/TRELLIS-image-large"
 
42
  )
43
 
44
  # ๋ฒˆ์—ญ๊ธฐ ์ดˆ๊ธฐํ™”
45
  translator = translation_pipeline(
46
  "translation",
47
  model="Helsinki-NLP/opus-mt-ko-en",
48
+ device="cpu"
 
49
  )
50
 
51
  # Flux ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™”
52
  flux_pipe = FluxPipeline.from_pretrained(
53
  "black-forest-labs/FLUX.1-dev",
54
+ torch_dtype=torch.float32 # CPU ๋ชจ๋“œ
55
  )
56
 
57
  print("Models initialized successfully")
 
61
  print(f"Model initialization error: {str(e)}")
62
  return False
63
 
64
+ def free_memory():
65
+ """๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์ •๋ฆฌํ•˜๋Š” ์œ ํ‹ธ๋ฆฌํ‹ฐ ํ•จ์ˆ˜"""
66
+ import gc
67
+ gc.collect()
68
+
69
+ @spaces.GPU
70
+ def setup_gpu_model(model):
71
+ """GPU ์„ค์ •์ด ํ•„์š”ํ•œ ๋ชจ๋ธ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜"""
72
+ if torch.cuda.is_available():
73
+ model = model.to("cuda")
74
+ return model
75
+
76
+ if __name__ == "__main__":
77
+ # CPU ๋ฉ”๋ชจ๋ฆฌ๋งŒ ์ •๋ฆฌ
78
+ free_memory()
79
+
80
+ # ๋ชจ๋ธ ์ดˆ๊ธฐํ™”
81
+ if not initialize_models():
82
+ print("Failed to initialize models")
83
+ exit(1)
84
+
85
+ try:
86
+ # rembg ์‚ฌ์ „ ๋กœ๋“œ ์‹œ๋„ (์ž‘์€ ์ด๋ฏธ์ง€๋กœ)
87
+ test_image = Image.fromarray(np.ones((64, 64, 3), dtype=np.uint8) * 255)
88
+ pipeline.preprocess_image(test_image)
89
+ except Exception as e:
90
+ print(f"Warning: Failed to preload rembg: {str(e)}")
91
+
92
+ # Gradio ์•ฑ ์‹คํ–‰
93
+ demo.queue(max_size=5).launch(
94
+ share=True,
95
+ max_threads=2,
96
+ show_error=True,
97
+ cache_examples=False
98
+ )
99
+
100
  def translate_if_korean(text):
101
  if any(ord('๊ฐ€') <= ord(char) <= ord('ํžฃ') for char in text):
102
  translated = translator(text)[0]['translation_text']
 
166
  def image_to_3d(trial_id: str, seed: int, randomize_seed: bool, ss_guidance_strength: float,
167
  ss_sampling_steps: int, slat_guidance_strength: float, slat_sampling_steps: int):
168
  try:
 
 
 
 
169
  if randomize_seed:
170
  seed = np.random.randint(0, MAX_SEED)
171
 
 
181
  Image.LANCZOS
182
  )
183
 
184
+ if torch.cuda.is_available():
185
+ pipeline.to("cuda")
186
+
187
+ with torch.no_grad():
188
+ outputs = pipeline.run(
189
+ input_image,
190
+ seed=seed,
191
+ formats=["gaussian", "mesh"],
192
+ preprocess_image=False,
193
+ sparse_structure_sampler_params={
194
+ "steps": min(ss_sampling_steps, 15),
195
+ "cfg_strength": ss_guidance_strength,
196
+ },
197
+ slat_sampler_params={
198
+ "steps": min(slat_sampling_steps, 15),
199
+ "cfg_strength": slat_guidance_strength,
200
+ }
201
+ )
202
 
203
  video = render_utils.render_video(outputs['gaussian'][0], num_frames=30)['color']
204
  video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=30)['normal']
 
211
 
212
  state = pack_state(outputs['gaussian'][0], outputs['mesh'][0], trial_id)
213
 
214
+ if torch.cuda.is_available():
215
+ pipeline.to("cpu")
216
 
217
  return state, video_path
218
 
219
  except Exception as e:
220
  print(f"Error in image_to_3d: {str(e)}")
221
+ if torch.cuda.is_available():
222
+ pipeline.to("cpu")
223
  raise e
224
 
225
  @spaces.GPU