-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathuv.py
558 lines (459 loc) · 17.8 KB
/
uv.py
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
import re
import subprocess
import sys
from importlib import metadata
from pathlib import Path
from textwrap import dedent
from typing import Any, Optional, Union, cast
from comfy_cli import ui
from comfy_cli.constants import GPU_OPTION
from comfy_cli.typing import PathLike
def _run(cmd: list[str], cwd: PathLike, check: bool = True) -> subprocess.CompletedProcess[Any]:
return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, check=check)
def _check_call(cmd: list[str], cwd: Optional[PathLike] = None):
"""uses check_call to run pip, as reccomended by the pip maintainers.
see https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program"""
subprocess.check_call(cmd, cwd=cwd)
_req_name_re: re.Pattern[str] = re.compile(r"require\s([\w-]+)")
def _req_re_closure(name: str) -> re.Pattern[str]:
return re.compile(rf"({name}\S+)")
def parse_uv_compile_error(err: str) -> tuple[str, list[str]]:
"""takes in stderr from a run of `uv pip compile` that failed due to requirement conflict and spits out
a tuple of (reqiurement_name, [requirement_spec_in_conflict_a, requirement_spec_in_conflict_b]). Will probably
fail for stderr produced from other kinds of errors
"""
if reqNameMatch := _req_name_re.search(err):
reqName = reqNameMatch[1]
else:
raise ValueError
reqRe = _req_re_closure(reqName)
return reqName, cast(list[str], reqRe.findall(err))
def parse_req_file(rf: PathLike, skips: Optional[list[str]] = None):
skips = [] if skips is None else skips
reqs: list[str] = []
opts: list[str] = []
with open(rf) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
elif "==" in line and line.split("==")[0] in skips:
continue
elif line.startswith("--"):
opts.extend(line.split())
else:
reqs.append(line)
return opts + reqs
class DependencyCompiler:
rocmPytorchUrl = "https://download.pytorch.org/whl/rocm6.1"
nvidiaPytorchUrl = "https://download.pytorch.org/whl/cu126"
overrideGpu = dedent(
"""
# ensure usage of {gpu} version of pytorch
--extra-index-url {gpuUrl}
torch
torchaudio
torchsde
torchvision
"""
).strip()
reqNames = (
"requirements.txt",
"pyproject.toml",
"setup.cfg",
"setup.py",
)
@staticmethod
def Find_Req_Files(*ders: PathLike) -> list[Path]:
reqFiles = []
for der in ders:
reqFound = False
for reqName in DependencyCompiler.reqNames:
for file in Path(der).absolute().iterdir():
if file.name == reqName:
reqFiles.append(file)
reqFound = True
break
if reqFound:
break
return reqFiles
@staticmethod
def Install_Build_Deps(executable: PathLike = sys.executable):
"""Use pip to install bare minimum requirements for uv to do its thing"""
cmd = [str(executable), "-m", "pip", "install", "--upgrade", "pip", "uv"]
_check_call(cmd=cmd)
@staticmethod
def Compile(
cwd: PathLike,
reqFiles: list[PathLike],
emit_index_annotation: bool = True,
emit_index_url: bool = True,
executable: PathLike = sys.executable,
index_strategy: str = "unsafe-best-match",
out: Optional[PathLike] = None,
override: Optional[PathLike] = None,
resolve_strategy: Optional[str] = None,
) -> subprocess.CompletedProcess[Any]:
cmd = [
str(executable),
"-m",
"uv",
"pip",
"compile",
]
for reqFile in reqFiles:
cmd.append(str(reqFile))
if emit_index_annotation:
cmd.append("--emit-index-annotation")
if emit_index_url:
cmd.append("--emit-index-url")
# ensures that eg tqdm is latest version, even though an old tqdm is on the amd url
# see https://github.com/astral-sh/uv/blob/main/PIP_COMPATIBILITY.md#packages-that-exist-on-multiple-indexes and https://github.com/astral-sh/uv/issues/171
if index_strategy is not None:
cmd.extend(["--index-strategy", "unsafe-best-match"])
if out is not None:
cmd.extend(["-o", str(out)])
if override is not None:
cmd.extend(["--override", str(override)])
try:
return _run(cmd, cwd)
except subprocess.CalledProcessError as e:
print(e.__class__.__name__)
print(e)
print(f"STDOUT:\n{e.stdout}")
print(f"STDERR:\n{e.stderr}")
if resolve_strategy == "ask":
name, reqs = parse_uv_compile_error(e.stderr)
vers = [req.split(name)[1].strip(",") for req in reqs]
ver = ui.prompt_select(
"Please pick one of the conflicting version specs (or pick latest):",
choices=vers + ["latest"],
default=vers[0],
)
if ver == "latest":
req = name
else:
req = name + ver
e.req = req
elif resolve_strategy is not None:
# no other resolve_strategy options implemented yet
raise ValueError
raise e
@staticmethod
def Install(
cwd: PathLike,
executable: PathLike = sys.executable,
dry: bool = False,
extra_index_url: Optional[str] = None,
find_links: Optional[list[str]] = None,
index_strategy: Optional[str] = "unsafe-best-match",
no_deps: bool = False,
no_index: bool = False,
override: Optional[PathLike] = None,
reqs: Optional[list[str]] = None,
reqFile: Optional[list[PathLike]] = None,
) -> None:
cmd = [
str(executable),
"-m",
"uv",
"pip",
"install",
]
if dry:
cmd.append("--dry-run")
if extra_index_url is not None:
cmd.extend(["--extra-index-url", extra_index_url])
if find_links is not None:
for fl in find_links:
cmd.extend(["--find-links", fl])
if index_strategy is not None:
cmd.extend(["--index-strategy", "unsafe-best-match"])
if no_deps:
cmd.append("--no-deps")
if no_index:
cmd.append("--no-index")
if override is not None:
cmd.extend(["--override", str(override)])
if reqs is not None:
cmd.extend(reqs)
if reqFile is not None:
for rf in reqFile:
cmd.extend(["--requirement", rf])
return _check_call(cmd, cwd)
@staticmethod
def Sync(
cwd: PathLike,
reqFile: list[PathLike],
dry: bool = False,
executable: PathLike = sys.executable,
extraUrl: Optional[str] = None,
index_strategy: str = "unsafe-best-match",
) -> None:
cmd = [
str(executable),
"-m",
"uv",
"pip",
"sync",
str(reqFile),
]
if index_strategy is not None:
cmd.extend(["--index-strategy", "unsafe-best-match"])
if extraUrl is not None:
cmd.extend(["--extra-index-url", extraUrl])
if dry:
cmd.append("--dry-run")
return _check_call(cmd, cwd)
@staticmethod
def Download(
cwd: PathLike,
executable: PathLike = sys.executable,
extraUrl: Optional[str] = None,
noDeps: bool = False,
out: Optional[PathLike] = None,
reqs: Optional[list[str]] = None,
reqFile: Optional[list[PathLike]] = None,
) -> None:
"""For now, the `download` cmd has no uv support, so use pip"""
cmd = [
str(executable),
"-m",
"pip",
"download",
]
if extraUrl is not None:
cmd.extend(["--extra-index-url", extraUrl])
if noDeps:
cmd.append("--no-deps")
if out is not None:
cmd.extend(["-d", str(out)])
if reqs is not None:
cmd.extend(reqs)
if reqFile is not None:
for rf in reqFile:
cmd.extend(["--requirement", rf])
return _check_call(cmd, cwd)
@staticmethod
def Wheel(
cwd: PathLike,
executable: PathLike = sys.executable,
extraUrl: Optional[str] = None,
noDeps: bool = False,
out: Optional[PathLike] = None,
reqs: Optional[list[str]] = None,
reqFile: Optional[list[PathLike]] = None,
) -> None:
"""For now, the `wheel` cmd has no uv support, so use pip"""
cmd = [
str(executable),
"-m",
"pip",
"wheel",
]
if extraUrl is not None:
cmd.extend(["--extra-index-url", extraUrl])
if noDeps:
cmd.append("--no-deps")
if out is not None:
cmd.extend(["-w", str(out)])
if reqs is not None:
cmd.extend(reqs)
if reqFile is not None:
for rf in reqFile:
cmd.extend(["--requirement", rf])
return _check_call(cmd, cwd)
@staticmethod
def Resolve_Gpu(gpu: Union[GPU_OPTION, None]):
if gpu is None:
try:
tver = metadata.version("torch")
if "+cu" in tver:
return GPU_OPTION.NVIDIA
elif "+rocm" in tver:
return GPU_OPTION.AMD
else:
return None
except metadata.PackageNotFoundError:
return None
else:
return gpu
def __init__(
self,
cwd: PathLike = ".",
executable: PathLike = sys.executable,
gpu: Union[GPU_OPTION, None] = None,
outDir: PathLike = ".",
outName: str = "requirements.compiled",
reqFilesCore: Optional[list[PathLike]] = None,
reqFilesExt: Optional[list[PathLike]] = None,
extraSpecs: Optional[list[str]] = None,
):
"""Compiler/installer of Python dependencies based on uv
Args:
cwd (PathLike): should generally be a comfy workspace dir. Dir that is searched for dependency specification files, and where subprocesses are run in
executable (PathLike): path to Python executable used to run uv and other subprocesses
gpu (Union[GPU_OPTION, None]): the gpu against which pytorch and any related dependencies should be built against
outDir (PathLike): the directory in which to create any output from the compiler itself
outName (str): the name of the output file containing the compiled requirements
reqFilesCore (Optional[list[PathLike]]): list of core requirement files (requirements.txt, pyproject.toml, etc) to be included in the compilation. Any requirements determined from these files will override all other requirements
reqFilesExt (Optional[list[PathLike]]): list of requirement files (requirements.txt, pyproject.toml, etc) to be included in the compilation
extraSpecs (Optional[list[str]]): list of extra Python requirement specifiers to be included in the compilation
"""
self.cwd = Path(cwd).expanduser().resolve()
self.outDir: Path = Path(outDir).expanduser().resolve()
# use .absolute since .resolve breaks the softlink-is-interpreter assumption of venvs
self.executable = Path(executable).expanduser().absolute()
self.gpu = DependencyCompiler.Resolve_Gpu(gpu)
self.reqFiles = [Path(reqFile) for reqFile in reqFilesExt] if reqFilesExt is not None else None
self.extraSpecs = [] if extraSpecs is None else extraSpecs
self.gpuUrl = (
DependencyCompiler.nvidiaPytorchUrl if self.gpu == GPU_OPTION.NVIDIA else
DependencyCompiler.rocmPytorchUrl if self.gpu == GPU_OPTION.AMD else
None
) # fmt: skip
self.out: Path = self.outDir / outName
self.override = self.outDir / "override.txt"
self.reqFilesCore = reqFilesCore if reqFilesCore is not None else self.find_core_reqs()
self.reqFilesExt = reqFilesExt if reqFilesExt is not None else self.find_ext_reqs()
def find_core_reqs(self):
return DependencyCompiler.Find_Req_Files(self.cwd)
def find_ext_reqs(self):
extDirs = [d for d in (self.cwd / "custom_nodes").iterdir() if d.is_dir() and d.name != "__pycache__"]
return DependencyCompiler.Find_Req_Files(*extDirs)
def make_override(self):
# clean up
self.override.unlink(missing_ok=True)
with open(self.override, "w") as f:
if self.gpu is not None and self.gpuUrl is not None:
f.write(DependencyCompiler.overrideGpu.format(gpu=self.gpu, gpuUrl=self.gpuUrl))
f.write("\n\n")
f.write("numpy<2\n")
f.write("\n\n")
completed = DependencyCompiler.Compile(
cwd=self.cwd,
reqFiles=self.reqFilesCore,
emit_index_annotation=False,
emit_index_url=False,
executable=self.executable,
override=self.override,
)
with open(self.override, "a") as f:
f.write("# ensure that core comfyui deps take precedence over any 3rd party extension deps\n")
for line in completed.stdout:
f.write(line)
f.write("\n")
def compile_core_plus_ext(self):
reqExtras = self.outDir / "requirements.extra"
# clean up
reqExtras.unlink(missing_ok=True)
self.out.unlink(missing_ok=True)
# make the extra specs file
if self.extraSpecs:
with reqExtras.open("w") as f:
for spec in self.extraSpecs:
f.write(spec)
f.write("\n")
while True:
try:
DependencyCompiler.Compile(
cwd=self.cwd,
reqFiles=self.reqFilesCore + self.reqFilesExt + ([reqExtras] if self.extraSpecs else []),
executable=self.executable,
override=self.override,
out=self.out,
resolve_strategy="ask",
)
break
except subprocess.CalledProcessError as e:
if hasattr(e, "req"):
with open(self.override, "a") as f:
f.write(e.req + "\n")
else:
raise AttributeError
def handle_opencv(self):
"""as per the opencv docs, you should only have exactly one opencv package.
headless is more suitable for comfy than the gui version, so remove gui if
headless is present. TODO: add support for contrib pkgs. see: https://github.com/opencv/opencv-python"""
with open(self.out, "r") as f:
lines = f.readlines()
guiFound, headlessFound = False, False
for line in lines:
if "opencv-python==" in line:
guiFound = True
elif "opencv-python-headless==" in line:
headlessFound = True
if headlessFound and guiFound:
with open(self.out, "w") as f:
for line in lines:
if "opencv-python==" not in line:
f.write(line)
def compile_deps(self):
self.make_override()
self.compile_core_plus_ext()
self.handle_opencv()
def install_deps(self):
DependencyCompiler.Install(
cwd=self.cwd,
executable=self.executable,
extra_index_url=self.gpuUrl,
override=self.override,
reqFile=[self.out],
)
def install_dists(self):
DependencyCompiler.Install(
cwd=self.cwd,
executable=self.executable,
find_links=[self.outDir / "dists"],
no_deps=True,
no_index=True,
reqFile=[self.out],
)
def install_wheels(self):
DependencyCompiler.Install(
cwd=self.cwd,
executable=self.executable,
find_links=[self.outDir / "wheels"],
no_deps=True,
no_index=True,
reqFile=[self.out],
)
def install_wheels_directly(self):
DependencyCompiler.Install(
cwd=self.cwd,
executable=self.executable,
no_deps=True,
no_index=True,
reqs=(self.outDir / "wheels").glob("*.whl"),
)
def sync_core_plus_ext(self):
DependencyCompiler.Sync(
cwd=self.cwd,
reqFile=[self.out],
executable=self.executable,
extraUrl=self.gpuUrl,
)
def fetch_dep_dists(self, skip_uv: bool = False):
skips = ["uv"] if skip_uv else None
reqs = parse_req_file(self.out, skips=skips)
extraUrl = None if "--extra-index-url" in reqs else self.gpuUrl
DependencyCompiler.Download(
cwd=self.cwd,
executable=self.executable,
extraUrl=extraUrl,
noDeps=True,
out=self.outDir / "dists",
reqs=reqs,
)
def fetch_dep_wheels(self, skip_uv: bool = False):
skips = ["uv"] if skip_uv else None
reqs = parse_req_file(self.out, skips=skips)
extraUrl = None if "--extra-index-url" in reqs else self.gpuUrl
DependencyCompiler.Wheel(
cwd=self.cwd,
executable=self.executable,
extraUrl=extraUrl,
noDeps=True,
out=self.outDir / "wheels",
reqs=reqs,
)