-
Notifications
You must be signed in to change notification settings - Fork 7
/
facetool.py
executable file
·596 lines (485 loc) · 19.8 KB
/
facetool.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
#!/usr/bin/env python3
from dataknead import Knead
from facetool import config, media, util
from facetool.constants import *
from facetool.path import Path
from facetool.profiler import Profiler
from facetool.errors import ArgumentError
from facetool.util import message, force_mkdir, sample_remove, is_json_path
from random import random
from tqdm import tqdm
import argparse
import logging
import json
import os
import pandas as pd
import pdb
import shutil
import sys
COMMANDS = (
"average",
"classify",
"cluster",
"combineaudio",
"combineframes",
"count",
"distance",
"crop",
"encode",
"extractframes",
"landmarks",
"locate",
"pose",
"probe",
"sample",
"swap",
)
OUTPUT_FORMAT_CHOICES = (
"default",
"csv",
"json"
)
SWAP_METHODS = [
"faceswap",
"faceswap3d"
]
logger = logging.getLogger(__name__)
# Note that we always profile, we just don't print the output if the
# option is not enabled
profiler = Profiler("facetool.py")
def get_parser():
parser = argparse.ArgumentParser(description = "Manipulate faces in videos and images")
# Essentials
parser.add_argument("command", choices = COMMANDS, nargs = "?")
parser.add_argument("-i", "--input", type = str,
required = True,
help = "Input file or folder, 'face' when swapping"
)
parser.add_argument("-o", "--output", type = str,
help = "Output file or folder",
default = None
)
parser.add_argument("-t", "--target", type = str,
help = "'Head' when swapping"
)
# Extra arguments
parser.add_argument("-ai", "--audio-input", type = str,
default = None,
help = "Add a separate audio file with the end result movie"
)
parser.add_argument("--as-percentage", action = "store_true",
help = "Show face distances as percentages"
)
parser.add_argument("-bl", "--blur", type = float,
default = BLUR_AMOUNT,
help = "Amount of blur to use during colour correction"
)
parser.add_argument("-dd", "--data-directory", type = str,
default = DATA_DIRECTORY,
help = "Directory where the data files are located"
)
parser.add_argument("-f", "--force", action = "store_true",
help = "Force commands and ignore warnings, like with sample"
)
parser.add_argument("-fr", "--framerate", type = str,
default = DEFAULT_FRAMERATE
)
parser.add_argument("-fa", "--feather", type = int,
default = FEATHER_AMOUNT,
help = "Softness of edges on a swapped face"
)
parser.add_argument("-if", "--ignore-nofaces", action = "store_true",
default = False,
help = "When having no faces to swap, keep the original input image"
)
parser.add_argument("-ih", "--image-height", type = int,
default = DEFAULT_IMAGE_HEIGHT,
help = "Height of output image / height"
)
parser.add_argument("-iw", "--image-width", type = int,
default = DEFAULT_IMAGE_WIDTH,
help = "Width of output image / video"
)
parser.add_argument("-kt", "--keep-temp", action = "store_true",
help = "Keep temporary files (used with video swapping)"
)
parser.add_argument("-m", "--model", type = str,
help = "Use a precalculated model (for calculating distances)"
)
parser.add_argument("--no-audio", action = "store_true")
parser.add_argument("-nocc", "--no-colour-correct", action = "store_true",
help = "Don't colour correct"
)
parser.add_argument("--no-eyesbrows", action = "store_true")
parser.add_argument("--no-nosemouth", action = "store_true")
parser.add_argument("--no-threading", action = "store_true",
help = "Don't use multithreading"
)
parser.add_argument("--only-mouth", action="store_true")
parser.add_argument("-of", "--output-format",
choices = OUTPUT_FORMAT_CHOICES,
help = "Specify output format"
)
parser.add_argument("-pp", "--predictor-path", type = str,
default = PREDICTOR_PATH
)
parser.add_argument("--profile", action = "store_true",
help = "Show profiler information"
)
parser.add_argument("-q", "--quiet", action = "store_true",
help = "Don't print output to the console"
)
parser.add_argument("-s", "--swap", action = "store_true",
help = "Swap input and target"
)
parser.add_argument("--save-originals", action = "store_true",
help = "Save original images when averaging faces"
)
parser.add_argument("--save-warped", action = "store_true",
help = "Save warped images when averaging faces"
)
parser.add_argument("--swap-method",
choices = SWAP_METHODS,
default = SWAP_METHODS[0],
help = f"Swap method for faceswap (options are: {SWAP_METHODS}"
)
parser.add_argument("-so", "--swap-order", type = str,
help = "Comma-separated list with order of faceswaps on target, implies a multiswap"
)
parser.add_argument("-sp", "--sample-percentage", type = float,
help = "Percentage of files in a directory to randomly remove (used for the sample command)"
)
parser.add_argument("-sr", "--swap-order-repeat", action = "store_true", default = False,
help = "When using --swap-order and there are not enough target faces, repeat the sequence"
)
parser.add_argument("--temp-dir", type = str,
help = "Define the directory where temporary files should be placed"
)
parser.add_argument("-v", "--verbose", action = "store_true",
help = "Show debug information"
)
parser.add_argument("-vv", "--extra-verbose", action = "store_true",
help = "Show debug information AND raise / abort on exceptions"
)
parser.add_argument("--warp-3d", action="store_true",
help = "Swap faces and morph to coordinates of target face"
)
return parser
def main(args):
if args.verbose or args.extra_verbose:
logging.basicConfig(level=logging.DEBUG)
logging.debug(args)
config.PROFILE = args.profile
config.QUIET = args.quiet
config.VERBOSE = args.verbose or args.extra_verbose
# Check for invalid argument combinations
if any([args.output_format == "csv", args.output_format == "json"]) and not args.output:
raise ArgumentError("With CSV as output format, a filename (-o) is required")
# Swap around input and target
if args.swap:
args.input, args.target = args.target, args.input
# Okay, the main stuff, get the command
# Extract all frames from a movie to a set of jpg files
if args.command == "extractframes":
util.mkdir_if_not_exists(args.output)
media.extractframes(args.input, args.output)
# Combine all frames from a set of jpg files to a movie
elif args.command == "combineframes":
media.combineframes(args.input, args.output, framerate = args.framerate)
# Combine audio with an input movie
elif args.command == "combineaudio":
media.combineaudio(args.input, args.audio_input, args.output)
# Randomly remove (sample) a percentage of files from a given directory
elif args.command == "sample":
if not args.sample_percentage:
raise ArgumentError("The sample command needs a sample percentage (-sp)")
sample_remove(args.input, args.sample_percentage, force_delete = args.force)
# Show metadata on a media file
elif args.command == "probe":
try:
data = media.probe(args.input)
except:
raise ArgumentError(f"Could not probe '{args.input}', probably not a video/image file")
else:
jsondata = json.dumps(data, indent = 4)
message(jsondata)
elif args.command == "landmarks":
from facetool.landmarks import Landmarks
landmarks = Landmarks(predictor_path = args.predictor_path)
save_data = args.output_format and args.output_format != "default"
if save_data:
data = []
# Check if we *could* have an output directory, and if so,
# create it
if args.output and Path(args.output).could_be_dir():
Path(args.output).mkdir_if_not_exists()
for pathobj in Path(args.input).images():
path = str(pathobj)
logging.debug(f"Processing {path}")
logging.debug(f"Getting landmarks of {path}")
if not args.output:
outpath = None
else:
out = Path(args.output)
if out.is_dir():
outpath = f"{out}/{Path(path).name}"
else:
outpath = str(out)
marks = landmarks.get_landmarks(str(path), outpath = outpath)
if marks and save_data:
points = [str(path)]
[points.extend([m.x, m.y]) for m in marks]
data.append(points)
message(path, marks)
if save_data:
df = pd.DataFrame(data)
if args.output_format == "csv":
df.to_csv(args.output)
elif args.output_format == "json":
df.to_json(args.output)
else:
raise ArgumentError(f"Invalid output format: {args.output_format}")
elif args.command == "pose":
from facetool.poser import Poser
poser = Poser(predictor_path = args.predictor_path)
# Check if we *could* have an output directory, and if so,
# create it
if args.output and Path(args.output).could_be_dir():
Path(args.output).mkdir_if_not_exists()
for pathobj in Path(args.input).images():
path = str(pathobj)
logging.debug(f"Processing {path}")
if not args.output:
outpath = None
else:
out = Path(args.output)
if out.is_dir():
outpath = f"{out}/{Path(path).name}"
else:
outpath = str(out)
poses = poser.get_poses(path, outpath = outpath)
message(f"{path}: {poses}")
elif args.command == "count":
from facetool.detect import Detect
detect = Detect()
if args.output_format == "csv":
csv = []
for path in Path(args.input).images():
count = detect.count(path)
message(f"Number of faces in '{path}': {count}")
if args.output_format == "csv":
csv.append({
"path" : path,
"count" : count
})
if args.output_format == "csv":
df = pd.DataFrame(csv)
df.to_csv(args.output)
elif args.command == "locate":
from facetool.detect import Detect
detect = Detect()
for path in Path(args.input).images():
to_directory = os.path.isdir(args.input)
locations = detect.locate(path, args.output, to_directory = to_directory)
message(f"Face locations in '{args.input}': {locations}")
elif args.command == "crop":
from facetool.detect import Detect
from facetool.media import extractframes
# We can't crop to an image path, because an input image might
# have multiple faces, so throw an error in that case
if Path(args.output).is_image():
raise ArgumentError(f"Can't crop with an image as output")
detect = Detect()
# FIXME: we need some general mechanism for juggling frames around
TMP_DIR = "crop-tmp"
IS_VIDEO = Path(args.input).is_video()
logging.debug(f"Cropping. Input is video? {IS_VIDEO}")
if IS_VIDEO:
force_mkdir(TMP_DIR)
extractframes(args.input, TMP_DIR)
images = Path(TMP_DIR).images()
else:
images = Path(args.input).images()
for path in images:
logging.debug(f"Cropping <{path}>")
detect.crop(str(path), args.output)
if IS_VIDEO:
shutil.rmtree(TMP_DIR)
elif args.command == "classify":
from facetool.classifier import Classifier
classifier = Classifier(
data_directory = args.data_directory,
output_format = args.output_format,
predictor_path = args.predictor_path
)
for path in Path(args.input).images():
logging.debug(f"Classifying <{path}>")
classifier.classify(str(path))
if args.output_format == "csv":
classifier.to_csv(args.output)
elif args.command == "average":
from facetool.averager import Averager
profiler.tick("start averaging")
averager = Averager(
predictor_path = args.predictor_path,
img_height = args.image_height,
img_width = args.image_width,
save_originals = args.save_originals,
save_warped = args.save_warped
)
TMP_DIR = "average-tmp"
path = Path(args.input)
# If this is a video, extract all images and average those
if path.is_file() and path.is_video():
# First create a temporary directory to hold all frames
util.mkdir_if_not_exists(TMP_DIR)
media.extractframes(args.input, TMP_DIR)
# Now average
averager.average(TMP_DIR, args.output)
# And remove the temporary directory
logging.debug(f"Removing {TMP_DIR}")
shutil.rmtree(TMP_DIR)
# Not a video, so if it's a file it's probably an image
# extract all faces and average those
elif path.is_file():
# First create a temporary directory
util.mkdir_if_not_exists(TMP_DIR)
# Now extract all the images to said directory
from facetool.detect import Detect
detect = Detect()
logging.debug(f"Cropping <{args.input}> to {TMP_DIR}")
detect.crop(str(args.input), TMP_DIR)
# Average the stuff
averager.average(TMP_DIR, args.output)
# And remove the temporary directory
logging.debug(f"Removing {TMP_DIR}")
shutil.rmtree(TMP_DIR)
elif path.is_dir():
# Just a directory, use this
averager.average(args.input, args.output)
else:
raise ArgumentError("Invalid input for averaging")
profiler.tick("done averaging")
elif args.command == "distance":
from facetool.recognizer import Recognizer
if not all([args.input, any([args.target, args.model])]):
raise ArgumentError("For the recognizer you need an input and target/model")
logging.debug(f"Trying to recognize {args.input} in {args.target}{args.model}")
recognizer = Recognizer()
results = recognizer.recognize(
input_path = args.input,
model_path = args.model,
target_path = args.target,
as_percentage = args.as_percentage
)
if args.output_format == "csv":
pd.Series(results).to_csv(args.output, header = False)
elif args.output_format == "json":
pd.Series(results).to_json(args.output)
else:
message(f"{args.input} distance to {args.target}")
for path, distance in results.items():
message(f"{path}: {distance}")
elif args.command == "encode":
from facetool.recognizer import Recognizer
if not all([args.input, args.output]):
raise ArgumentError("For encoding faces you need both input and output")
recognizer = Recognizer()
encodings = recognizer.encode_path(args.input)
with open(args.output, "w") as f:
f.write(encodings)
message(f"Written encodings of {args.input} to {args.output}")
elif args.command == "cluster":
from facetool.clusterer import Clusterer
# A .json file with encodings is also valid, if that is give, use that
# instead
if is_json_path(args.input):
encodings = Knead(args.input).data()["encodings"]
else:
from facetool.recognizer import Recognizer
recognizer = Recognizer()
encodings = recognizer.encode_path(args.input, return_type = "dict")
encodings = encodings["encodings"]
clusterer = Clusterer()
output = clusterer.cluster_encodings(encodings)
if args.output:
if is_json_path(args.output):
Knead(output).write(args.output)
else:
force_mkdir(args.output)
clusterer.move_files(output, args.output)
else:
# Just print the output
Knead(output).print()
elif args.command == "swap":
from facetool.swapper import Swapper
profiler.tick("start swapping")
# First check if all arguments are given
arguments = [args.input, args.target]
if not all(arguments + [args.output]):
raise ArgumentError("Input, target and output are required for swapping")
# And if these things are paths or files
if not all([os.path.exists(a) for a in arguments]):
raise ArgumentError("Input and target should be valid files or directories")
pbar = tqdm()
def update_pbar():
pbar.total = swapper.filecount
pbar.update()
if args.verbose:
pbar.write(swapper.last_message)
# That is out of the way, set up the swapper
swapper = Swapper(
predictor_path = args.predictor_path,
feather = args.feather,
blur = args.blur,
keep_temp = args.keep_temp,
swap_audio = not args.no_audio,
overlay_eyesbrows = not args.no_eyesbrows,
overlay_nosemouth = not args.no_nosemouth,
only_mouth = args.only_mouth,
reporthook = update_pbar,
swap_method = args.swap_method,
warp_3d = args.warp_3d,
swap_order = args.swap_order,
swap_order_repeat = args.swap_order_repeat,
ignore_nofaces = args.ignore_nofaces,
concurrent = not args.no_threading,
colour_correct = not args.no_colour_correct,
temp_dir = args.temp_dir
)
# Directory of faces to directory of heads
if Path(args.input).is_dir() and Path(args.target).is_dir():
swapper.swap_directory_to_directory(args.input, args.target, args.output)
# Face to directory of heads
elif media.is_image(args.input) and Path(args.target).is_dir():
swapper.swap_image_to_directory(args.input, args.target, args.output)
# Directory of faces to head
elif Path(args.input).is_dir() and media.is_image(args.target):
swapper.swap_directory_to_image(args.input, args.target, args.output)
# Face in image to video
elif media.is_video(args.target) and media.is_image(args.input):
swapper.swap_image_to_video(args.target, args.input, args.output)
# Face of video to head in other video
elif media.is_video(args.target) and media.is_video(args.input):
swapper.swap_video_to_video(args.target, args.input, args.output)
# Image to image
elif media.is_image(args.target) and media.is_image(args.input):
swapper.swap_image_to_image(args.target, args.input, args.output)
# I don't even know if there is an option that isn't in the list above,
# but if it isn't, you'll get this
else:
raise ArgumentError("Invalid swap options")
pbar.close()
profiler.tick("done swapping")
else:
# No arguments, just display help
parser.print_help()
if __name__ == "__main__":
parser = get_parser()
args = parser.parse_args()
try:
main(args)
except IsADirectoryError as e:
print(f"Can't use a directory as an argument: {e}")
if config.PROFILE:
profiler.dump_events()