forked from PozzettiAndrea/ComfyUI-GeometryPack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblender_install.py
More file actions
303 lines (244 loc) · 9.5 KB
/
blender_install.py
File metadata and controls
303 lines (244 loc) · 9.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2025 ComfyUI-GeometryPack Contributors
"""
Blender Installer for ComfyUI-GeometryPack
Downloads and installs Blender for UV unwrapping and remeshing nodes.
Run this script manually if you need Blender functionality.
Usage:
python blender_install.py
"""
import os
import sys
import platform
import urllib.request
import tarfile
import zipfile
import shutil
import subprocess
from pathlib import Path
# Try to import optimized libraries, fallback to basic if not available
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
try:
from tqdm import tqdm
HAS_TQDM = True
except ImportError:
HAS_TQDM = False
def get_platform_info():
"""Detect current platform and architecture."""
system = platform.system().lower()
machine = platform.machine().lower()
if system == "darwin":
plat = "macos"
arch = "arm64" if machine == "arm64" else "x64"
elif system == "linux":
plat = "linux"
arch = "x64"
elif system == "windows":
plat = "windows"
arch = "x64"
else:
plat = None
arch = None
return plat, arch
def get_blender_download_url(platform_name, architecture):
"""
Get Blender 4.2 LTS download URL for the platform.
Returns:
tuple: (download_url, version, filename) or (None, None, None) if not found
"""
version = "4.2.3"
base_url = "https://download.blender.org/release/Blender4.2"
urls = {
("linux", "x64"): (
f"{base_url}/blender-{version}-linux-x64.tar.xz",
version,
f"blender-{version}-linux-x64.tar.xz"
),
("macos", "x64"): (
f"{base_url}/blender-{version}-macos-x64.dmg",
version,
f"blender-{version}-macos-x64.dmg"
),
("macos", "arm64"): (
f"{base_url}/blender-{version}-macos-arm64.dmg",
version,
f"blender-{version}-macos-arm64.dmg"
),
("windows", "x64"): (
f"{base_url}/blender-{version}-windows-x64.zip",
version,
f"blender-{version}-windows-x64.zip"
),
}
key = (platform_name, architecture)
if key in urls:
url, ver, filename = urls[key]
print(f"[Blender] Using Blender {ver} for {platform_name}-{architecture}")
return url, ver, filename
return None, None, None
def download_file_optimized(url, dest_path):
"""Download file with requests and tqdm for better performance and progress."""
print(f"[Blender] Downloading: {url}")
print(f"[Blender] Destination: {dest_path}")
try:
response = requests.get(url, stream=True, timeout=30)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
block_size = 8192
if HAS_TQDM:
with tqdm(total=total_size, unit='B', unit_scale=True, unit_divisor=1024) as pbar:
with open(dest_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=block_size):
if chunk:
f.write(chunk)
pbar.update(len(chunk))
else:
downloaded = 0
with open(dest_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=block_size):
if chunk:
f.write(chunk)
downloaded += len(chunk)
if total_size > 0:
percent = int(downloaded * 100 / total_size)
sys.stdout.write(f"\r[Blender] Progress: {percent}%")
sys.stdout.flush()
sys.stdout.write("\n")
print("[Blender] Download complete!")
return True
except Exception as e:
print(f"\n[Blender] Error downloading: {e}")
return False
def download_file(url, dest_path):
"""Download file with progress."""
if HAS_REQUESTS:
return download_file_optimized(url, dest_path)
print(f"[Blender] Downloading: {url}")
print(f"[Blender] Destination: {dest_path}")
def progress_hook(count, block_size, total_size):
percent = int(count * block_size * 100 / total_size)
sys.stdout.write(f"\r[Blender] Progress: {percent}%")
sys.stdout.flush()
try:
urllib.request.urlretrieve(url, dest_path, progress_hook)
sys.stdout.write("\n")
print("[Blender] Download complete!")
return True
except Exception as e:
print(f"\n[Blender] Error downloading: {e}")
return False
def extract_archive(archive_path, extract_to):
"""Extract tar.gz, tar.xz, zip, or handle DMG (macOS) - sequential only."""
print(f"[Blender] Extracting: {archive_path}")
try:
if archive_path.endswith('.tar.xz'):
print("[Blender] Extracting .tar.xz archive...")
with tarfile.open(archive_path, 'r:*') as tar:
if hasattr(tarfile, 'data_filter'):
tar.extractall(extract_to, filter='data')
else:
tar.extractall(extract_to)
elif archive_path.endswith(('.tar.gz', '.tar.bz2')):
print("[Blender] Extracting tar archive...")
with tarfile.open(archive_path, 'r:*') as tar:
if hasattr(tarfile, 'data_filter'):
tar.extractall(extract_to, filter='data')
else:
tar.extractall(extract_to)
elif archive_path.endswith('.zip'):
print("[Blender] Extracting .zip archive (this may take a moment)...")
with zipfile.ZipFile(archive_path, 'r') as zip_ref:
zip_ref.extractall(extract_to)
elif archive_path.endswith('.dmg'):
print("[Blender] DMG detected - mounting disk image...")
mount_result = subprocess.run(
['hdiutil', 'attach', '-nobrowse', archive_path],
capture_output=True,
text=True
)
if mount_result.returncode != 0:
print(f"[Blender] Error mounting DMG: {mount_result.stderr}")
return False
mount_point = None
for line in mount_result.stdout.split('\n'):
if '/Volumes/' in line:
mount_point = line.split('\t')[-1].strip()
break
if not mount_point:
print("[Blender] Error: Could not find mount point")
return False
try:
blender_app = Path(mount_point) / "Blender.app"
if blender_app.exists():
dest_app = Path(extract_to) / "Blender.app"
shutil.copytree(blender_app, dest_app)
print(f"[Blender] Copied Blender.app to: {dest_app}")
else:
print(f"[Blender] Error: Blender.app not found in {mount_point}")
return False
finally:
subprocess.run(['hdiutil', 'detach', mount_point], check=False)
else:
print(f"[Blender] Error: Unknown archive format: {archive_path}")
return False
print(f"[Blender] Extraction complete!")
return True
except Exception as e:
print(f"[Blender] Error extracting: {e}")
return False
def main():
"""Main installation function."""
print("\n" + "="*60)
print("ComfyUI-GeometryPack: Blender Installation")
print("="*60 + "\n")
script_dir = Path(__file__).parent.absolute()
blender_dir = script_dir / "_blender"
if blender_dir.exists():
print("[Blender] Blender directory already exists at:")
print(f"[Blender] {blender_dir}")
print("[Blender] Skipping download. Delete '_blender/' folder to reinstall.")
return True
plat, arch = get_platform_info()
if not plat or not arch:
print("[Blender] Error: Could not detect platform")
print("[Blender] Please install Blender manually from: https://www.blender.org/download/")
return False
print(f"[Blender] Detected platform: {plat}-{arch}")
url, version, filename = get_blender_download_url(plat, arch)
if not url:
print("[Blender] Error: Could not find Blender download for your platform")
print("[Blender] Please install Blender manually from: https://www.blender.org/download/")
return False
temp_dir = script_dir / "_temp_download"
temp_dir.mkdir(exist_ok=True)
try:
download_path = temp_dir / filename
if not download_file(url, str(download_path)):
return False
blender_dir.mkdir(exist_ok=True)
if not extract_archive(str(download_path), str(blender_dir)):
return False
print("\n[Blender] Installation complete!")
print(f"[Blender] Location: {blender_dir}")
if plat == "windows":
blender_exe = list(blender_dir.rglob("blender.exe"))
else:
blender_exe = list(blender_dir.rglob("blender"))
if blender_exe:
print(f"[Blender] Blender executable: {blender_exe[0]}")
return True
except Exception as e:
print(f"\n[Blender] Error during installation: {e}")
return False
finally:
if temp_dir.exists():
print("[Blender] Cleaning up temporary files...")
shutil.rmtree(temp_dir, ignore_errors=True)
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)