Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

FacesetEnhancer.py 6.0 KB

You have to be logged in to leave a comment. Sign In
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
  1. import multiprocessing
  2. import shutil
  3. from DFLIMG import *
  4. from interact import interact as io
  5. from joblib import Subprocessor
  6. from nnlib import nnlib
  7. from utils import Path_utils
  8. from utils.cv2_utils import *
  9. class FacesetEnhancerSubprocessor(Subprocessor):
  10. #override
  11. def __init__(self, image_paths, output_dirpath, multi_gpu=False, cpu_only=False):
  12. self.image_paths = image_paths
  13. self.output_dirpath = output_dirpath
  14. self.result = []
  15. self.devices = FacesetEnhancerSubprocessor.get_devices_for_config(multi_gpu, cpu_only)
  16. super().__init__('FacesetEnhancer', FacesetEnhancerSubprocessor.Cli, 600)
  17. #override
  18. def on_clients_initialized(self):
  19. io.progress_bar (None, len (self.image_paths))
  20. #override
  21. def on_clients_finalized(self):
  22. io.progress_bar_close()
  23. #override
  24. def process_info_generator(self):
  25. base_dict = {'output_dirpath':self.output_dirpath}
  26. for (device_idx, device_type, device_name, device_total_vram_gb) in self.devices:
  27. client_dict = base_dict.copy()
  28. client_dict['device_idx'] = device_idx
  29. client_dict['device_name'] = device_name
  30. client_dict['device_type'] = device_type
  31. yield client_dict['device_name'], {}, client_dict
  32. #override
  33. def get_data(self, host_dict):
  34. if len (self.image_paths) > 0:
  35. return self.image_paths.pop(0)
  36. #override
  37. def on_data_return (self, host_dict, data):
  38. self.image_paths.insert(0, data)
  39. #override
  40. def on_result (self, host_dict, data, result):
  41. io.progress_bar_inc(1)
  42. if result[0] == 1:
  43. self.result +=[ (result[1], result[2]) ]
  44. #override
  45. def get_result(self):
  46. return self.result
  47. @staticmethod
  48. def get_devices_for_config (multi_gpu, cpu_only):
  49. backend = nnlib.device.backend
  50. if 'cpu' in backend:
  51. cpu_only = True
  52. if not cpu_only and backend == "plaidML":
  53. cpu_only = True
  54. if not cpu_only:
  55. devices = []
  56. if multi_gpu:
  57. devices = nnlib.device.getValidDevicesWithAtLeastTotalMemoryGB(2)
  58. if len(devices) == 0:
  59. idx = nnlib.device.getBestValidDeviceIdx()
  60. if idx != -1:
  61. devices = [idx]
  62. if len(devices) == 0:
  63. cpu_only = True
  64. result = []
  65. for idx in devices:
  66. dev_name = nnlib.device.getDeviceName(idx)
  67. dev_vram = nnlib.device.getDeviceVRAMTotalGb(idx)
  68. result += [ (idx, 'GPU', dev_name, dev_vram) ]
  69. return result
  70. if cpu_only:
  71. return [ (i, 'CPU', 'CPU%d' % (i), 0 ) for i in range( min(8, multiprocessing.cpu_count() // 2) ) ]
  72. class Cli(Subprocessor.Cli):
  73. #override
  74. def on_initialize(self, client_dict):
  75. device_idx = client_dict['device_idx']
  76. cpu_only = client_dict['device_type'] == 'CPU'
  77. self.output_dirpath = client_dict['output_dirpath']
  78. device_config = nnlib.DeviceConfig ( cpu_only=cpu_only, force_gpu_idx=device_idx, allow_growth=True)
  79. nnlib.import_all (device_config)
  80. device_vram = device_config.gpu_vram_gb[0]
  81. intro_str = 'Running on %s.' % (client_dict['device_name'])
  82. if not cpu_only and device_vram <= 2:
  83. intro_str += " Recommended to close all programs using this device."
  84. self.log_info (intro_str)
  85. from facelib import FaceEnhancer
  86. self.fe = FaceEnhancer()
  87. #override
  88. def process_data(self, filepath):
  89. try:
  90. dflimg = DFLIMG.load (filepath)
  91. if dflimg is None:
  92. self.log_err ("%s is not a dfl image file" % (filepath.name) )
  93. else:
  94. img = cv2_imread(filepath).astype(np.float32) / 255.0
  95. img = self.fe.enhance(img)
  96. img = np.clip (img*255, 0, 255).astype(np.uint8)
  97. output_filepath = self.output_dirpath / filepath.name
  98. cv2_imwrite ( str(output_filepath), img, [int(cv2.IMWRITE_JPEG_QUALITY), 100] )
  99. dflimg.embed_and_set ( str(output_filepath) )
  100. return (1, filepath, output_filepath)
  101. except:
  102. self.log_err (f"Exception occured while processing file {filepath}. Error: {traceback.format_exc()}")
  103. return (0, filepath, None)
  104. def process_folder ( dirpath, multi_gpu=False, cpu_only=False ):
  105. output_dirpath = dirpath.parent / (dirpath.name + '_enhanced')
  106. output_dirpath.mkdir (exist_ok=True, parents=True)
  107. dirpath_parts = '/'.join( dirpath.parts[-2:])
  108. output_dirpath_parts = '/'.join( output_dirpath.parts[-2:] )
  109. io.log_info (f"Enhancing faceset in {dirpath_parts}")
  110. io.log_info ( f"Processing to {output_dirpath_parts}")
  111. output_images_paths = Path_utils.get_image_paths(output_dirpath)
  112. if len(output_images_paths) > 0:
  113. for filename in output_images_paths:
  114. Path(filename).unlink()
  115. image_paths = [Path(x) for x in Path_utils.get_image_paths( dirpath )]
  116. result = FacesetEnhancerSubprocessor ( image_paths, output_dirpath, multi_gpu=multi_gpu, cpu_only=cpu_only).run()
  117. is_merge = io.input_bool (f"\r\nMerge {output_dirpath_parts} to {dirpath_parts} ? (y/n skip:y) : ", True)
  118. if is_merge:
  119. io.log_info (f"Copying processed files to {dirpath_parts}")
  120. for (filepath, output_filepath) in result:
  121. try:
  122. shutil.copy (output_filepath, filepath)
  123. except:
  124. pass
  125. io.log_info (f"Removing {output_dirpath_parts}")
  126. shutil.rmtree(output_dirpath)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...