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

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

Comments

Loading...