forked from deepfakes/faceswap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
executable file
·1615 lines (1401 loc) · 65.9 KB
/
setup.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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
""" Install packages for faceswap.py """
# pylint: disable=too-many-lines
import logging
import ctypes
import json
import locale
import platform
import operator
import os
import re
import sys
from shutil import which
from subprocess import list2cmdline, PIPE, Popen, run, STDOUT
from typing import Any, Dict, List, Optional, Set, Tuple, Type
from pkg_resources import parse_requirements, Requirement
from lib.logger import log_setup
if sys.version_info < (3, 8):
from typing_extensions import Literal
else:
from typing import Literal
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
_INSTALL_FAILED = False
# Revisions of tensorflow GPU and cuda/cudnn requirements. These relate specifically to the
# Tensorflow builds available from pypi
_TENSORFLOW_REQUIREMENTS = {">=2.7.0,<2.11.0": ["11.2", "8.1"]}
# ROCm min/max version requirements for Tensorflow
_TENSORFLOW_ROCM_REQUIREMENTS = {">=2.10.0,<2.11.0": ((5, 2, 0), (5, 4, 0))}
# TODO tensorflow-metal versioning
# Packages that are explicitly required for setup.py
_INSTALLER_REQUIREMENTS: List[Tuple[str, str]] = [("pexpect>=4.8.0", "!Windows"),
("pywinpty==2.0.2", "Windows")]
# Mapping of Python packages to their conda names if different from pip or in non-default channel
_CONDA_MAPPING: Dict[str, Tuple[str, str]] = {
# "opencv-python": ("opencv", "conda-forge"), # Periodic issues with conda-forge opencv
"fastcluster": ("fastcluster", "conda-forge"),
"imageio-ffmpeg": ("imageio-ffmpeg", "conda-forge"),
"scikit-learn": ("scikit-learn", "conda-forge"), # Exists in Default but is dependency hell
"tensorflow-deps": ("tensorflow-deps", "apple"),
"libblas": ("libblas", "conda-forge")}
# Packages that should be installed first to prevent version conflicts
_PRIORITY = ["numpy"]
class Environment():
""" The current install environment
Parameters
----------
updater: bool, Optional
``True`` if the script is being called by Faceswap's internal updater. ``False`` if full
setup is running. Default: ``False``
"""
_backends = (("nvidia", "amd", "apple_silicon", "directml", "rocm", "cpu"))
def __init__(self, updater: bool = False) -> None:
self.updater = updater
# Flag that setup is being run by installer so steps can be skipped
self.is_installer: bool = False
self.backend: Optional[Literal["nvidia", "amd", "apple_silicon",
"directml", "cpu", "rocm"]] = None
self.enable_docker: bool = False
self.cuda_cudnn = ["", ""]
self.rocm_version: Tuple[int, ...] = (0, 0, 0)
self._process_arguments()
self._check_permission()
self._check_system()
self._check_python()
self._output_runtime_info()
self._check_pip()
self._upgrade_pip()
self._set_env_vars()
self._packages = Packages(self)
@property
def encoding(self) -> str:
""" Get system encoding """
return locale.getpreferredencoding()
@property
def os_version(self) -> Tuple[str, str]:
""" Get OS Version """
return platform.system(), platform.release()
@property
def py_version(self) -> Tuple[str, str]:
""" Get Python Version """
return platform.python_version(), platform.architecture()[0]
@property
def is_conda(self) -> bool:
""" Check whether using Conda """
return ("conda" in sys.version.lower() or
os.path.exists(os.path.join(sys.prefix, 'conda-meta')))
@property
def is_admin(self) -> bool:
""" Check whether user is admin """
try:
retval = os.getuid() == 0 # type: ignore
except AttributeError:
retval = ctypes.windll.shell32.IsUserAnAdmin() != 0 # type: ignore
return retval
@property
def cuda_version(self) -> str:
""" str: The detected globally installed Cuda Version """
return self.cuda_cudnn[0]
@property
def cudnn_version(self) -> str:
""" str: The detected globally installed cuDNN Version """
return self.cuda_cudnn[1]
@property
def is_virtualenv(self) -> bool:
""" Check whether this is a virtual environment """
if not self.is_conda:
retval = (hasattr(sys, "real_prefix") or
(hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix))
else:
prefix = os.path.dirname(sys.prefix)
retval = (os.path.basename(prefix) == "envs")
return retval
def _process_arguments(self) -> None:
""" Process any cli arguments and dummy in cli arguments if calling from updater. """
args = [arg for arg in sys.argv] # pylint:disable=unnecessary-comprehension
if self.updater:
from lib.utils import get_backend # pylint:disable=import-outside-toplevel
args.append(f"--{get_backend()}")
logger.debug(args)
for arg in args:
if arg == "--installer":
self.is_installer = True
if not self.backend and (arg.startswith("--") and
arg.replace("--", "") in self._backends):
self.backend = arg.replace("--", "").lower() # type:ignore
def _check_permission(self) -> None:
""" Check for Admin permissions """
if self.updater:
return
if self.is_admin:
logger.info("Running as Root/Admin")
else:
logger.info("Running without root/admin privileges")
def _check_system(self) -> None:
""" Check the system """
if not self.updater:
logger.info("The tool provides tips for installation and installs required python "
"packages")
logger.info("Setup in %s %s", self.os_version[0], self.os_version[1])
if not self.updater and not self.os_version[0] in ["Windows", "Linux", "Darwin"]:
logger.error("Your system %s is not supported!", self.os_version[0])
sys.exit(1)
if self.os_version[0].lower() == "darwin" and platform.machine() == "arm64":
self.backend = "apple_silicon"
if not self.updater and not self.is_conda:
logger.error("Setting up Faceswap for Apple Silicon outside of a Conda "
"environment is unsupported")
sys.exit(1)
def _check_python(self) -> None:
""" Check python and virtual environment status """
logger.info("Installed Python: %s %s", self.py_version[0], self.py_version[1])
if self.updater:
return
if not ((3, 7) <= sys.version_info < (3, 10) and self.py_version[1] == "64bit"):
logger.error("Please run this script with Python version 3.7 to 3.9 64bit and try "
"again.")
sys.exit(1)
if self.backend == "amd" and sys.version_info >= (3, 9):
logger.error("The AMD version of Faceswap cannot be installed on versions of Python "
"higher than 3.8")
sys.exit(1)
def _output_runtime_info(self) -> None:
""" Output run time info """
if self.is_conda:
logger.info("Running in Conda")
if self.is_virtualenv:
logger.info("Running in a Virtual Environment")
logger.info("Encoding: %s", self.encoding)
def _check_pip(self) -> None:
""" Check installed pip version """
if self.updater:
return
try:
import pip # noqa pylint:disable=unused-import,import-outside-toplevel
except ImportError:
logger.error("Import pip failed. Please Install python3-pip and try again")
sys.exit(1)
def _upgrade_pip(self) -> None:
""" Upgrade pip to latest version """
if not self.is_conda:
# Don't do this with Conda, as we must use Conda version of pip
logger.info("Upgrading pip...")
pipexe = [sys.executable, "-m", "pip"]
pipexe.extend(["install", "--no-cache-dir", "-qq", "--upgrade"])
if not self.is_admin and not self.is_virtualenv:
pipexe.append("--user")
pipexe.append("pip")
run(pipexe, check=True)
import pip # pylint:disable=import-outside-toplevel
pip_version = pip.__version__
logger.info("Installed pip: %s", pip_version)
def set_config(self) -> None:
""" Set the backend in the faceswap config file """
config = {"backend": self.backend}
pypath = os.path.dirname(os.path.realpath(__file__))
config_file = os.path.join(pypath, "config", ".faceswap")
with open(config_file, "w", encoding="utf8") as cnf:
json.dump(config, cnf)
logger.info("Faceswap config written to: %s", config_file)
def _set_env_vars(self) -> None:
""" There are some foibles under Conda which need to be worked around in different
situations.
Linux:
Update the LD_LIBRARY_PATH environment variable when activating a conda environment
and revert it when deactivating.
Windows + AMD + Python 3.8:
Add CONDA_DLL_SEARCH_MODIFICATION_ENABLE=1 environment variable to get around a bug which
prevents SciPy from loading in this config: https://github.com/scipy/scipy/issues/14002
Notes
-----
From Tensorflow 2.7, installing Cuda Toolkit from conda-forge and tensorflow from pip
causes tensorflow to not be able to locate shared libs and hence not use the GPU.
We update the environment variable for all instances using Conda as it shouldn't hurt
anything and may help avoid conflicts with globally installed Cuda
"""
if not self.is_conda:
return
linux_update = self.os_version[0].lower() == "linux" and self.backend == "nvidia"
windows_update = (self.os_version[0].lower() == "windows" and
self.backend == "amd" and (3, 8) <= sys.version_info < (3, 9))
if not linux_update and not windows_update:
return
conda_prefix = os.environ["CONDA_PREFIX"]
activate_folder = os.path.join(conda_prefix, "etc", "conda", "activate.d")
deactivate_folder = os.path.join(conda_prefix, "etc", "conda", "deactivate.d")
os.makedirs(activate_folder, exist_ok=True)
os.makedirs(deactivate_folder, exist_ok=True)
ext = ".bat" if windows_update else ".sh"
activate_script = os.path.join(conda_prefix, activate_folder, f"env_vars{ext}")
deactivate_script = os.path.join(conda_prefix, deactivate_folder, f"env_vars{ext}")
if os.path.isfile(activate_script):
# Only create file if it does not already exist. There may be instances where people
# have created their own scripts, but these should be few and far between and those
# people should already know what they are doing.
return
if linux_update:
conda_libs = os.path.join(conda_prefix, "lib")
activate = ["#!/bin/sh\n\n",
"export OLD_LD_LIBRARY_PATH=${LD_LIBRARY_PATH}\n",
f"export LD_LIBRARY_PATH='{conda_libs}':${{LD_LIBRARY_PATH}}\n"]
deactivate = ["#!/bin/sh\n\n",
"export LD_LIBRARY_PATH=${OLD_LD_LIBRARY_PATH}\n",
"unset OLD_LD_LIBRARY_PATH\n"]
logger.info("Cuda search path set to '%s'", conda_libs)
if windows_update:
activate = ["@ECHO OFF\n",
"set CONDA_DLL_SEARCH_MODIFICATION_ENABLE=1\n"]
deactivate = ["@ECHO OFF\n",
"set CONDA_DLL_SEARCH_MODIFICATION_ENABLE=\n"]
logger.verbose("CONDA_DLL_SEARCH_MODIFICATION_ENABLE set to 1") # type: ignore
with open(activate_script, "w", encoding="utf8") as afile:
afile.writelines(activate)
with open(deactivate_script, "w", encoding="utf8") as afile:
afile.writelines(deactivate)
class Packages():
""" Holds information about installed and required packages.
Handles updating dependencies based on running platform/backend
Parameters
----------
environment: :class:`Environment`
Environment class holding information about the running system
"""
def __init__(self, environment: Environment) -> None:
self._env = environment
self._conda_required_packages: List[Tuple[str, ...]] = [("tk", )]
if self._env.os_version[0] == "Linux":
# TODO Put these kind of dependencies somewhere more visible or remove when not needed
# conda-forge scipy requires GLIBCXX_3.4.30. Some Linux install do not have the
# specific version, so we install it just in case.
# Ref: https://forum.faceswap.dev/viewtopic.php?f=7&t=2247
self._conda_required_packages.append(("gcc=12.1.0", "conda-forge"))
self._installed_packages = self._get_installed_packages()
self._conda_installed_packages = self._get_installed_conda_packages()
self._required_packages: List[Tuple[str, List[Tuple[str, str]]]] = []
self._missing_packages: List[Tuple[str, List[Tuple[str, str]]]] = []
self._conda_missing_packages: List[Tuple[str, ...]] = []
@property
def prerequisites(self) -> List[Tuple[str, List[Tuple[str, str]]]]:
""" list: Any required packages that the installer needs prior to installing the faceswap
environment on the specific platform that are not already installed """
all_installed = self._all_installed_packages
candidates = self._format_requirements(
[pkg for pkg, plat in _INSTALLER_REQUIREMENTS
if self._env.os_version[0] == plat or (plat[0] == "!" and
self._env.os_version[0] != plat[1:])])
retval = [(pkg, spec) for pkg, spec in candidates
if pkg not in all_installed or (
pkg in all_installed and
not self._validate_spec(spec, all_installed.get(pkg, ""))
)]
return retval
@property
def packages_need_install(self) -> bool:
"""bool: ``True`` if there are packages available that need to be installed """
return bool(self._missing_packages or self._conda_missing_packages)
@property
def to_install(self) -> List[Tuple[str, List[Tuple[str, str]]]]:
""" list: The required packages that need to be installed """
return self._missing_packages
@property
def to_install_conda(self) -> List[Tuple[str, ...]]:
""" list: The required conda packages that need to be installed """
return self._conda_missing_packages
@property
def _all_installed_packages(self) -> Dict[str, str]:
""" dict[str, str]: The package names and version string for all installed packages across
pip and conda """
return {**self._installed_packages, **self._conda_installed_packages}
@classmethod
def _format_requirements(cls, packages: List[str]) -> List[Tuple[str, List[Tuple[str, str]]]]:
""" Parse a list of requirements.txt formatted package strings to a list of pkgresource
formatted requirements """
return [(package.unsafe_name, package.specs)
for package in parse_requirements(packages)
if package.marker is None or package.marker.evaluate()]
@classmethod
def _validate_spec(cls,
required: List[Tuple[str, str]],
existing: str) -> bool:
""" Validate whether the required specification for a package is met by the installed
version.
required: list[tuple[str, str]]
The required package version spec to check
existing: str
The version of the installed package
Returns
-------
bool
``True`` if the required specification is met by the existing specification
"""
ops = {"==": operator.eq, ">=": operator.ge, "<=": operator.le,
">": operator.gt, "<": operator.lt}
if not required:
return True
return all(ops[spec[0]]([int(s) for s in existing.split(".")],
[int(s) for s in spec[1].split(".")])
for spec in required)
def _get_installed_packages(self) -> Dict[str, str]:
""" Get currently installed packages and add to :attr:`_installed_packages`
Returns
-------
dict[str, str]
The installed package name and version string
"""
installed_packages = {}
with Popen(f"\"{sys.executable}\" -m pip freeze --local", shell=True, stdout=PIPE) as chk:
installed = chk.communicate()[0].decode(self._env.encoding,
errors="ignore").splitlines()
for pkg in installed:
if "==" not in pkg:
continue
item = pkg.split("==")
installed_packages[item[0]] = item[1]
logger.debug(installed_packages)
return installed_packages
def _get_installed_conda_packages(self) -> Dict[str, str]:
""" Get currently installed conda packages
Returns
-------
dict[str, str]
The installed package name and version string
"""
if not self._env.is_conda:
return {}
chk = os.popen("conda list").read()
installed = [re.sub(" +", " ", line.strip())
for line in chk.splitlines() if not line.startswith("#")]
retval = {}
for pkg in installed:
item = pkg.split(" ")
retval[item[0]] = item[1]
logger.debug(retval)
return retval
def get_required_packages(self) -> None:
""" Load the requirements from the backend specific requirements list """
req_files = ["_requirements_base.txt", f"requirements_{self._env.backend}.txt"]
pypath = os.path.dirname(os.path.realpath(__file__))
requirements = []
for req_file in req_files:
requirements_file = os.path.join(pypath, "requirements", req_file)
with open(requirements_file, encoding="utf8") as req:
for package in req.readlines():
package = package.strip()
if package and (not package.startswith(("#", "-r"))):
requirements.append(package)
self._required_packages = self._format_requirements(requirements)
logger.debug(self._required_packages)
def _update_tf_dep_nvidia(self) -> None:
""" Update the Tensorflow dependency for global Cuda installs """
if self._env.is_conda: # Conda handles Cuda and cuDNN so nothing to do here
return
tf_ver = None
cudnn_inst = self._env.cudnn_version.split(".")
for key, val in _TENSORFLOW_REQUIREMENTS.items():
cuda_req = val[0]
cudnn_req = val[1].split(".")
if cuda_req == self._env.cuda_version and (cudnn_req[0] == cudnn_inst[0] and
cudnn_req[1] <= cudnn_inst[1]):
tf_ver = key
break
if tf_ver:
# Remove the version of tensorflow in requirements file and add the correct version
# that corresponds to the installed Cuda/cuDNN versions
self._required_packages = [pkg for pkg in self._required_packages
if not pkg[0].startswith("tensorflow-gpu")]
tf_ver = f"tensorflow-gpu{tf_ver}"
tf_ver = f"tensorflow-gpu{tf_ver}"
self._required_packages.append(("tensorflow-gpu",
next(parse_requirements(tf_ver)).specs))
return
logger.warning(
"The minimum Tensorflow requirement is 2.8 \n"
"Tensorflow currently has no official prebuild for your CUDA, cuDNN combination.\n"
"Either install a combination that Tensorflow supports or build and install your own "
"tensorflow-gpu.\r\n"
"CUDA Version: %s\r\n"
"cuDNN Version: %s\r\n"
"Help:\n"
"Building Tensorflow: https://www.tensorflow.org/install/install_sources\r\n"
"Tensorflow supported versions: "
"https://www.tensorflow.org/install/source#tested_build_configurations",
self._env.cuda_version, self._env.cudnn_version)
custom_tf = input("Location of custom tensorflow-gpu wheel (leave "
"blank to manually install): ")
if not custom_tf:
return
custom_tf = os.path.realpath(os.path.expanduser(custom_tf))
global _INSTALL_FAILED # pylint:disable=global-statement
if not os.path.isfile(custom_tf):
logger.error("%s not found", custom_tf)
_INSTALL_FAILED = True
elif os.path.splitext(custom_tf)[1] != ".whl":
logger.error("%s is not a valid pip wheel", custom_tf)
_INSTALL_FAILED = True
elif custom_tf:
self._required_packages.append((custom_tf, [(custom_tf, "")]))
def _update_tf_dep_rocm(self) -> None:
""" Update the Tensorflow dependency for global ROCm installs """
if not any(self._env.rocm_version): # ROCm was not found and the install will be aborted
return
global _INSTALL_FAILED # pylint:disable=global-statement
candidates = [key for key, val in _TENSORFLOW_ROCM_REQUIREMENTS.items()
if val[0] <= self._env.rocm_version <= val[1]]
if not candidates:
_INSTALL_FAILED = True
logger.error("No matching Tensorflow candidates found for ROCm %s in %s",
".".join(str(v) for v in self._env.rocm_version),
_TENSORFLOW_ROCM_REQUIREMENTS)
return
# set tf_ver to the minimum and maximum compatible range
tf_ver = f"{candidates[0].split(',')[0]},{candidates[-1].split(',')[-1]}"
# Remove the version of tensorflow-rocm in requirements file and add the correct version
# that corresponds to the installed ROCm version
self._required_packages = [pkg for pkg in self._required_packages
if not pkg[0].startswith("tensorflow-rocm")]
tf_ver = f"tensorflow-rocm{tf_ver}"
self._required_packages.append(("tensorflow-rocm",
next(parse_requirements(tf_ver)).specs))
def update_tf_dep(self) -> None:
""" Update Tensorflow Dependency.
Selects a compatible version of Tensorflow for a globally installed GPU library
"""
if self._env.backend == "nvidia":
self._update_tf_dep_nvidia()
if self._env.backend == "rocm":
self._update_tf_dep_rocm()
def _check_conda_missing_dependencies(self) -> None:
""" Check for conda missing dependencies and add to :attr:`_conda_missing_packages` """
if not self._env.is_conda:
return
for pkg in self._conda_required_packages:
key = pkg[0].split("==", maxsplit=1)[0]
if key not in self._conda_installed_packages:
self._conda_missing_packages.append(pkg)
continue
if len(pkg[0].split("==")) > 1:
if pkg[0].split("==")[1] != self._conda_installed_packages.get(key):
self._conda_missing_packages.append(pkg)
continue
logger.debug(self._conda_missing_packages)
def check_missing_dependencies(self) -> None:
""" Check for missing dependencies and add to :attr:`_missing_packages` """
for key, specs in self._required_packages:
if self._env.is_conda: # Get Conda alias for Key
key = _CONDA_MAPPING.get(key, (key, None))[0]
if key not in self._all_installed_packages:
# Add not installed packages to missing packages list
self._missing_packages.append((key, specs))
continue
if not self._validate_spec(specs, self._all_installed_packages.get(key, "")):
self._missing_packages.append((key, specs))
for priority in reversed(_PRIORITY):
# Put priority packages at beginning of list
package = next((pkg for pkg in self._missing_packages if pkg[0] == priority), None)
if package:
idx = self._missing_packages.index(package)
self._missing_packages.insert(0, self._missing_packages.pop(idx))
logger.debug(self._missing_packages)
self._check_conda_missing_dependencies()
class Checks(): # pylint:disable=too-few-public-methods
""" Pre-installation checks
Parameters
----------
environment: :class:`Environment`
Environment class holding information about the running system
"""
def __init__(self, environment: Environment) -> None:
self._env: Environment = environment
self._tips: Tips = Tips()
# Checks not required for installer
if self._env.is_installer:
return
# Checks not required for Apple Silicon
if self._env.backend == "apple_silicon":
return
self._user_input()
self._check_cuda()
self._check_rocm()
if self._env.os_version[0] == "Windows":
self._tips.pip()
def _rocm_ask_enable(self) -> None:
""" Set backend to 'rocm' if OS is Linux and ROCm support required """
if self._env.os_version[0] != "Linux":
return
logger.info("ROCm support:\r\nIf you are using an AMD GPU, then select 'yes'."
"\r\nCPU/non-AMD GPU users should answer 'no'.\r\n")
i = input("Enable ROCm Support? [y/N] ")
if i in ("Y", "y"):
logger.info("ROCm Support Enabled")
self._env.backend = "rocm"
def _directml_ask_enable(self) -> None:
""" Set backend to 'directml' if OS is Windows and DirectML support required """
if self._env.os_version[0] != "Windows":
return
logger.info("DirectML support:\r\nIf you are using an AMD or Intel GPU, then select 'yes'."
"\r\nNvidia users should answer 'no'.")
i = input("Enable DirectML Support? [y/N] ")
if i in ("Y", "y"):
logger.info("DirectML Support Enabled")
self._env.backend = "directml"
def _amd_ask_enable(self) -> None:
""" Set backend to 'amd' to use plaidML if AMD support required """
msg = ""
if self._env.os_version[0] == "Windows":
msg = "AMD users should select 'DirectML support' if possible.\r\n"
if self._env.os_version[0] == "Linux":
msg = "AMD users should select 'ROCm support' if possible.\r\n"
logger.info("AMD Support:\r\nThis version is deprecated and will be removed from a future "
"update.\r\n%s"
"Nvidia Users MUST answer 'no' to this option.", msg)
i = input("Enable AMD Support? [y/N] ")
if i in ("Y", "y"):
logger.info("AMD Support Enabled")
self._env.backend = "amd"
def _user_input(self) -> None:
""" Get user input for AMD/DirectML/ROCm/Cuda/Docker """
self._directml_ask_enable()
self._rocm_ask_enable()
if not self._env.backend:
self._amd_ask_enable()
if not self._env.backend:
self._docker_ask_enable()
self._cuda_ask_enable()
if self._env.os_version[0] != "Linux" and (self._env.enable_docker
and self._env.backend == "nvidia"):
self._docker_confirm()
if self._env.enable_docker:
self._docker_tips()
self._env.set_config()
sys.exit(0)
def _docker_ask_enable(self) -> None:
""" Enable or disable Docker """
i = input("Enable Docker? [y/N] ")
if i in ("Y", "y"):
logger.info("Docker Enabled")
self._env.enable_docker = True
else:
logger.info("Docker Disabled")
self._env.enable_docker = False
def _docker_confirm(self) -> None:
""" Warn if nvidia-docker on non-Linux system """
logger.warning("Nvidia-Docker is only supported on Linux.\r\n"
"Only CPU is supported in Docker for your system")
self._docker_ask_enable()
if self._env.enable_docker:
logger.warning("CUDA Disabled")
self._env.backend = "cpu"
def _docker_tips(self) -> None:
""" Provide tips for Docker use """
if self._env.backend != "nvidia":
self._tips.docker_no_cuda()
else:
self._tips.docker_cuda()
def _cuda_ask_enable(self) -> None:
""" Enable or disable CUDA """
i = input("Enable CUDA? [Y/n] ")
if i in ("", "Y", "y"):
logger.info("CUDA Enabled")
self._env.backend = "nvidia"
def _check_cuda(self) -> None:
""" Check for Cuda and cuDNN Locations. """
if self._env.backend != "nvidia":
logger.debug("Skipping Cuda checks as not enabled")
return
if self._env.is_conda:
logger.info("Skipping Cuda/cuDNN checks for Conda install")
return
if self._env.os_version[0] in ("Linux", "Windows"):
global _INSTALL_FAILED # pylint:disable=global-statement
check = CudaCheck()
if check.cuda_version:
self._env.cuda_cudnn[0] = check.cuda_version
logger.info("CUDA version: %s", self._env.cuda_version)
else:
logger.error("CUDA not found. Install and try again.\n"
"Recommended version: CUDA 10.1 cuDNN 7.6\n"
"CUDA: https://developer.nvidia.com/cuda-downloads\n"
"cuDNN: https://developer.nvidia.com/rdp/cudnn-download")
_INSTALL_FAILED = True
return
if check.cudnn_version:
self._env.cuda_cudnn[1] = ".".join(check.cudnn_version.split(".")[:2])
logger.info("cuDNN version: %s", self._env.cudnn_version)
else:
logger.error("cuDNN not found. See "
"https://github.com/deepfakes/faceswap/blob/master/INSTALL.md#"
"cudnn for instructions")
_INSTALL_FAILED = True
return
# If we get here we're on MacOS
self._tips.macos()
logger.warning("Cannot find CUDA on macOS")
self._env.cuda_cudnn[0] = input("Manually specify CUDA version: ")
def _check_rocm(self) -> None:
""" Check for ROCm version """
if self._env.backend != "rocm" or self._env.os_version[0] != "Linux":
logger.info("Skipping ROCm checks as not enabled")
return
global _INSTALL_FAILED # pylint:disable=global-statement
check = ROCmCheck()
str_min = ".".join(str(v) for v in check.version_min)
str_max = ".".join(str(v) for v in check.version_max)
if check.is_valid:
self._env.rocm_version = check.rocm_version
logger.info("ROCm version: %s", ".".join(str(v) for v in self._env.rocm_version))
else:
if check.rocm_version:
msg = f"Incompatible ROCm version: {'.'.join(str(v) for v in check.rocm_version)}"
else:
msg = "ROCm not found"
logger.error("%s.\n"
"A compatible version of ROCm must be installed to proceed.\n"
"ROCm versions between %s and %s are supported.\n"
"ROCm install guide: https://docs.amd.com/bundle/ROCm_Installation_Guide"
"v5.0/page/Overview_of_ROCm_Installation_Methods.html",
msg,
str_min,
str_max)
_INSTALL_FAILED = True
class ROCmCheck(): # pylint:disable=too-few-public-methods
""" Find the location of system installed ROCm on Linux """
def __init__(self) -> None:
self.version_min = min(v[0] for v in _TENSORFLOW_ROCM_REQUIREMENTS.values())
self.version_max = max(v[1] for v in _TENSORFLOW_ROCM_REQUIREMENTS.values())
self.rocm_version: Tuple[int, ...] = (0, 0, 0)
if platform.system() == "Linux":
self._rocm_check()
@property
def is_valid(self):
""" bool: `True` if ROCm has been detected and is between the minimum and maximum
compatible versions otherwise ``False`` """
return self.version_min <= self.rocm_version <= self.version_max
def _rocm_check(self) -> None:
""" Attempt to locate the installed ROCm version from the dynamic link loader. If not found
with ldconfig then attempt to find it in LD_LIBRARY_PATH. If found, set the
:attr:`rocm_version` to the discovered version
"""
chk = os.popen("ldconfig -p | grep -P \"librocm-core.so.\\d+\" | head -n 1").read()
if not chk and os.environ.get("LD_LIBRARY_PATH"):
for path in os.environ["LD_LIBRARY_PATH"].split(":"):
chk = os.popen(f"ls {path} | grep -P -o \"librocmcore.so.\\d+\" | "
"head -n 1").read()
if chk:
break
if not chk:
return
rocm_vers = chk.strip()
version = re.search(r"rocm\-(\d+\.\d+\.\d+)", rocm_vers)
if version is None:
return
try:
self.rocm_version = tuple(int(v) for v in version.groups()[0].split("."))
except ValueError:
return
class CudaCheck(): # pylint:disable=too-few-public-methods
""" Find the location of system installed Cuda and cuDNN on Windows and Linux. """
def __init__(self) -> None:
self.cuda_path: Optional[str] = None
self.cuda_version: Optional[str] = None
self.cudnn_version: Optional[str] = None
self._os: str = platform.system().lower()
self._cuda_keys: List[str] = [key
for key in os.environ
if key.lower().startswith("cuda_path_v")]
self._cudnn_header_files: List[str] = ["cudnn_version.h", "cudnn.h"]
logger.debug("cuda keys: %s, cudnn header files: %s",
self._cuda_keys, self._cudnn_header_files)
if self._os in ("windows", "linux"):
self._cuda_check()
self._cudnn_check()
def _cuda_check(self) -> None:
""" Obtain the location and version of Cuda and populate :attr:`cuda_version` and
:attr:`cuda_path`
Initially just calls `nvcc -V` to get the installed version of Cuda currently in use.
If this fails, drills down to more OS specific checking methods.
"""
with Popen("nvcc -V", shell=True, stdout=PIPE, stderr=PIPE) as chk:
stdout, stderr = chk.communicate()
if not stderr:
version = re.search(r".*release (?P<cuda>\d+\.\d+)",
stdout.decode(locale.getpreferredencoding(), errors="ignore"))
if version is not None:
self.cuda_version = version.groupdict().get("cuda", None)
locate = "where" if self._os == "windows" else "which"
path = os.popen(f"{locate} nvcc").read()
if path:
path = path.split("\n")[0] # Split multiple entries and take first found
while True: # Get Cuda root folder
path, split = os.path.split(path)
if split == "bin":
break
self.cuda_path = path
return
# Failed to load nvcc, manual check
getattr(self, f"_cuda_check_{self._os}")()
logger.debug("Cuda Version: %s, Cuda Path: %s", self.cuda_version, self.cuda_path)
def _cuda_check_linux(self) -> None:
""" For Linux check the dynamic link loader for libcudart. If not found with ldconfig then
attempt to find it in LD_LIBRARY_PATH. """
chk = os.popen("ldconfig -p | grep -P \"libcudart.so.\\d+.\\d+\" | head -n 1").read()
if not chk and os.environ.get("LD_LIBRARY_PATH"):
for path in os.environ["LD_LIBRARY_PATH"].split(":"):
chk = os.popen(f"ls {path} | grep -P -o \"libcudart.so.\\d+.\\d+\" | "
"head -n 1").read()
if chk:
break
if not chk: # Cuda not found
return
cudavers = chk.strip().replace("libcudart.so.", "")
self.cuda_version = cudavers[:cudavers.find(" ")]
self.cuda_path = chk[chk.find("=>") + 3:chk.find("targets") - 1]
def _cuda_check_windows(self) -> None:
""" Check Windows CUDA Version and path from Environment Variables"""
if not self._cuda_keys: # Cuda environment variable not found
return
self.cuda_version = self._cuda_keys[0].lower().replace("cuda_path_v", "").replace("_", ".")
self.cuda_path = os.environ[self._cuda_keys[0][0]]
def _cudnn_check(self):
""" Check Linux or Windows cuDNN Version from cudnn.h and add to :attr:`cudnn_version`. """
cudnn_checkfiles = getattr(self, f"_get_checkfiles_{self._os}")()
cudnn_checkfile = next((hdr for hdr in cudnn_checkfiles if os.path.isfile(hdr)), None)
logger.debug("cudnn checkfiles: %s", cudnn_checkfile)
if not cudnn_checkfile:
return
found = 0
with open(cudnn_checkfile, "r", encoding="utf8") as ofile:
for line in ofile:
if line.lower().startswith("#define cudnn_major"):
major = line[line.rfind(" ") + 1:].strip()
found += 1
elif line.lower().startswith("#define cudnn_minor"):
minor = line[line.rfind(" ") + 1:].strip()
found += 1
elif line.lower().startswith("#define cudnn_patchlevel"):
patchlevel = line[line.rfind(" ") + 1:].strip()
found += 1
if found == 3:
break
if found != 3: # Full version could not be determined
return
self.cudnn_version = ".".join([str(major), str(minor), str(patchlevel)])
logger.debug("cudnn version: %s", self.cudnn_version)
def _get_checkfiles_linux(self) -> List[str]:
""" Return the the files to check for cuDNN locations for Linux by querying
the dynamic link loader.
Returns
-------
list
List of header file locations to scan for cuDNN versions
"""
chk = os.popen("ldconfig -p | grep -P \"libcudnn.so.\\d+\" | head -n 1").read()
chk = chk.strip().replace("libcudnn.so.", "")
if not chk:
return []
cudnn_vers = chk[0]
header_files = [f"cudnn_v{cudnn_vers}.h"] + self._cudnn_header_files
cudnn_path = os.path.realpath(chk[chk.find("=>") + 3:chk.find("libcudnn") - 1])
cudnn_path = cudnn_path.replace("lib", "include")
cudnn_checkfiles = [os.path.join(cudnn_path, header) for header in header_files]
return cudnn_checkfiles
def _get_checkfiles_windows(self) -> List[str]:
""" Return the check-file locations for Windows. Just looks inside the include folder of
the discovered :attr:`cuda_path`
Returns
-------
list
List of header file locations to scan for cuDNN versions
"""
# TODO A more reliable way of getting the windows location
if not self.cuda_path:
return []
scandir = os.path.join(self.cuda_path, "include")
cudnn_checkfiles = [os.path.join(scandir, header) for header in self._cudnn_header_files]
return cudnn_checkfiles
class Install(): # pylint:disable=too-few-public-methods
""" Handles installation of Faceswap requirements
Parameters
----------
environment: :class:`Environment`
Environment class holding information about the running system
is_gui: bool, Optional
``True`` if the caller is the Faceswap GUI. Used to prevent output of progress bars
which get scrambled in the GUI
"""
def __init__(self, environment: Environment, is_gui: bool = False) -> None:
self._env = environment
self._packages = environment._packages
self._is_gui = is_gui
if self._env.os_version[0] == "Windows":
self._installer: Type[Installer] = WinPTYInstaller
else:
self._installer = PexpectInstaller
if not self._env.is_installer and not self._env.updater:
self._ask_continue()
self._packages.get_required_packages()
self._packages.update_tf_dep()
self._packages.check_missing_dependencies()
if self._env.updater and not self._packages.packages_need_install:
logger.info("All Dependencies are up to date")
return
logger.info("Installing Required Python Packages. This may take some time...")
self._install_setup_packages()
self._install_missing_dep()
if self._env.updater:
return
if not _INSTALL_FAILED:
logger.info("All python3 dependencies are met.\r\nYou are good to go.\r\n\r\n"
"Enter: 'python faceswap.py -h' to see the options\r\n"
" 'python faceswap.py gui' to launch the GUI")
else:
logger.error("Some packages failed to install. This may be a temporary error which "
"might be fixed by re-running this script. Otherwise please install "
"these packages manually.")
sys.exit(1)
def _ask_continue(self) -> None:
""" Ask Continue with Install """
text = "Please ensure your System Dependencies are met"
if self._env.backend == "rocm":
text += ("\r\nROCm users: Please ensure that your AMD GPU is supported by the "
"installed ROCm version before proceeding.")
text += "\r\nContinue? [y/N] "
inp = input(text)
if inp in ("", "N", "n"):
logger.error("Please install system dependencies to continue")