Your Name
commited on
Commit
•
c71d758
1
Parent(s):
b818e78
utils
Browse files
utils/__pycache__/drive.cpython-310.pyc
ADDED
Binary file (3.57 kB). View file
|
|
utils/__pycache__/shape_predictor.cpython-310.pyc
ADDED
Binary file (5.78 kB). View file
|
|
utils/drive.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# URL helpers, see https://github.com/NVlabs/stylegan
|
2 |
+
# ------------------------------------------------------------------------------------------
|
3 |
+
|
4 |
+
import requests
|
5 |
+
import html
|
6 |
+
import hashlib
|
7 |
+
import gdown
|
8 |
+
import glob
|
9 |
+
import os
|
10 |
+
import io
|
11 |
+
from typing import Any
|
12 |
+
import re
|
13 |
+
import uuid
|
14 |
+
|
15 |
+
weight_dic = {'afhqwild.pt': 'https://drive.google.com/file/d/14OnzO4QWaAytKXVqcfWo_o2MzoR4ygnr/view?usp=sharing',
|
16 |
+
'afhqdog.pt': 'https://drive.google.com/file/d/16v6jPtKVlvq8rg2Sdi3-R9qZEVDgvvEA/view?usp=sharing',
|
17 |
+
'afhqcat.pt': 'https://drive.google.com/file/d/1HXLER5R3EMI8DSYDBZafoqpX4EtyOf2R/view?usp=sharing',
|
18 |
+
'ffhq.pt': 'https://drive.google.com/file/d/1AT6bNR2ppK8f2ETL_evT27f3R_oyWNHS/view?usp=sharing',
|
19 |
+
'metfaces.pt': 'https://drive.google.com/file/d/16wM2PwVWzaMsRgPExvRGsq6BWw_muKbf/view?usp=sharing',
|
20 |
+
'seg.pth': 'https://drive.google.com/file/d/1lIKvQaFKHT5zC7uS4p17O9ZpfwmwlS62/view?usp=sharing'}
|
21 |
+
|
22 |
+
|
23 |
+
def download_weight(weight_path):
|
24 |
+
gdown.download(weight_dic[os.path.basename(weight_path)],
|
25 |
+
output=weight_path, fuzzy=True)
|
26 |
+
|
27 |
+
|
28 |
+
def is_url(obj: Any) -> bool:
|
29 |
+
"""Determine whether the given object is a valid URL string."""
|
30 |
+
if not isinstance(obj, str) or not "://" in obj:
|
31 |
+
return False
|
32 |
+
try:
|
33 |
+
res = requests.compat.urlparse(obj)
|
34 |
+
if not res.scheme or not res.netloc or not "." in res.netloc:
|
35 |
+
return False
|
36 |
+
res = requests.compat.urlparse(requests.compat.urljoin(obj, "/"))
|
37 |
+
if not res.scheme or not res.netloc or not "." in res.netloc:
|
38 |
+
return False
|
39 |
+
except:
|
40 |
+
return False
|
41 |
+
return True
|
42 |
+
|
43 |
+
|
44 |
+
def open_url(url: str, cache_dir: str = None, num_attempts: int = 10, verbose: bool = True,
|
45 |
+
return_path: bool = False) -> Any:
|
46 |
+
"""Download the given URL and return a binary-mode file object to access the data."""
|
47 |
+
assert is_url(url)
|
48 |
+
assert num_attempts >= 1
|
49 |
+
|
50 |
+
# Lookup from cache.
|
51 |
+
url_md5 = hashlib.md5(url.encode("utf-8")).hexdigest()
|
52 |
+
if cache_dir is not None:
|
53 |
+
cache_files = glob.glob(os.path.join(cache_dir, url_md5 + "_*"))
|
54 |
+
if len(cache_files) == 1:
|
55 |
+
if (return_path):
|
56 |
+
return cache_files[0]
|
57 |
+
else:
|
58 |
+
return open(cache_files[0], "rb")
|
59 |
+
|
60 |
+
# Download.
|
61 |
+
url_name = None
|
62 |
+
url_data = None
|
63 |
+
with requests.Session() as session:
|
64 |
+
if verbose:
|
65 |
+
print("Downloading %s ..." % url, end="", flush=True)
|
66 |
+
for attempts_left in reversed(range(num_attempts)):
|
67 |
+
try:
|
68 |
+
with session.get(url) as res:
|
69 |
+
res.raise_for_status()
|
70 |
+
if len(res.content) == 0:
|
71 |
+
raise IOError("No data received")
|
72 |
+
|
73 |
+
if len(res.content) < 8192:
|
74 |
+
content_str = res.content.decode("utf-8")
|
75 |
+
if "download_warning" in res.headers.get("Set-Cookie", ""):
|
76 |
+
links = [html.unescape(link) for link in content_str.split('"') if
|
77 |
+
"export=download" in link]
|
78 |
+
if len(links) == 1:
|
79 |
+
url = requests.compat.urljoin(url, links[0])
|
80 |
+
raise IOError("Google Drive virus checker nag")
|
81 |
+
if "Google Drive - Quota exceeded" in content_str:
|
82 |
+
raise IOError("Google Drive quota exceeded")
|
83 |
+
|
84 |
+
match = re.search(r'filename="([^"]*)"', res.headers.get("Content-Disposition", ""))
|
85 |
+
url_name = match[1] if match else url
|
86 |
+
url_data = res.content
|
87 |
+
if verbose:
|
88 |
+
print(" done")
|
89 |
+
break
|
90 |
+
except:
|
91 |
+
if not attempts_left:
|
92 |
+
if verbose:
|
93 |
+
print(" failed")
|
94 |
+
raise
|
95 |
+
if verbose:
|
96 |
+
print(".", end="", flush=True)
|
97 |
+
|
98 |
+
# Save to cache.
|
99 |
+
if cache_dir is not None:
|
100 |
+
safe_name = re.sub(r"[^0-9a-zA-Z-._]", "_", url_name)
|
101 |
+
cache_file = os.path.join(cache_dir, url_md5 + "_" + safe_name)
|
102 |
+
temp_file = os.path.join(cache_dir, "tmp_" + uuid.uuid4().hex + "_" + url_md5 + "_" + safe_name)
|
103 |
+
os.makedirs(cache_dir, exist_ok=True)
|
104 |
+
with open(temp_file, "wb") as f:
|
105 |
+
f.write(url_data)
|
106 |
+
os.replace(temp_file, cache_file) # atomic
|
107 |
+
if (return_path): return cache_file
|
108 |
+
|
109 |
+
# Return data as file object.
|
110 |
+
return io.BytesIO(url_data)
|
utils/shape_predictor.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from pathlib import Path
|
3 |
+
|
4 |
+
import PIL
|
5 |
+
import dlib
|
6 |
+
import numpy as np
|
7 |
+
import scipy
|
8 |
+
import scipy.ndimage
|
9 |
+
import torch
|
10 |
+
from PIL import Image
|
11 |
+
from torchvision import transforms as T
|
12 |
+
|
13 |
+
from utils.drive import open_url
|
14 |
+
|
15 |
+
"""
|
16 |
+
brief: face alignment with FFHQ method (https://github.com/NVlabs/ffhq-dataset)
|
17 |
+
author: lzhbrian (https://lzhbrian.me)
|
18 |
+
date: 2020.1.5
|
19 |
+
note: code is heavily borrowed from
|
20 |
+
https://github.com/NVlabs/ffhq-dataset
|
21 |
+
http://dlib.net/face_landmark_detection.py.html
|
22 |
+
|
23 |
+
requirements:
|
24 |
+
apt install cmake
|
25 |
+
conda install Pillow numpy scipy
|
26 |
+
pip install dlib
|
27 |
+
# download face landmark model from:
|
28 |
+
# http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
|
29 |
+
"""
|
30 |
+
|
31 |
+
|
32 |
+
def get_landmark(filepath, predictor):
|
33 |
+
"""get landmark with dlib
|
34 |
+
:return: np.array shape=(68, 2)
|
35 |
+
"""
|
36 |
+
detector = dlib.get_frontal_face_detector()
|
37 |
+
|
38 |
+
img = dlib.load_rgb_image(filepath)
|
39 |
+
dets = detector(img, 1)
|
40 |
+
filepath = Path(filepath)
|
41 |
+
print(f"{filepath.name}: Number of faces detected: {len(dets)}")
|
42 |
+
shapes = [predictor(img, d) for k, d in enumerate(dets)]
|
43 |
+
|
44 |
+
lms = [np.array([[tt.x, tt.y] for tt in shape.parts()]) for shape in shapes]
|
45 |
+
|
46 |
+
return lms
|
47 |
+
|
48 |
+
|
49 |
+
def get_landmark_from_tensors(tensors: list[torch.Tensor | Image.Image | np.ndarray], predictor):
|
50 |
+
detector = dlib.get_frontal_face_detector()
|
51 |
+
transform = T.ToPILImage()
|
52 |
+
images = []
|
53 |
+
lms = []
|
54 |
+
|
55 |
+
for k, tensor in enumerate(tensors):
|
56 |
+
if isinstance(tensor, torch.Tensor):
|
57 |
+
img_pil = transform(tensor)
|
58 |
+
else:
|
59 |
+
img_pil = tensor
|
60 |
+
img = np.array(img_pil)
|
61 |
+
images.append(img_pil)
|
62 |
+
|
63 |
+
dets = detector(img, 1)
|
64 |
+
if len(dets) == 0:
|
65 |
+
raise ValueError(f"No faces detected in the image {k}.")
|
66 |
+
elif len(dets) == 1:
|
67 |
+
print(f"Number of faces detected: {len(dets)}")
|
68 |
+
else:
|
69 |
+
print(f"Number of faces detected: {len(dets)}, get largest face")
|
70 |
+
|
71 |
+
# Find the largest face
|
72 |
+
dets = sorted(dets, key=lambda det: det.width() * det.height(), reverse=True)
|
73 |
+
shape = predictor(img, dets[0])
|
74 |
+
lm = np.array([[tt.x, tt.y] for tt in shape.parts()])
|
75 |
+
lms.append(lm)
|
76 |
+
|
77 |
+
return images, lms
|
78 |
+
|
79 |
+
|
80 |
+
def align_face(data, predictor=None, is_filepath=False, return_tensors=True):
|
81 |
+
"""
|
82 |
+
:param data: filepath or list torch Tensors
|
83 |
+
:return: list of PIL Images
|
84 |
+
"""
|
85 |
+
if predictor is None:
|
86 |
+
predictor_path = 'shape_predictor_68_face_landmarks.dat'
|
87 |
+
|
88 |
+
if not os.path.isfile(predictor_path):
|
89 |
+
print("Downloading Shape Predictor")
|
90 |
+
data_io = open_url("https://drive.google.com/uc?id=1huhv8PYpNNKbGCLOaYUjOgR1pY5pmbJx")
|
91 |
+
with open(predictor_path, 'wb') as f:
|
92 |
+
f.write(data_io.getbuffer())
|
93 |
+
|
94 |
+
predictor = dlib.shape_predictor(predictor_path)
|
95 |
+
|
96 |
+
if is_filepath:
|
97 |
+
lms = get_landmark(data, predictor)
|
98 |
+
else:
|
99 |
+
if not isinstance(data, list):
|
100 |
+
data = [data]
|
101 |
+
images, lms = get_landmark_from_tensors(data, predictor)
|
102 |
+
|
103 |
+
imgs = []
|
104 |
+
for num_img, lm in enumerate(lms):
|
105 |
+
lm_chin = lm[0: 17] # left-right
|
106 |
+
lm_eyebrow_left = lm[17: 22] # left-right
|
107 |
+
lm_eyebrow_right = lm[22: 27] # left-right
|
108 |
+
lm_nose = lm[27: 31] # top-down
|
109 |
+
lm_nostrils = lm[31: 36] # top-down
|
110 |
+
lm_eye_left = lm[36: 42] # left-clockwise
|
111 |
+
lm_eye_right = lm[42: 48] # left-clockwise
|
112 |
+
lm_mouth_outer = lm[48: 60] # left-clockwise
|
113 |
+
lm_mouth_inner = lm[60: 68] # left-clockwise
|
114 |
+
|
115 |
+
# Calculate auxiliary vectors.
|
116 |
+
eye_left = np.mean(lm_eye_left, axis=0)
|
117 |
+
eye_right = np.mean(lm_eye_right, axis=0)
|
118 |
+
eye_avg = (eye_left + eye_right) * 0.5
|
119 |
+
eye_to_eye = eye_right - eye_left
|
120 |
+
mouth_left = lm_mouth_outer[0]
|
121 |
+
mouth_right = lm_mouth_outer[6]
|
122 |
+
mouth_avg = (mouth_left + mouth_right) * 0.5
|
123 |
+
eye_to_mouth = mouth_avg - eye_avg
|
124 |
+
|
125 |
+
# Choose oriented crop rectangle.
|
126 |
+
x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
|
127 |
+
x /= np.hypot(*x)
|
128 |
+
x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
|
129 |
+
y = np.flipud(x) * [-1, 1]
|
130 |
+
c = eye_avg + eye_to_mouth * 0.1
|
131 |
+
quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
|
132 |
+
qsize = np.hypot(*x) * 2
|
133 |
+
|
134 |
+
# read image
|
135 |
+
if is_filepath:
|
136 |
+
img = PIL.Image.open(data)
|
137 |
+
else:
|
138 |
+
img = images[num_img]
|
139 |
+
|
140 |
+
output_size = 1024
|
141 |
+
# output_size = 256
|
142 |
+
transform_size = 4096
|
143 |
+
enable_padding = True
|
144 |
+
|
145 |
+
# Shrink.
|
146 |
+
shrink = int(np.floor(qsize / output_size * 0.5))
|
147 |
+
if shrink > 1:
|
148 |
+
rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink)))
|
149 |
+
img = img.resize(rsize, PIL.Image.ANTIALIAS)
|
150 |
+
quad /= shrink
|
151 |
+
qsize /= shrink
|
152 |
+
|
153 |
+
# Crop.
|
154 |
+
border = max(int(np.rint(qsize * 0.1)), 3)
|
155 |
+
crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
|
156 |
+
int(np.ceil(max(quad[:, 1]))))
|
157 |
+
crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]),
|
158 |
+
min(crop[3] + border, img.size[1]))
|
159 |
+
if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
|
160 |
+
img = img.crop(crop)
|
161 |
+
quad -= crop[0:2]
|
162 |
+
|
163 |
+
# Pad.
|
164 |
+
pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
|
165 |
+
int(np.ceil(max(quad[:, 1]))))
|
166 |
+
pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0),
|
167 |
+
max(pad[3] - img.size[1] + border, 0))
|
168 |
+
if enable_padding and max(pad) > border - 4:
|
169 |
+
pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
|
170 |
+
img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
|
171 |
+
h, w, _ = img.shape
|
172 |
+
y, x, _ = np.ogrid[:h, :w, :1]
|
173 |
+
mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]),
|
174 |
+
1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3]))
|
175 |
+
blur = qsize * 0.02
|
176 |
+
img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
|
177 |
+
img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
|
178 |
+
img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
|
179 |
+
quad += pad[:2]
|
180 |
+
|
181 |
+
# Transform.
|
182 |
+
img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(),
|
183 |
+
PIL.Image.BILINEAR)
|
184 |
+
if output_size < transform_size:
|
185 |
+
img = img.resize((output_size, output_size), PIL.Image.LANCZOS)
|
186 |
+
|
187 |
+
# Save aligned image.
|
188 |
+
imgs.append(img)
|
189 |
+
|
190 |
+
if return_tensors:
|
191 |
+
transform = T.ToTensor()
|
192 |
+
tensors = [transform(img).clamp(0, 1) for img in imgs]
|
193 |
+
return tensors
|
194 |
+
return imgs
|