Spaces:
Sleeping
Sleeping
Commit
·
3455fb1
0
Parent(s):
Duplicate from CVPR/DualStyleGAN
Browse filesCo-authored-by: hysts <[email protected]>
- .gitattributes +28 -0
- .gitignore +1 -0
- .gitmodules +3 -0
- .pre-commit-config.yaml +35 -0
- .style.yapf +5 -0
- DualStyleGAN +1 -0
- README.md +13 -0
- app.py +242 -0
- dualstylegan.py +203 -0
- images/95UF6LXe-Lo.jpg +3 -0
- images/ILip77SbmOE.jpg +3 -0
- images/README.md +6 -0
- images/et_78QkMMQs.jpg +3 -0
- images/rDEOVtE7vOs.jpg +3 -0
- packages.txt +3 -0
- requirements.txt +7 -0
- style.css +19 -0
.gitattributes
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.bin.* filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
21 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
26 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.zstandard filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
shape_predictor_68_face_landmarks.dat*
|
.gitmodules
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
[submodule "DualStyleGAN"]
|
2 |
+
path = DualStyleGAN
|
3 |
+
url = https://github.com/williamyang1991/DualStyleGAN
|
.pre-commit-config.yaml
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
repos:
|
2 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
3 |
+
rev: v4.2.0
|
4 |
+
hooks:
|
5 |
+
- id: check-executables-have-shebangs
|
6 |
+
- id: check-json
|
7 |
+
- id: check-merge-conflict
|
8 |
+
- id: check-shebang-scripts-are-executable
|
9 |
+
- id: check-toml
|
10 |
+
- id: check-yaml
|
11 |
+
- id: double-quote-string-fixer
|
12 |
+
- id: end-of-file-fixer
|
13 |
+
- id: mixed-line-ending
|
14 |
+
args: ['--fix=lf']
|
15 |
+
- id: requirements-txt-fixer
|
16 |
+
- id: trailing-whitespace
|
17 |
+
- repo: https://github.com/myint/docformatter
|
18 |
+
rev: v1.4
|
19 |
+
hooks:
|
20 |
+
- id: docformatter
|
21 |
+
args: ['--in-place']
|
22 |
+
- repo: https://github.com/pycqa/isort
|
23 |
+
rev: 5.10.1
|
24 |
+
hooks:
|
25 |
+
- id: isort
|
26 |
+
- repo: https://github.com/pre-commit/mirrors-mypy
|
27 |
+
rev: v0.812
|
28 |
+
hooks:
|
29 |
+
- id: mypy
|
30 |
+
args: ['--ignore-missing-imports']
|
31 |
+
- repo: https://github.com/google/yapf
|
32 |
+
rev: v0.32.0
|
33 |
+
hooks:
|
34 |
+
- id: yapf
|
35 |
+
args: ['--parallel', '--in-place']
|
.style.yapf
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[style]
|
2 |
+
based_on_style = pep8
|
3 |
+
blank_line_before_nested_class_or_def = false
|
4 |
+
spaces_before_comment = 2
|
5 |
+
split_before_logical_operator = true
|
DualStyleGAN
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Subproject commit d9c52c2313913352cd2e35707f72fd450bf16630
|
README.md
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Portrait Style Transfer with DualStyleGAN
|
3 |
+
emoji: 😻
|
4 |
+
colorFrom: purple
|
5 |
+
colorTo: red
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 3.0.15
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
duplicated_from: CVPR/DualStyleGAN
|
11 |
+
---
|
12 |
+
|
13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference
|
app.py
ADDED
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
|
3 |
+
from __future__ import annotations
|
4 |
+
|
5 |
+
import argparse
|
6 |
+
import pathlib
|
7 |
+
|
8 |
+
import gradio as gr
|
9 |
+
|
10 |
+
from dualstylegan import Model
|
11 |
+
|
12 |
+
DESCRIPTION = '''# Portrait Style Transfer with <a href="https://github.com/williamyang1991/DualStyleGAN">DualStyleGAN</a>
|
13 |
+
|
14 |
+
<img id="overview" alt="overview" src="https://raw.githubusercontent.com/williamyang1991/DualStyleGAN/main/doc_images/overview.jpg" />
|
15 |
+
'''
|
16 |
+
FOOTER = '<img id="visitor-badge" alt="visitor badge" src="https://visitor-badge.glitch.me/badge?page_id=gradio-blocks.dualstylegan" />'
|
17 |
+
|
18 |
+
|
19 |
+
def parse_args() -> argparse.Namespace:
|
20 |
+
parser = argparse.ArgumentParser()
|
21 |
+
parser.add_argument('--device', type=str, default='cpu')
|
22 |
+
parser.add_argument('--theme', type=str)
|
23 |
+
parser.add_argument('--share', action='store_true')
|
24 |
+
parser.add_argument('--port', type=int)
|
25 |
+
parser.add_argument('--disable-queue',
|
26 |
+
dest='enable_queue',
|
27 |
+
action='store_false')
|
28 |
+
return parser.parse_args()
|
29 |
+
|
30 |
+
|
31 |
+
def get_style_image_url(style_name: str) -> str:
|
32 |
+
base_url = 'https://raw.githubusercontent.com/williamyang1991/DualStyleGAN/main/doc_images'
|
33 |
+
filenames = {
|
34 |
+
'cartoon': 'cartoon_overview.jpg',
|
35 |
+
'caricature': 'caricature_overview.jpg',
|
36 |
+
'anime': 'anime_overview.jpg',
|
37 |
+
'arcane': 'Reconstruction_arcane_overview.jpg',
|
38 |
+
'comic': 'Reconstruction_comic_overview.jpg',
|
39 |
+
'pixar': 'Reconstruction_pixar_overview.jpg',
|
40 |
+
'slamdunk': 'Reconstruction_slamdunk_overview.jpg',
|
41 |
+
}
|
42 |
+
return f'{base_url}/{filenames[style_name]}'
|
43 |
+
|
44 |
+
|
45 |
+
def get_style_image_markdown_text(style_name: str) -> str:
|
46 |
+
url = get_style_image_url(style_name)
|
47 |
+
return f'<img id="style-image" src="{url}" alt="style image">'
|
48 |
+
|
49 |
+
|
50 |
+
def update_slider(choice: str) -> dict:
|
51 |
+
max_vals = {
|
52 |
+
'cartoon': 316,
|
53 |
+
'caricature': 198,
|
54 |
+
'anime': 173,
|
55 |
+
'arcane': 99,
|
56 |
+
'comic': 100,
|
57 |
+
'pixar': 121,
|
58 |
+
'slamdunk': 119,
|
59 |
+
}
|
60 |
+
return gr.Slider.update(maximum=max_vals[choice])
|
61 |
+
|
62 |
+
|
63 |
+
def update_style_image(style_name: str) -> dict:
|
64 |
+
text = get_style_image_markdown_text(style_name)
|
65 |
+
return gr.Markdown.update(value=text)
|
66 |
+
|
67 |
+
|
68 |
+
def set_example_image(example: list) -> dict:
|
69 |
+
return gr.Image.update(value=example[0])
|
70 |
+
|
71 |
+
|
72 |
+
def set_example_styles(example: list) -> list[dict]:
|
73 |
+
return [
|
74 |
+
gr.Radio.update(value=example[0]),
|
75 |
+
gr.Slider.update(value=example[1]),
|
76 |
+
]
|
77 |
+
|
78 |
+
|
79 |
+
def set_example_weights(example: list) -> list[dict]:
|
80 |
+
return [
|
81 |
+
gr.Slider.update(value=example[0]),
|
82 |
+
gr.Slider.update(value=example[1]),
|
83 |
+
]
|
84 |
+
|
85 |
+
|
86 |
+
def main():
|
87 |
+
args = parse_args()
|
88 |
+
model = Model(device=args.device)
|
89 |
+
|
90 |
+
with gr.Blocks(theme=args.theme, css='style.css') as demo:
|
91 |
+
gr.Markdown(DESCRIPTION)
|
92 |
+
|
93 |
+
with gr.Box():
|
94 |
+
gr.Markdown('''## Step 1 (Preprocess Input Image)
|
95 |
+
|
96 |
+
- Drop an image containing a near-frontal face to the **Input Image**.
|
97 |
+
- If there are multiple faces in the image, hit the Edit button in the upper right corner and crop the input image beforehand.
|
98 |
+
- Hit the **Preprocess** button.
|
99 |
+
- Choose the encoder version. Default is Z+ encoder which has better stylization performance. W+ encoder better reconstructs the input image to preserve more details.
|
100 |
+
- The final result will be based on this **Reconstructed Face**. So, if the reconstructed image is not satisfactory, you may want to change the input image.
|
101 |
+
''')
|
102 |
+
with gr.Row():
|
103 |
+
encoder_type = gr.Radio(choices=['Z+ encoder (better stylization)', 'W+ encoder (better reconstruction)'],
|
104 |
+
value='Z+ encoder (better stylization)',
|
105 |
+
label='Encoder Type')
|
106 |
+
with gr.Row():
|
107 |
+
with gr.Column():
|
108 |
+
with gr.Row():
|
109 |
+
input_image = gr.Image(label='Input Image',
|
110 |
+
type='file')
|
111 |
+
with gr.Row():
|
112 |
+
preprocess_button = gr.Button('Preprocess')
|
113 |
+
with gr.Column():
|
114 |
+
with gr.Row():
|
115 |
+
aligned_face = gr.Image(label='Aligned Face',
|
116 |
+
type='numpy',
|
117 |
+
interactive=False)
|
118 |
+
with gr.Column():
|
119 |
+
reconstructed_face = gr.Image(label='Reconstructed Face',
|
120 |
+
type='numpy')
|
121 |
+
instyle = gr.Variable()
|
122 |
+
|
123 |
+
with gr.Row():
|
124 |
+
paths = sorted(pathlib.Path('images').glob('*.jpg'))
|
125 |
+
example_images = gr.Dataset(components=[input_image],
|
126 |
+
samples=[[path.as_posix()]
|
127 |
+
for path in paths])
|
128 |
+
|
129 |
+
with gr.Box():
|
130 |
+
gr.Markdown('''## Step 2 (Select Style Image)
|
131 |
+
|
132 |
+
- Select **Style Type**.
|
133 |
+
- Select **Style Image Index** from the image table below.
|
134 |
+
''')
|
135 |
+
with gr.Row():
|
136 |
+
with gr.Column():
|
137 |
+
style_type = gr.Radio(model.style_types,
|
138 |
+
label='Style Type')
|
139 |
+
text = get_style_image_markdown_text('cartoon')
|
140 |
+
style_image = gr.Markdown(value=text)
|
141 |
+
style_index = gr.Slider(0,
|
142 |
+
316,
|
143 |
+
value=26,
|
144 |
+
step=1,
|
145 |
+
label='Style Image Index')
|
146 |
+
|
147 |
+
with gr.Row():
|
148 |
+
example_styles = gr.Dataset(
|
149 |
+
components=[style_type, style_index],
|
150 |
+
samples=[
|
151 |
+
['cartoon', 26],
|
152 |
+
['caricature', 65],
|
153 |
+
['arcane', 63],
|
154 |
+
['pixar', 80],
|
155 |
+
])
|
156 |
+
|
157 |
+
with gr.Box():
|
158 |
+
gr.Markdown('''## Step 3 (Generate Style Transferred Image)
|
159 |
+
|
160 |
+
- Adjust **Structure Weight** and **Color Weight**.
|
161 |
+
- These are weights for the style image, so the larger the value, the closer the resulting image will be to the style image.
|
162 |
+
- Tips: For W+ encoder, better way of (Structure Only) is to uncheck (Structure Only) and set Color weight to 0.
|
163 |
+
- Hit the **Generate** button.
|
164 |
+
''')
|
165 |
+
with gr.Row():
|
166 |
+
with gr.Column():
|
167 |
+
with gr.Row():
|
168 |
+
structure_weight = gr.Slider(0,
|
169 |
+
1,
|
170 |
+
value=0.6,
|
171 |
+
step=0.1,
|
172 |
+
label='Structure Weight')
|
173 |
+
with gr.Row():
|
174 |
+
color_weight = gr.Slider(0,
|
175 |
+
1,
|
176 |
+
value=1,
|
177 |
+
step=0.1,
|
178 |
+
label='Color Weight')
|
179 |
+
with gr.Row():
|
180 |
+
structure_only = gr.Checkbox(label='Structure Only')
|
181 |
+
with gr.Row():
|
182 |
+
generate_button = gr.Button('Generate')
|
183 |
+
|
184 |
+
with gr.Column():
|
185 |
+
result = gr.Image(label='Result')
|
186 |
+
|
187 |
+
with gr.Row():
|
188 |
+
example_weights = gr.Dataset(
|
189 |
+
components=[structure_weight, color_weight],
|
190 |
+
samples=[
|
191 |
+
[0.6, 1.0],
|
192 |
+
[0.3, 1.0],
|
193 |
+
[0.0, 1.0],
|
194 |
+
[1.0, 0.0],
|
195 |
+
])
|
196 |
+
|
197 |
+
gr.Markdown(FOOTER)
|
198 |
+
|
199 |
+
preprocess_button.click(fn=model.detect_and_align_face,
|
200 |
+
inputs=[input_image],
|
201 |
+
outputs=aligned_face)
|
202 |
+
aligned_face.change(fn=model.reconstruct_face,
|
203 |
+
inputs=[aligned_face, encoder_type],
|
204 |
+
outputs=[
|
205 |
+
reconstructed_face,
|
206 |
+
instyle,
|
207 |
+
])
|
208 |
+
style_type.change(fn=update_slider,
|
209 |
+
inputs=style_type,
|
210 |
+
outputs=style_index)
|
211 |
+
style_type.change(fn=update_style_image,
|
212 |
+
inputs=style_type,
|
213 |
+
outputs=style_image)
|
214 |
+
generate_button.click(fn=model.generate,
|
215 |
+
inputs=[
|
216 |
+
style_type,
|
217 |
+
style_index,
|
218 |
+
structure_weight,
|
219 |
+
color_weight,
|
220 |
+
structure_only,
|
221 |
+
instyle,
|
222 |
+
],
|
223 |
+
outputs=result)
|
224 |
+
example_images.click(fn=set_example_image,
|
225 |
+
inputs=example_images,
|
226 |
+
outputs=example_images.components)
|
227 |
+
example_styles.click(fn=set_example_styles,
|
228 |
+
inputs=example_styles,
|
229 |
+
outputs=example_styles.components)
|
230 |
+
example_weights.click(fn=set_example_weights,
|
231 |
+
inputs=example_weights,
|
232 |
+
outputs=example_weights.components)
|
233 |
+
|
234 |
+
demo.launch(
|
235 |
+
enable_queue=args.enable_queue,
|
236 |
+
server_port=args.port,
|
237 |
+
share=args.share,
|
238 |
+
)
|
239 |
+
|
240 |
+
|
241 |
+
if __name__ == '__main__':
|
242 |
+
main()
|
dualstylegan.py
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import argparse
|
4 |
+
import os
|
5 |
+
import pathlib
|
6 |
+
import subprocess
|
7 |
+
import sys
|
8 |
+
from typing import Callable
|
9 |
+
|
10 |
+
import dlib
|
11 |
+
import huggingface_hub
|
12 |
+
import numpy as np
|
13 |
+
import PIL.Image
|
14 |
+
import torch
|
15 |
+
import torch.nn as nn
|
16 |
+
import torchvision.transforms as T
|
17 |
+
|
18 |
+
if os.getenv('SYSTEM') == 'spaces':
|
19 |
+
os.system("sed -i '10,17d' DualStyleGAN/model/stylegan/op/fused_act.py")
|
20 |
+
os.system("sed -i '10,17d' DualStyleGAN/model/stylegan/op/upfirdn2d.py")
|
21 |
+
|
22 |
+
app_dir = pathlib.Path(__file__).parent
|
23 |
+
submodule_dir = app_dir / 'DualStyleGAN'
|
24 |
+
sys.path.insert(0, submodule_dir.as_posix())
|
25 |
+
|
26 |
+
from model.dualstylegan import DualStyleGAN
|
27 |
+
from model.encoder.align_all_parallel import align_face
|
28 |
+
from model.encoder.psp import pSp
|
29 |
+
|
30 |
+
MODEL_REPO = 'CVPR/DualStyleGAN'
|
31 |
+
|
32 |
+
|
33 |
+
class Model:
|
34 |
+
def __init__(self, device: torch.device | str):
|
35 |
+
self.device = torch.device(device)
|
36 |
+
self.landmark_model = self._create_dlib_landmark_model()
|
37 |
+
self.encoder_dict = self._load_encoder()
|
38 |
+
self.transform = self._create_transform()
|
39 |
+
self.encoder_type = 'z+'
|
40 |
+
|
41 |
+
self.style_types = [
|
42 |
+
'cartoon',
|
43 |
+
'caricature',
|
44 |
+
'anime',
|
45 |
+
'arcane',
|
46 |
+
'comic',
|
47 |
+
'pixar',
|
48 |
+
'slamdunk',
|
49 |
+
]
|
50 |
+
self.generator_dict = {
|
51 |
+
style_type: self._load_generator(style_type)
|
52 |
+
for style_type in self.style_types
|
53 |
+
}
|
54 |
+
self.exstyle_dict = {
|
55 |
+
style_type: self._load_exstylecode(style_type)
|
56 |
+
for style_type in self.style_types
|
57 |
+
}
|
58 |
+
|
59 |
+
@staticmethod
|
60 |
+
def _create_dlib_landmark_model():
|
61 |
+
url = 'http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2'
|
62 |
+
path = pathlib.Path('shape_predictor_68_face_landmarks.dat')
|
63 |
+
if not path.exists():
|
64 |
+
bz2_path = 'shape_predictor_68_face_landmarks.dat.bz2'
|
65 |
+
torch.hub.download_url_to_file(url, bz2_path)
|
66 |
+
subprocess.run(f'bunzip2 -d {bz2_path}'.split())
|
67 |
+
return dlib.shape_predictor(path.as_posix())
|
68 |
+
|
69 |
+
def _load_encoder(self) -> nn.Module:
|
70 |
+
ckpt_path = huggingface_hub.hf_hub_download(MODEL_REPO,
|
71 |
+
'models/encoder.pt')
|
72 |
+
ckpt = torch.load(ckpt_path, map_location='cpu')
|
73 |
+
opts = ckpt['opts']
|
74 |
+
opts['device'] = self.device.type
|
75 |
+
opts['checkpoint_path'] = ckpt_path
|
76 |
+
opts = argparse.Namespace(**opts)
|
77 |
+
model = pSp(opts)
|
78 |
+
model.to(self.device)
|
79 |
+
model.eval()
|
80 |
+
|
81 |
+
ckpt_path = huggingface_hub.hf_hub_download(MODEL_REPO,
|
82 |
+
'models/encoder_wplus.pt')
|
83 |
+
ckpt = torch.load(ckpt_path, map_location='cpu')
|
84 |
+
opts = ckpt['opts']
|
85 |
+
opts['device'] = self.device.type
|
86 |
+
opts['checkpoint_path'] = ckpt_path
|
87 |
+
opts['output_size'] = 1024
|
88 |
+
opts = argparse.Namespace(**opts)
|
89 |
+
model2 = pSp(opts)
|
90 |
+
model2.to(self.device)
|
91 |
+
model2.eval()
|
92 |
+
|
93 |
+
return {'z+': model, 'w+': model2}
|
94 |
+
|
95 |
+
@staticmethod
|
96 |
+
def _create_transform() -> Callable:
|
97 |
+
transform = T.Compose([
|
98 |
+
T.Resize(256),
|
99 |
+
T.CenterCrop(256),
|
100 |
+
T.ToTensor(),
|
101 |
+
T.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
|
102 |
+
])
|
103 |
+
return transform
|
104 |
+
|
105 |
+
def _load_generator(self, style_type: str) -> nn.Module:
|
106 |
+
model = DualStyleGAN(1024, 512, 8, 2, res_index=6)
|
107 |
+
ckpt_path = huggingface_hub.hf_hub_download(
|
108 |
+
MODEL_REPO, f'models/{style_type}/generator.pt')
|
109 |
+
ckpt = torch.load(ckpt_path, map_location='cpu')
|
110 |
+
model.load_state_dict(ckpt['g_ema'])
|
111 |
+
model.to(self.device)
|
112 |
+
model.eval()
|
113 |
+
return model
|
114 |
+
|
115 |
+
@staticmethod
|
116 |
+
def _load_exstylecode(style_type: str) -> dict[str, np.ndarray]:
|
117 |
+
if style_type in ['cartoon', 'caricature', 'anime']:
|
118 |
+
filename = 'refined_exstyle_code.npy'
|
119 |
+
else:
|
120 |
+
filename = 'exstyle_code.npy'
|
121 |
+
path = huggingface_hub.hf_hub_download(
|
122 |
+
MODEL_REPO, f'models/{style_type}/{filename}')
|
123 |
+
exstyles = np.load(path, allow_pickle=True).item()
|
124 |
+
return exstyles
|
125 |
+
|
126 |
+
def detect_and_align_face(self, image) -> np.ndarray:
|
127 |
+
image = align_face(filepath=image.name, predictor=self.landmark_model)
|
128 |
+
x, y = np.random.randint(255), np.random.randint(255)
|
129 |
+
r, g, b = image.getpixel((x, y))
|
130 |
+
image.putpixel((x, y), (r, g+1, b)) # trick to make sure run reconstruct_face() once any input setting changes
|
131 |
+
return image
|
132 |
+
|
133 |
+
@staticmethod
|
134 |
+
def denormalize(tensor: torch.Tensor) -> torch.Tensor:
|
135 |
+
return torch.clamp((tensor + 1) / 2 * 255, 0, 255).to(torch.uint8)
|
136 |
+
|
137 |
+
def postprocess(self, tensor: torch.Tensor) -> np.ndarray:
|
138 |
+
tensor = self.denormalize(tensor)
|
139 |
+
return tensor.cpu().numpy().transpose(1, 2, 0)
|
140 |
+
|
141 |
+
@torch.inference_mode()
|
142 |
+
def reconstruct_face(self,
|
143 |
+
image: np.ndarray, encoder_type: str) -> tuple[np.ndarray, torch.Tensor]:
|
144 |
+
if encoder_type == 'Z+ encoder (better stylization)':
|
145 |
+
self.encoder_type = 'z+'
|
146 |
+
z_plus_latent = True
|
147 |
+
return_z_plus_latent = True
|
148 |
+
else:
|
149 |
+
self.encoder_type = 'w+'
|
150 |
+
z_plus_latent = False
|
151 |
+
return_z_plus_latent = False
|
152 |
+
image = PIL.Image.fromarray(image)
|
153 |
+
input_data = self.transform(image).unsqueeze(0).to(self.device)
|
154 |
+
img_rec, instyle = self.encoder_dict[self.encoder_type](input_data,
|
155 |
+
randomize_noise=False,
|
156 |
+
return_latents=True,
|
157 |
+
z_plus_latent=z_plus_latent,
|
158 |
+
return_z_plus_latent=return_z_plus_latent,
|
159 |
+
resize=False)
|
160 |
+
img_rec = torch.clamp(img_rec.detach(), -1, 1)
|
161 |
+
img_rec = self.postprocess(img_rec[0])
|
162 |
+
return img_rec, instyle
|
163 |
+
|
164 |
+
@torch.inference_mode()
|
165 |
+
def generate(self, style_type: str, style_id: int, structure_weight: float,
|
166 |
+
color_weight: float, structure_only: bool,
|
167 |
+
instyle: torch.Tensor) -> np.ndarray:
|
168 |
+
|
169 |
+
|
170 |
+
if self.encoder_type == 'z+':
|
171 |
+
z_plus_latent = True
|
172 |
+
input_is_latent = False
|
173 |
+
else:
|
174 |
+
z_plus_latent = False
|
175 |
+
input_is_latent = True
|
176 |
+
|
177 |
+
generator = self.generator_dict[style_type]
|
178 |
+
exstyles = self.exstyle_dict[style_type]
|
179 |
+
|
180 |
+
style_id = int(style_id)
|
181 |
+
stylename = list(exstyles.keys())[style_id]
|
182 |
+
|
183 |
+
latent = torch.tensor(exstyles[stylename]).to(self.device)
|
184 |
+
if structure_only and self.encoder_type == 'z+':
|
185 |
+
latent[0, 7:18] = instyle[0, 7:18]
|
186 |
+
exstyle = generator.generator.style(
|
187 |
+
latent.reshape(latent.shape[0] * latent.shape[1],
|
188 |
+
latent.shape[2])).reshape(latent.shape)
|
189 |
+
if structure_only and self.encoder_type == 'w+':
|
190 |
+
exstyle[:,7:18] = instyle[:,7:18]
|
191 |
+
|
192 |
+
img_gen, _ = generator([instyle],
|
193 |
+
exstyle,
|
194 |
+
input_is_latent=input_is_latent,
|
195 |
+
z_plus_latent=z_plus_latent,
|
196 |
+
truncation=0.7,
|
197 |
+
truncation_latent=0,
|
198 |
+
use_res=True,
|
199 |
+
interp_weights=[structure_weight] * 7 +
|
200 |
+
[color_weight] * 11)
|
201 |
+
img_gen = torch.clamp(img_gen.detach(), -1, 1)
|
202 |
+
img_gen = self.postprocess(img_gen[0])
|
203 |
+
return img_gen
|
images/95UF6LXe-Lo.jpg
ADDED
![]() |
Git LFS Details
|
images/ILip77SbmOE.jpg
ADDED
![]() |
Git LFS Details
|
images/README.md
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
These images are freely-usable ones from [Unsplash](https://unsplash.com/).
|
2 |
+
|
3 |
+
- https://unsplash.com/photos/rDEOVtE7vOs
|
4 |
+
- https://unsplash.com/photos/et_78QkMMQs
|
5 |
+
- https://unsplash.com/photos/ILip77SbmOE
|
6 |
+
- https://unsplash.com/photos/95UF6LXe-Lo
|
images/et_78QkMMQs.jpg
ADDED
![]() |
Git LFS Details
|
images/rDEOVtE7vOs.jpg
ADDED
![]() |
Git LFS Details
|
packages.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
bzip2
|
2 |
+
cmake
|
3 |
+
ninja-build
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
dlib==19.23.0
|
2 |
+
numpy==1.22.3
|
3 |
+
opencv-python-headless==4.5.5.62
|
4 |
+
Pillow==9.0.1
|
5 |
+
scipy==1.8.0
|
6 |
+
torch==1.11.0
|
7 |
+
torchvision==0.12.0
|
style.css
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
h1 {
|
2 |
+
text-align: center;
|
3 |
+
}
|
4 |
+
img#overview {
|
5 |
+
max-width: 1000px;
|
6 |
+
max-height: 600px;
|
7 |
+
display: block;
|
8 |
+
margin: auto;
|
9 |
+
}
|
10 |
+
img#style-image {
|
11 |
+
max-width: 1000px;
|
12 |
+
max-height: 600px;
|
13 |
+
display: block;
|
14 |
+
margin: auto;
|
15 |
+
}
|
16 |
+
img#visitor-badge {
|
17 |
+
display: block;
|
18 |
+
margin: auto;
|
19 |
+
}
|