stinkyshep commited on
Commit
fb1a458
·
1 Parent(s): 54dbed6
README.md CHANGED
@@ -1,12 +1,103 @@
1
- ---
2
- title: FaceSwapper
3
- emoji: 🌖
4
- colorFrom: green
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 4.16.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # roop-unleashed
2
+
3
+ [Changelog](#changelog) • [Usage](#usage) • [Wiki](https://github.com/C0untFloyd/roop-unleashed/wiki)
4
+
5
+
6
+ Uncensored Deepfakes for images and videos without training and an easy-to-use GUI.
7
+
8
+
9
+ ![Screen](https://github.com/C0untFloyd/roop-unleashed/assets/131583554/6ee6860d-efbe-4337-8c62-a67598863637)
10
+
11
+ ### Features
12
+
13
+ - Platform-independant Browser GUI
14
+ - Selection of multiple input/output faces in one go
15
+ - Many different swapping modes, first detected, face selections, by gender
16
+ - Batch processing of images/videos
17
+ - Masking of face occluders using text prompts
18
+ - Optional Face Restoration using different enhancers
19
+ - Preview swapping from different video frames
20
+ - Live Fake Cam using your webcam
21
+ - Extras Tab for cutting videos etc.
22
+ - Settings - storing configuration for next session
23
+ - Theme Support
24
+
25
+ and lots more...
26
+
27
+
28
+ ## Disclaimer
29
+
30
+ This project is for technical and academic use only.
31
+ Users of this software are expected to use this software responsibly while abiding the local law. If a face of a real person is being used, users are suggested to get consent from the concerned person and clearly mention that it is a deepfake when posting content online. Developers of this software will not be responsible for actions of end-users.
32
+ **Please do not apply it to illegal and unethical scenarios.**
33
+
34
+ In the event of violation of the legal and ethical requirements of the user's country or region, this code repository is exempt from liability
35
+
36
+ ### Installation
37
+
38
+ Please refer to the Wiki.
39
+
40
+
41
+
42
+
43
+ ### Usage
44
+
45
+ - Windows: run the `windows_run.bat` from the Installer.
46
+ - Linux: `python run.py`
47
+
48
+ <a target="_blank" href="https://colab.research.google.com/github/C0untFloyd/roop-unleashed/blob/main/roop-unleashed.ipynb">
49
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
50
+ </a>
51
+
52
+
53
+ Additional commandline arguments are currently unsupported and settings should be done via the UI.
54
+
55
+ > Note: When you run this program for the first time, it will download some models roughly ~2Gb in size.
56
+
57
+
58
+
59
+
60
+ ### Changelog
61
+
62
+ **08.01.2024** v3.5.0
63
+
64
+ - Bugfix: wrong access options when creating folders
65
+ - New auto rotation of horizontal faces, fixing bad landmark positions (expanded on ![PR 364](https://github.com/C0untFloyd/roop-unleashed/pull/364))
66
+ - Simple VR Option for stereo Images/Movies, best used in selected face mode
67
+ - Added RestoreFormer Enhancer - https://github.com/wzhouxiff/RestoreFormer
68
+ - Bumped up package versions for onnx/Torch etc.
69
+
70
+
71
+ **16.10.2023** v3.3.4
72
+
73
+ **11.8.2023** v2.7.0
74
+
75
+ Initial Gradio Version - old TkInter Version now deprecated
76
+
77
+ - Re-added unified padding to face enhancers
78
+ - Fixed DMDNet for all resolutions
79
+ - Selecting target face now automatically switches swapping mode to selected
80
+ - GPU providers are correctly set using the GUI (needs restart currently)
81
+ - Local output folder can be opened from page
82
+ - Unfinished extras functions disabled for now
83
+ - Installer checks out specific commit, allowing to go back to first install
84
+ - Updated readme for new gradio version
85
+ - Updated Colab
86
+
87
+
88
+ # Acknowledgements
89
+
90
+ Lots of ideas, code or pre-trained models used from the following projects:
91
+
92
+ https://github.com/deepinsight/insightface
93
+ https://github.com/s0md3v/roop
94
+ https://github.com/AUTOMATIC1111/stable-diffusion-webui
95
+ https://github.com/Hillobar/Rope
96
+ https://github.com/janvarev/chain-img-processor
97
+ https://github.com/TencentARC/GFPGAN
98
+ https://github.com/kadirnar/codeformer-pip
99
+ https://github.com/csxmli2016/DMDNet
100
+
101
+
102
+ Thanks to all developers!
103
+
clip/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .clip import *
clip/bpe_simple_vocab_16e6.txt ADDED
The diff for this file is too large to render. See raw diff
 
clip/clip.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import urllib
4
+ import warnings
5
+ from typing import Any, Union, List
6
+ from pkg_resources import packaging
7
+
8
+ import torch
9
+ from PIL import Image
10
+ from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
11
+ from tqdm import tqdm
12
+
13
+ from .model import build_model
14
+ from .simple_tokenizer import SimpleTokenizer as _Tokenizer
15
+
16
+ try:
17
+ from torchvision.transforms import InterpolationMode
18
+ BICUBIC = InterpolationMode.BICUBIC
19
+ except ImportError:
20
+ BICUBIC = Image.BICUBIC
21
+
22
+
23
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
24
+ warnings.warn("PyTorch version 1.7.1 or higher is recommended")
25
+
26
+
27
+ __all__ = ["available_models", "load", "tokenize"]
28
+ _tokenizer = _Tokenizer()
29
+
30
+ _MODELS = {
31
+ "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
32
+ "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
33
+ "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
34
+ "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
35
+ "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
36
+ "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
37
+ "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
38
+ "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
39
+ "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
40
+ }
41
+
42
+
43
+ def _download(url: str, root: str):
44
+ os.makedirs(root, exist_ok=True)
45
+ filename = os.path.basename(url)
46
+
47
+ expected_sha256 = url.split("/")[-2]
48
+ download_target = os.path.join(root, filename)
49
+
50
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
51
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
52
+
53
+ if os.path.isfile(download_target):
54
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
55
+ return download_target
56
+ else:
57
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
58
+
59
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
60
+ with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
61
+ while True:
62
+ buffer = source.read(8192)
63
+ if not buffer:
64
+ break
65
+
66
+ output.write(buffer)
67
+ loop.update(len(buffer))
68
+
69
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
70
+ raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
71
+
72
+ return download_target
73
+
74
+
75
+ def _convert_image_to_rgb(image):
76
+ return image.convert("RGB")
77
+
78
+
79
+ def _transform(n_px):
80
+ return Compose([
81
+ Resize(n_px, interpolation=BICUBIC),
82
+ CenterCrop(n_px),
83
+ _convert_image_to_rgb,
84
+ ToTensor(),
85
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
86
+ ])
87
+
88
+
89
+ def available_models() -> List[str]:
90
+ """Returns the names of available CLIP models"""
91
+ return list(_MODELS.keys())
92
+
93
+
94
+ def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None):
95
+ """Load a CLIP model
96
+
97
+ Parameters
98
+ ----------
99
+ name : str
100
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
101
+
102
+ device : Union[str, torch.device]
103
+ The device to put the loaded model
104
+
105
+ jit : bool
106
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
107
+
108
+ download_root: str
109
+ path to download the model files; by default, it uses "~/.cache/clip"
110
+
111
+ Returns
112
+ -------
113
+ model : torch.nn.Module
114
+ The CLIP model
115
+
116
+ preprocess : Callable[[PIL.Image], torch.Tensor]
117
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
118
+ """
119
+ if name in _MODELS:
120
+ model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
121
+ elif os.path.isfile(name):
122
+ model_path = name
123
+ else:
124
+ raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
125
+
126
+ with open(model_path, 'rb') as opened_file:
127
+ try:
128
+ # loading JIT archive
129
+ model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
130
+ state_dict = None
131
+ except RuntimeError:
132
+ # loading saved state dict
133
+ if jit:
134
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
135
+ jit = False
136
+ state_dict = torch.load(opened_file, map_location="cpu")
137
+
138
+ if not jit:
139
+ model = build_model(state_dict or model.state_dict()).to(device)
140
+ if str(device) == "cpu":
141
+ model.float()
142
+ return model, _transform(model.visual.input_resolution)
143
+
144
+ # patch the device names
145
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
146
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
147
+
148
+ def _node_get(node: torch._C.Node, key: str):
149
+ """Gets attributes of a node which is polymorphic over return type.
150
+
151
+ From https://github.com/pytorch/pytorch/pull/82628
152
+ """
153
+ sel = node.kindOf(key)
154
+ return getattr(node, sel)(key)
155
+
156
+ def patch_device(module):
157
+ try:
158
+ graphs = [module.graph] if hasattr(module, "graph") else []
159
+ except RuntimeError:
160
+ graphs = []
161
+
162
+ if hasattr(module, "forward1"):
163
+ graphs.append(module.forward1.graph)
164
+
165
+ for graph in graphs:
166
+ for node in graph.findAllNodes("prim::Constant"):
167
+ if "value" in node.attributeNames() and str(_node_get(node, "value")).startswith("cuda"):
168
+ node.copyAttributes(device_node)
169
+
170
+ model.apply(patch_device)
171
+ patch_device(model.encode_image)
172
+ patch_device(model.encode_text)
173
+
174
+ # patch dtype to float32 on CPU
175
+ if str(device) == "cpu":
176
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
177
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
178
+ float_node = float_input.node()
179
+
180
+ def patch_float(module):
181
+ try:
182
+ graphs = [module.graph] if hasattr(module, "graph") else []
183
+ except RuntimeError:
184
+ graphs = []
185
+
186
+ if hasattr(module, "forward1"):
187
+ graphs.append(module.forward1.graph)
188
+
189
+ for graph in graphs:
190
+ for node in graph.findAllNodes("aten::to"):
191
+ inputs = list(node.inputs())
192
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
193
+ if _node_get(inputs[i].node(), "value") == 5:
194
+ inputs[i].node().copyAttributes(float_node)
195
+
196
+ model.apply(patch_float)
197
+ patch_float(model.encode_image)
198
+ patch_float(model.encode_text)
199
+
200
+ model.float()
201
+
202
+ return model, _transform(model.input_resolution.item())
203
+
204
+
205
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> Union[torch.IntTensor, torch.LongTensor]:
206
+ """
207
+ Returns the tokenized representation of given input string(s)
208
+
209
+ Parameters
210
+ ----------
211
+ texts : Union[str, List[str]]
212
+ An input string or a list of input strings to tokenize
213
+
214
+ context_length : int
215
+ The context length to use; all CLIP models use 77 as the context length
216
+
217
+ truncate: bool
218
+ Whether to truncate the text in case its encoding is longer than the context length
219
+
220
+ Returns
221
+ -------
222
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
223
+ We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
224
+ """
225
+ if isinstance(texts, str):
226
+ texts = [texts]
227
+
228
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
229
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
230
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
231
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
232
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
233
+ else:
234
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
235
+
236
+ for i, tokens in enumerate(all_tokens):
237
+ if len(tokens) > context_length:
238
+ if truncate:
239
+ tokens = tokens[:context_length]
240
+ tokens[-1] = eot_token
241
+ else:
242
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
243
+ result[i, :len(tokens)] = torch.tensor(tokens)
244
+
245
+ return result
clip/clipseg.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from os.path import basename, dirname, join, isfile
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as nnf
6
+ from torch.nn.modules.activation import ReLU
7
+
8
+
9
+ def get_prompt_list(prompt):
10
+ if prompt == 'plain':
11
+ return ['{}']
12
+ elif prompt == 'fixed':
13
+ return ['a photo of a {}.']
14
+ elif prompt == 'shuffle':
15
+ return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.']
16
+ elif prompt == 'shuffle+':
17
+ return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.',
18
+ 'a cropped photo of a {}.', 'a good photo of a {}.', 'a photo of one {}.',
19
+ 'a bad photo of a {}.', 'a photo of the {}.']
20
+ else:
21
+ raise ValueError('Invalid value for prompt')
22
+
23
+
24
+ def forward_multihead_attention(x, b, with_aff=False, attn_mask=None):
25
+ """
26
+ Simplified version of multihead attention (taken from torch source code but without tons of if clauses).
27
+ The mlp and layer norm come from CLIP.
28
+ x: input.
29
+ b: multihead attention module.
30
+ """
31
+
32
+ x_ = b.ln_1(x)
33
+ q, k, v = nnf.linear(x_, b.attn.in_proj_weight, b.attn.in_proj_bias).chunk(3, dim=-1)
34
+ tgt_len, bsz, embed_dim = q.size()
35
+
36
+ head_dim = embed_dim // b.attn.num_heads
37
+ scaling = float(head_dim) ** -0.5
38
+
39
+ q = q.contiguous().view(tgt_len, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
40
+ k = k.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
41
+ v = v.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
42
+
43
+ q = q * scaling
44
+
45
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2)) # n_heads * batch_size, tokens^2, tokens^2
46
+ if attn_mask is not None:
47
+
48
+
49
+ attn_mask_type, attn_mask = attn_mask
50
+ n_heads = attn_output_weights.size(0) // attn_mask.size(0)
51
+ attn_mask = attn_mask.repeat(n_heads, 1)
52
+
53
+ if attn_mask_type == 'cls_token':
54
+ # the mask only affects similarities compared to the readout-token.
55
+ attn_output_weights[:, 0, 1:] = attn_output_weights[:, 0, 1:] * attn_mask[None,...]
56
+ # attn_output_weights[:, 0, 0] = 0*attn_output_weights[:, 0, 0]
57
+
58
+ if attn_mask_type == 'all':
59
+ # print(attn_output_weights.shape, attn_mask[:, None].shape)
60
+ attn_output_weights[:, 1:, 1:] = attn_output_weights[:, 1:, 1:] * attn_mask[:, None]
61
+
62
+
63
+ attn_output_weights = torch.softmax(attn_output_weights, dim=-1)
64
+
65
+ attn_output = torch.bmm(attn_output_weights, v)
66
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
67
+ attn_output = b.attn.out_proj(attn_output)
68
+
69
+ x = x + attn_output
70
+ x = x + b.mlp(b.ln_2(x))
71
+
72
+ if with_aff:
73
+ return x, attn_output_weights
74
+ else:
75
+ return x
76
+
77
+
78
+ class CLIPDenseBase(nn.Module):
79
+
80
+ def __init__(self, version, reduce_cond, reduce_dim, prompt, n_tokens):
81
+ super().__init__()
82
+
83
+ import clip
84
+
85
+ # prec = torch.FloatTensor
86
+ self.clip_model, _ = clip.load(version, device='cpu', jit=False)
87
+ self.model = self.clip_model.visual
88
+
89
+ # if not None, scale conv weights such that we obtain n_tokens.
90
+ self.n_tokens = n_tokens
91
+
92
+ for p in self.clip_model.parameters():
93
+ p.requires_grad_(False)
94
+
95
+ # conditional
96
+ if reduce_cond is not None:
97
+ self.reduce_cond = nn.Linear(512, reduce_cond)
98
+ for p in self.reduce_cond.parameters():
99
+ p.requires_grad_(False)
100
+ else:
101
+ self.reduce_cond = None
102
+
103
+ self.film_mul = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
104
+ self.film_add = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
105
+
106
+ self.reduce = nn.Linear(768, reduce_dim)
107
+
108
+ self.prompt_list = get_prompt_list(prompt)
109
+
110
+ # precomputed prompts
111
+ import pickle
112
+ if isfile('precomputed_prompt_vectors.pickle'):
113
+ precomp = pickle.load(open('precomputed_prompt_vectors.pickle', 'rb'))
114
+ self.precomputed_prompts = {k: torch.from_numpy(v) for k, v in precomp.items()}
115
+ else:
116
+ self.precomputed_prompts = dict()
117
+
118
+ def rescaled_pos_emb(self, new_size):
119
+ assert len(new_size) == 2
120
+
121
+ a = self.model.positional_embedding[1:].T.view(1, 768, *self.token_shape)
122
+ b = nnf.interpolate(a, new_size, mode='bicubic', align_corners=False).squeeze(0).view(768, new_size[0]*new_size[1]).T
123
+ return torch.cat([self.model.positional_embedding[:1], b])
124
+
125
+ def visual_forward(self, x_inp, extract_layers=(), skip=False, mask=None):
126
+
127
+
128
+ with torch.no_grad():
129
+
130
+ inp_size = x_inp.shape[2:]
131
+
132
+ if self.n_tokens is not None:
133
+ stride2 = x_inp.shape[2] // self.n_tokens
134
+ conv_weight2 = nnf.interpolate(self.model.conv1.weight, (stride2, stride2), mode='bilinear', align_corners=True)
135
+ x = nnf.conv2d(x_inp, conv_weight2, bias=self.model.conv1.bias, stride=stride2, dilation=self.model.conv1.dilation)
136
+ else:
137
+ x = self.model.conv1(x_inp) # shape = [*, width, grid, grid]
138
+
139
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
140
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
141
+
142
+ x = torch.cat([self.model.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
143
+
144
+ standard_n_tokens = 50 if self.model.conv1.kernel_size[0] == 32 else 197
145
+
146
+ if x.shape[1] != standard_n_tokens:
147
+ new_shape = int(math.sqrt(x.shape[1]-1))
148
+ x = x + self.rescaled_pos_emb((new_shape, new_shape)).to(x.dtype)[None,:,:]
149
+ else:
150
+ x = x + self.model.positional_embedding.to(x.dtype)
151
+
152
+ x = self.model.ln_pre(x)
153
+
154
+ x = x.permute(1, 0, 2) # NLD -> LND
155
+
156
+ activations, affinities = [], []
157
+ for i, res_block in enumerate(self.model.transformer.resblocks):
158
+
159
+ if mask is not None:
160
+ mask_layer, mask_type, mask_tensor = mask
161
+ if mask_layer == i or mask_layer == 'all':
162
+ # import ipdb; ipdb.set_trace()
163
+ size = int(math.sqrt(x.shape[0] - 1))
164
+
165
+ attn_mask = (mask_type, nnf.interpolate(mask_tensor.unsqueeze(1).float(), (size, size)).view(mask_tensor.shape[0], size * size))
166
+
167
+ else:
168
+ attn_mask = None
169
+ else:
170
+ attn_mask = None
171
+
172
+ x, aff_per_head = forward_multihead_attention(x, res_block, with_aff=True, attn_mask=attn_mask)
173
+
174
+ if i in extract_layers:
175
+ affinities += [aff_per_head]
176
+
177
+ #if self.n_tokens is not None:
178
+ # activations += [nnf.interpolate(x, inp_size, mode='bilinear', align_corners=True)]
179
+ #else:
180
+ activations += [x]
181
+
182
+ if len(extract_layers) > 0 and i == max(extract_layers) and skip:
183
+ print('early skip')
184
+ break
185
+
186
+ x = x.permute(1, 0, 2) # LND -> NLD
187
+ x = self.model.ln_post(x[:, 0, :])
188
+
189
+ if self.model.proj is not None:
190
+ x = x @ self.model.proj
191
+
192
+ return x, activations, affinities
193
+
194
+ def sample_prompts(self, words, prompt_list=None):
195
+
196
+ prompt_list = prompt_list if prompt_list is not None else self.prompt_list
197
+
198
+ prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True)
199
+ prompts = [prompt_list[i] for i in prompt_indices]
200
+ return [promt.format(w) for promt, w in zip(prompts, words)]
201
+
202
+ def get_cond_vec(self, conditional, batch_size):
203
+ # compute conditional from a single string
204
+ if conditional is not None and type(conditional) == str:
205
+ cond = self.compute_conditional(conditional)
206
+ cond = cond.repeat(batch_size, 1)
207
+
208
+ # compute conditional from string list/tuple
209
+ elif conditional is not None and type(conditional) in {list, tuple} and type(conditional[0]) == str:
210
+ assert len(conditional) == batch_size
211
+ cond = self.compute_conditional(conditional)
212
+
213
+ # use conditional directly
214
+ elif conditional is not None and type(conditional) == torch.Tensor and conditional.ndim == 2:
215
+ cond = conditional
216
+
217
+ # compute conditional from image
218
+ elif conditional is not None and type(conditional) == torch.Tensor:
219
+ with torch.no_grad():
220
+ cond, _, _ = self.visual_forward(conditional)
221
+ else:
222
+ raise ValueError('invalid conditional')
223
+ return cond
224
+
225
+ def compute_conditional(self, conditional):
226
+ import clip
227
+
228
+ dev = next(self.parameters()).device
229
+
230
+ if type(conditional) in {list, tuple}:
231
+ text_tokens = clip.tokenize(conditional).to(dev)
232
+ cond = self.clip_model.encode_text(text_tokens)
233
+ else:
234
+ if conditional in self.precomputed_prompts:
235
+ cond = self.precomputed_prompts[conditional].float().to(dev)
236
+ else:
237
+ text_tokens = clip.tokenize([conditional]).to(dev)
238
+ cond = self.clip_model.encode_text(text_tokens)[0]
239
+
240
+ if self.shift_vector is not None:
241
+ return cond + self.shift_vector
242
+ else:
243
+ return cond
244
+
245
+
246
+ def clip_load_untrained(version):
247
+ assert version == 'ViT-B/16'
248
+ from clip.model import CLIP
249
+ from clip.clip import _MODELS, _download
250
+ model = torch.jit.load(_download(_MODELS['ViT-B/16'])).eval()
251
+ state_dict = model.state_dict()
252
+
253
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
254
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
255
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
256
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
257
+ image_resolution = vision_patch_size * grid_size
258
+ embed_dim = state_dict["text_projection"].shape[1]
259
+ context_length = state_dict["positional_embedding"].shape[0]
260
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
261
+ transformer_width = state_dict["ln_final.weight"].shape[0]
262
+ transformer_heads = transformer_width // 64
263
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
264
+
265
+ return CLIP(embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size,
266
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers)
267
+
268
+
269
+ class CLIPDensePredT(CLIPDenseBase):
270
+
271
+ def __init__(self, version='ViT-B/32', extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4, prompt='fixed',
272
+ extra_blocks=0, reduce_cond=None, fix_shift=False,
273
+ learn_trans_conv_only=False, limit_to_clip_only=False, upsample=False,
274
+ add_calibration=False, rev_activations=False, trans_conv=None, n_tokens=None, complex_trans_conv=False):
275
+
276
+ super().__init__(version, reduce_cond, reduce_dim, prompt, n_tokens)
277
+ # device = 'cpu'
278
+
279
+ self.extract_layers = extract_layers
280
+ self.cond_layer = cond_layer
281
+ self.limit_to_clip_only = limit_to_clip_only
282
+ self.process_cond = None
283
+ self.rev_activations = rev_activations
284
+
285
+ depth = len(extract_layers)
286
+
287
+ if add_calibration:
288
+ self.calibration_conds = 1
289
+
290
+ self.upsample_proj = nn.Conv2d(reduce_dim, 1, kernel_size=1) if upsample else None
291
+
292
+ self.add_activation1 = True
293
+
294
+ self.version = version
295
+
296
+ self.token_shape = {'ViT-B/32': (7, 7), 'ViT-B/16': (14, 14)}[version]
297
+
298
+ if fix_shift:
299
+ # self.shift_vector = nn.Parameter(torch.load(join(dirname(basename(__file__)), 'clip_text_shift_vector.pth')), requires_grad=False)
300
+ self.shift_vector = nn.Parameter(torch.load(join(dirname(basename(__file__)), 'shift_text_to_vis.pth')), requires_grad=False)
301
+ # self.shift_vector = nn.Parameter(-1*torch.load(join(dirname(basename(__file__)), 'shift2.pth')), requires_grad=False)
302
+ else:
303
+ self.shift_vector = None
304
+
305
+ if trans_conv is None:
306
+ trans_conv_ks = {'ViT-B/32': (32, 32), 'ViT-B/16': (16, 16)}[version]
307
+ else:
308
+ # explicitly define transposed conv kernel size
309
+ trans_conv_ks = (trans_conv, trans_conv)
310
+
311
+ if not complex_trans_conv:
312
+ self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
313
+ else:
314
+ assert trans_conv_ks[0] == trans_conv_ks[1]
315
+
316
+ tp_kernels = (trans_conv_ks[0] // 4, trans_conv_ks[0] // 4)
317
+
318
+ self.trans_conv = nn.Sequential(
319
+ nn.Conv2d(reduce_dim, reduce_dim, kernel_size=3, padding=1),
320
+ nn.ReLU(),
321
+ nn.ConvTranspose2d(reduce_dim, reduce_dim // 2, kernel_size=tp_kernels[0], stride=tp_kernels[0]),
322
+ nn.ReLU(),
323
+ nn.ConvTranspose2d(reduce_dim // 2, 1, kernel_size=tp_kernels[1], stride=tp_kernels[1]),
324
+ )
325
+
326
+ # self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
327
+
328
+ assert len(self.extract_layers) == depth
329
+
330
+ self.reduces = nn.ModuleList([nn.Linear(768, reduce_dim) for _ in range(depth)])
331
+ self.blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(len(self.extract_layers))])
332
+ self.extra_blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(extra_blocks)])
333
+
334
+ # refinement and trans conv
335
+
336
+ if learn_trans_conv_only:
337
+ for p in self.parameters():
338
+ p.requires_grad_(False)
339
+
340
+ for p in self.trans_conv.parameters():
341
+ p.requires_grad_(True)
342
+
343
+ self.prompt_list = get_prompt_list(prompt)
344
+
345
+
346
+ def forward(self, inp_image, conditional=None, return_features=False, mask=None):
347
+
348
+ assert type(return_features) == bool
349
+
350
+ inp_image = inp_image.to(self.model.positional_embedding.device)
351
+
352
+ if mask is not None:
353
+ raise ValueError('mask not supported')
354
+
355
+ # x_inp = normalize(inp_image)
356
+ x_inp = inp_image
357
+
358
+ bs, dev = inp_image.shape[0], x_inp.device
359
+
360
+ cond = self.get_cond_vec(conditional, bs)
361
+
362
+ visual_q, activations, _ = self.visual_forward(x_inp, extract_layers=[0] + list(self.extract_layers))
363
+
364
+ activation1 = activations[0]
365
+ activations = activations[1:]
366
+
367
+ _activations = activations[::-1] if not self.rev_activations else activations
368
+
369
+ a = None
370
+ for i, (activation, block, reduce) in enumerate(zip(_activations, self.blocks, self.reduces)):
371
+
372
+ if a is not None:
373
+ a = reduce(activation) + a
374
+ else:
375
+ a = reduce(activation)
376
+
377
+ if i == self.cond_layer:
378
+ if self.reduce_cond is not None:
379
+ cond = self.reduce_cond(cond)
380
+
381
+ a = self.film_mul(cond) * a + self.film_add(cond)
382
+
383
+ a = block(a)
384
+
385
+ for block in self.extra_blocks:
386
+ a = a + block(a)
387
+
388
+ a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens
389
+
390
+ size = int(math.sqrt(a.shape[2]))
391
+
392
+ a = a.view(bs, a.shape[1], size, size)
393
+
394
+ a = self.trans_conv(a)
395
+
396
+ if self.n_tokens is not None:
397
+ a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear', align_corners=True)
398
+
399
+ if self.upsample_proj is not None:
400
+ a = self.upsample_proj(a)
401
+ a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear')
402
+
403
+ if return_features:
404
+ return a, visual_q, cond, [activation1] + activations
405
+ else:
406
+ return a,
407
+
408
+
409
+
410
+ class CLIPDensePredTMasked(CLIPDensePredT):
411
+
412
+ def __init__(self, version='ViT-B/32', extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4,
413
+ prompt='fixed', extra_blocks=0, reduce_cond=None, fix_shift=False, learn_trans_conv_only=False,
414
+ refine=None, limit_to_clip_only=False, upsample=False, add_calibration=False, n_tokens=None):
415
+
416
+ super().__init__(version=version, extract_layers=extract_layers, cond_layer=cond_layer, reduce_dim=reduce_dim,
417
+ n_heads=n_heads, prompt=prompt, extra_blocks=extra_blocks, reduce_cond=reduce_cond,
418
+ fix_shift=fix_shift, learn_trans_conv_only=learn_trans_conv_only,
419
+ limit_to_clip_only=limit_to_clip_only, upsample=upsample, add_calibration=add_calibration,
420
+ n_tokens=n_tokens)
421
+
422
+ def visual_forward_masked(self, img_s, seg_s):
423
+ return super().visual_forward(img_s, mask=('all', 'cls_token', seg_s))
424
+
425
+ def forward(self, img_q, cond_or_img_s, seg_s=None, return_features=False):
426
+
427
+ if seg_s is None:
428
+ cond = cond_or_img_s
429
+ else:
430
+ img_s = cond_or_img_s
431
+
432
+ with torch.no_grad():
433
+ cond, _, _ = self.visual_forward_masked(img_s, seg_s)
434
+
435
+ return super().forward(img_q, cond, return_features=return_features)
436
+
437
+
438
+
439
+ class CLIPDenseBaseline(CLIPDenseBase):
440
+
441
+ def __init__(self, version='ViT-B/32', cond_layer=0,
442
+ extract_layer=9, reduce_dim=128, reduce2_dim=None, prompt='fixed',
443
+ reduce_cond=None, limit_to_clip_only=False, n_tokens=None):
444
+
445
+ super().__init__(version, reduce_cond, reduce_dim, prompt, n_tokens)
446
+ device = 'cpu'
447
+
448
+ # self.cond_layer = cond_layer
449
+ self.extract_layer = extract_layer
450
+ self.limit_to_clip_only = limit_to_clip_only
451
+ self.shift_vector = None
452
+
453
+ self.token_shape = {'ViT-B/32': (7, 7), 'ViT-B/16': (14, 14)}[version]
454
+
455
+ assert reduce2_dim is not None
456
+
457
+ self.reduce2 = nn.Sequential(
458
+ nn.Linear(reduce_dim, reduce2_dim),
459
+ nn.ReLU(),
460
+ nn.Linear(reduce2_dim, reduce_dim)
461
+ )
462
+
463
+ trans_conv_ks = {'ViT-B/32': (32, 32), 'ViT-B/16': (16, 16)}[version]
464
+ self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
465
+
466
+
467
+ def forward(self, inp_image, conditional=None, return_features=False):
468
+
469
+ inp_image = inp_image.to(self.model.positional_embedding.device)
470
+
471
+ # x_inp = normalize(inp_image)
472
+ x_inp = inp_image
473
+
474
+ bs, dev = inp_image.shape[0], x_inp.device
475
+
476
+ cond = self.get_cond_vec(conditional, bs)
477
+
478
+ visual_q, activations, affinities = self.visual_forward(x_inp, extract_layers=[self.extract_layer])
479
+
480
+ a = activations[0]
481
+ a = self.reduce(a)
482
+ a = self.film_mul(cond) * a + self.film_add(cond)
483
+
484
+ if self.reduce2 is not None:
485
+ a = self.reduce2(a)
486
+
487
+ # the original model would execute a transformer block here
488
+
489
+ a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens
490
+
491
+ size = int(math.sqrt(a.shape[2]))
492
+
493
+ a = a.view(bs, a.shape[1], size, size)
494
+ a = self.trans_conv(a)
495
+
496
+ if return_features:
497
+ return a, visual_q, cond, activations
498
+ else:
499
+ return a,
500
+
501
+
502
+ class CLIPSegMultiLabel(nn.Module):
503
+
504
+ def __init__(self, model) -> None:
505
+ super().__init__()
506
+
507
+ from third_party.JoEm.data_loader import get_seen_idx, get_unseen_idx, VOC
508
+
509
+ self.pascal_classes = VOC
510
+
511
+ from clip.clipseg import CLIPDensePredT
512
+ from general_utils import load_model
513
+ # self.clipseg = load_model('rd64-vit16-neg0.2-phrasecut', strict=False)
514
+ self.clipseg = load_model(model, strict=False)
515
+
516
+ self.clipseg.eval()
517
+
518
+ def forward(self, x):
519
+
520
+ bs = x.shape[0]
521
+ out = torch.ones(21, bs, 352, 352).to(x.device) * -10
522
+
523
+ for class_id, class_name in enumerate(self.pascal_classes):
524
+
525
+ fac = 3 if class_name == 'background' else 1
526
+
527
+ with torch.no_grad():
528
+ pred = torch.sigmoid(self.clipseg(x, class_name)[0][:,0]) * fac
529
+
530
+ out[class_id] += pred
531
+
532
+
533
+ out = out.permute(1, 0, 2, 3)
534
+
535
+ return out
536
+
537
+ # construct output tensor
538
+
clip/model.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+
10
+ class Bottleneck(nn.Module):
11
+ expansion = 4
12
+
13
+ def __init__(self, inplanes, planes, stride=1):
14
+ super().__init__()
15
+
16
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
17
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
18
+ self.bn1 = nn.BatchNorm2d(planes)
19
+ self.relu1 = nn.ReLU(inplace=True)
20
+
21
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
22
+ self.bn2 = nn.BatchNorm2d(planes)
23
+ self.relu2 = nn.ReLU(inplace=True)
24
+
25
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
26
+
27
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
28
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
29
+ self.relu3 = nn.ReLU(inplace=True)
30
+
31
+ self.downsample = None
32
+ self.stride = stride
33
+
34
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
35
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
36
+ self.downsample = nn.Sequential(OrderedDict([
37
+ ("-1", nn.AvgPool2d(stride)),
38
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
39
+ ("1", nn.BatchNorm2d(planes * self.expansion))
40
+ ]))
41
+
42
+ def forward(self, x: torch.Tensor):
43
+ identity = x
44
+
45
+ out = self.relu1(self.bn1(self.conv1(x)))
46
+ out = self.relu2(self.bn2(self.conv2(out)))
47
+ out = self.avgpool(out)
48
+ out = self.bn3(self.conv3(out))
49
+
50
+ if self.downsample is not None:
51
+ identity = self.downsample(x)
52
+
53
+ out += identity
54
+ out = self.relu3(out)
55
+ return out
56
+
57
+
58
+ class AttentionPool2d(nn.Module):
59
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
60
+ super().__init__()
61
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
62
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
63
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
64
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
65
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
66
+ self.num_heads = num_heads
67
+
68
+ def forward(self, x):
69
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
70
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
71
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
72
+ x, _ = F.multi_head_attention_forward(
73
+ query=x[:1], key=x, value=x,
74
+ embed_dim_to_check=x.shape[-1],
75
+ num_heads=self.num_heads,
76
+ q_proj_weight=self.q_proj.weight,
77
+ k_proj_weight=self.k_proj.weight,
78
+ v_proj_weight=self.v_proj.weight,
79
+ in_proj_weight=None,
80
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
81
+ bias_k=None,
82
+ bias_v=None,
83
+ add_zero_attn=False,
84
+ dropout_p=0,
85
+ out_proj_weight=self.c_proj.weight,
86
+ out_proj_bias=self.c_proj.bias,
87
+ use_separate_proj_weight=True,
88
+ training=self.training,
89
+ need_weights=False
90
+ )
91
+ return x.squeeze(0)
92
+
93
+
94
+ class ModifiedResNet(nn.Module):
95
+ """
96
+ A ResNet class that is similar to torchvision's but contains the following changes:
97
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
98
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
99
+ - The final pooling layer is a QKV attention instead of an average pool
100
+ """
101
+
102
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
103
+ super().__init__()
104
+ self.output_dim = output_dim
105
+ self.input_resolution = input_resolution
106
+
107
+ # the 3-layer stem
108
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
109
+ self.bn1 = nn.BatchNorm2d(width // 2)
110
+ self.relu1 = nn.ReLU(inplace=True)
111
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
112
+ self.bn2 = nn.BatchNorm2d(width // 2)
113
+ self.relu2 = nn.ReLU(inplace=True)
114
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
115
+ self.bn3 = nn.BatchNorm2d(width)
116
+ self.relu3 = nn.ReLU(inplace=True)
117
+ self.avgpool = nn.AvgPool2d(2)
118
+
119
+ # residual layers
120
+ self._inplanes = width # this is a *mutable* variable used during construction
121
+ self.layer1 = self._make_layer(width, layers[0])
122
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
123
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
124
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
125
+
126
+ embed_dim = width * 32 # the ResNet feature dimension
127
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
128
+
129
+ def _make_layer(self, planes, blocks, stride=1):
130
+ layers = [Bottleneck(self._inplanes, planes, stride)]
131
+
132
+ self._inplanes = planes * Bottleneck.expansion
133
+ for _ in range(1, blocks):
134
+ layers.append(Bottleneck(self._inplanes, planes))
135
+
136
+ return nn.Sequential(*layers)
137
+
138
+ def forward(self, x):
139
+ def stem(x):
140
+ x = self.relu1(self.bn1(self.conv1(x)))
141
+ x = self.relu2(self.bn2(self.conv2(x)))
142
+ x = self.relu3(self.bn3(self.conv3(x)))
143
+ x = self.avgpool(x)
144
+ return x
145
+
146
+ x = x.type(self.conv1.weight.dtype)
147
+ x = stem(x)
148
+ x = self.layer1(x)
149
+ x = self.layer2(x)
150
+ x = self.layer3(x)
151
+ x = self.layer4(x)
152
+ x = self.attnpool(x)
153
+
154
+ return x
155
+
156
+
157
+ class LayerNorm(nn.LayerNorm):
158
+ """Subclass torch's LayerNorm to handle fp16."""
159
+
160
+ def forward(self, x: torch.Tensor):
161
+ orig_type = x.dtype
162
+ ret = super().forward(x.type(torch.float32))
163
+ return ret.type(orig_type)
164
+
165
+
166
+ class QuickGELU(nn.Module):
167
+ def forward(self, x: torch.Tensor):
168
+ return x * torch.sigmoid(1.702 * x)
169
+
170
+
171
+ class ResidualAttentionBlock(nn.Module):
172
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
173
+ super().__init__()
174
+
175
+ self.attn = nn.MultiheadAttention(d_model, n_head)
176
+ self.ln_1 = LayerNorm(d_model)
177
+ self.mlp = nn.Sequential(OrderedDict([
178
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
179
+ ("gelu", QuickGELU()),
180
+ ("c_proj", nn.Linear(d_model * 4, d_model))
181
+ ]))
182
+ self.ln_2 = LayerNorm(d_model)
183
+ self.attn_mask = attn_mask
184
+
185
+ def attention(self, x: torch.Tensor):
186
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
187
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
188
+
189
+ def forward(self, x: torch.Tensor):
190
+ x = x + self.attention(self.ln_1(x))
191
+ x = x + self.mlp(self.ln_2(x))
192
+ return x
193
+
194
+
195
+ class Transformer(nn.Module):
196
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
197
+ super().__init__()
198
+ self.width = width
199
+ self.layers = layers
200
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
201
+
202
+ def forward(self, x: torch.Tensor):
203
+ return self.resblocks(x)
204
+
205
+
206
+ class VisionTransformer(nn.Module):
207
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
208
+ super().__init__()
209
+ self.input_resolution = input_resolution
210
+ self.output_dim = output_dim
211
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
212
+
213
+ scale = width ** -0.5
214
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
215
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
216
+ self.ln_pre = LayerNorm(width)
217
+
218
+ self.transformer = Transformer(width, layers, heads)
219
+
220
+ self.ln_post = LayerNorm(width)
221
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
222
+
223
+ def forward(self, x: torch.Tensor):
224
+ x = self.conv1(x) # shape = [*, width, grid, grid]
225
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
226
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
227
+ x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
228
+ x = x + self.positional_embedding.to(x.dtype)
229
+ x = self.ln_pre(x)
230
+
231
+ x = x.permute(1, 0, 2) # NLD -> LND
232
+ x = self.transformer(x)
233
+ x = x.permute(1, 0, 2) # LND -> NLD
234
+
235
+ x = self.ln_post(x[:, 0, :])
236
+
237
+ if self.proj is not None:
238
+ x = x @ self.proj
239
+
240
+ return x
241
+
242
+
243
+ class CLIP(nn.Module):
244
+ def __init__(self,
245
+ embed_dim: int,
246
+ # vision
247
+ image_resolution: int,
248
+ vision_layers: Union[Tuple[int, int, int, int], int],
249
+ vision_width: int,
250
+ vision_patch_size: int,
251
+ # text
252
+ context_length: int,
253
+ vocab_size: int,
254
+ transformer_width: int,
255
+ transformer_heads: int,
256
+ transformer_layers: int
257
+ ):
258
+ super().__init__()
259
+
260
+ self.context_length = context_length
261
+
262
+ if isinstance(vision_layers, (tuple, list)):
263
+ vision_heads = vision_width * 32 // 64
264
+ self.visual = ModifiedResNet(
265
+ layers=vision_layers,
266
+ output_dim=embed_dim,
267
+ heads=vision_heads,
268
+ input_resolution=image_resolution,
269
+ width=vision_width
270
+ )
271
+ else:
272
+ vision_heads = vision_width // 64
273
+ self.visual = VisionTransformer(
274
+ input_resolution=image_resolution,
275
+ patch_size=vision_patch_size,
276
+ width=vision_width,
277
+ layers=vision_layers,
278
+ heads=vision_heads,
279
+ output_dim=embed_dim
280
+ )
281
+
282
+ self.transformer = Transformer(
283
+ width=transformer_width,
284
+ layers=transformer_layers,
285
+ heads=transformer_heads,
286
+ attn_mask=self.build_attention_mask()
287
+ )
288
+
289
+ self.vocab_size = vocab_size
290
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
291
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
292
+ self.ln_final = LayerNorm(transformer_width)
293
+
294
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
295
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
296
+
297
+ self.initialize_parameters()
298
+
299
+ def initialize_parameters(self):
300
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
301
+ nn.init.normal_(self.positional_embedding, std=0.01)
302
+
303
+ if isinstance(self.visual, ModifiedResNet):
304
+ if self.visual.attnpool is not None:
305
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
306
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
307
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
308
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
309
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
310
+
311
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
312
+ for name, param in resnet_block.named_parameters():
313
+ if name.endswith("bn3.weight"):
314
+ nn.init.zeros_(param)
315
+
316
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
317
+ attn_std = self.transformer.width ** -0.5
318
+ fc_std = (2 * self.transformer.width) ** -0.5
319
+ for block in self.transformer.resblocks:
320
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
321
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
322
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
323
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
324
+
325
+ if self.text_projection is not None:
326
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
327
+
328
+ def build_attention_mask(self):
329
+ # lazily create causal attention mask, with full attention between the vision tokens
330
+ # pytorch uses additive attention mask; fill with -inf
331
+ mask = torch.empty(self.context_length, self.context_length)
332
+ mask.fill_(float("-inf"))
333
+ mask.triu_(1) # zero out the lower diagonal
334
+ return mask
335
+
336
+ @property
337
+ def dtype(self):
338
+ return self.visual.conv1.weight.dtype
339
+
340
+ def encode_image(self, image):
341
+ return self.visual(image.type(self.dtype))
342
+
343
+ def encode_text(self, text):
344
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
345
+
346
+ x = x + self.positional_embedding.type(self.dtype)
347
+ x = x.permute(1, 0, 2) # NLD -> LND
348
+ x = self.transformer(x)
349
+ x = x.permute(1, 0, 2) # LND -> NLD
350
+ x = self.ln_final(x).type(self.dtype)
351
+
352
+ # x.shape = [batch_size, n_ctx, transformer.width]
353
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
354
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
355
+
356
+ return x
357
+
358
+ def forward(self, image, text):
359
+ image_features = self.encode_image(image)
360
+ text_features = self.encode_text(text)
361
+
362
+ # normalized features
363
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
364
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
365
+
366
+ # cosine similarity as logits
367
+ logit_scale = self.logit_scale.exp()
368
+ logits_per_image = logit_scale * image_features @ text_features.t()
369
+ logits_per_text = logits_per_image.t()
370
+
371
+ # shape = [global_batch_size, global_batch_size]
372
+ return logits_per_image, logits_per_text
373
+
374
+
375
+ def convert_weights(model: nn.Module):
376
+ """Convert applicable model parameters to fp16"""
377
+
378
+ def _convert_weights_to_fp16(l):
379
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
380
+ l.weight.data = l.weight.data.half()
381
+ if l.bias is not None:
382
+ l.bias.data = l.bias.data.half()
383
+
384
+ if isinstance(l, nn.MultiheadAttention):
385
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
386
+ tensor = getattr(l, attr)
387
+ if tensor is not None:
388
+ tensor.data = tensor.data.half()
389
+
390
+ for name in ["text_projection", "proj"]:
391
+ if hasattr(l, name):
392
+ attr = getattr(l, name)
393
+ if attr is not None:
394
+ attr.data = attr.data.half()
395
+
396
+ model.apply(_convert_weights_to_fp16)
397
+
398
+
399
+ def build_model(state_dict: dict):
400
+ vit = "visual.proj" in state_dict
401
+
402
+ if vit:
403
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
404
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
405
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
406
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
407
+ image_resolution = vision_patch_size * grid_size
408
+ else:
409
+ counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
410
+ vision_layers = tuple(counts)
411
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
412
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
413
+ vision_patch_size = None
414
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
415
+ image_resolution = output_width * 32
416
+
417
+ embed_dim = state_dict["text_projection"].shape[1]
418
+ context_length = state_dict["positional_embedding"].shape[0]
419
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
420
+ transformer_width = state_dict["ln_final.weight"].shape[0]
421
+ transformer_heads = transformer_width // 64
422
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
423
+
424
+ model = CLIP(
425
+ embed_dim,
426
+ image_resolution, vision_layers, vision_width, vision_patch_size,
427
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
428
+ )
429
+
430
+ for key in ["input_resolution", "context_length", "vocab_size"]:
431
+ if key in state_dict:
432
+ del state_dict[key]
433
+
434
+ convert_weights(model)
435
+ model.load_state_dict(state_dict)
436
+ return model.eval()
clip/simple_tokenizer.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import html
3
+ import os
4
+ from functools import lru_cache
5
+
6
+ import ftfy
7
+ import regex as re
8
+
9
+
10
+ @lru_cache()
11
+ def default_bpe():
12
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
13
+
14
+
15
+ @lru_cache()
16
+ def bytes_to_unicode():
17
+ """
18
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
19
+ The reversible bpe codes work on unicode strings.
20
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
21
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
22
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
23
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
24
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
25
+ """
26
+ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
27
+ cs = bs[:]
28
+ n = 0
29
+ for b in range(2**8):
30
+ if b not in bs:
31
+ bs.append(b)
32
+ cs.append(2**8+n)
33
+ n += 1
34
+ cs = [chr(n) for n in cs]
35
+ return dict(zip(bs, cs))
36
+
37
+
38
+ def get_pairs(word):
39
+ """Return set of symbol pairs in a word.
40
+ Word is represented as tuple of symbols (symbols being variable-length strings).
41
+ """
42
+ pairs = set()
43
+ prev_char = word[0]
44
+ for char in word[1:]:
45
+ pairs.add((prev_char, char))
46
+ prev_char = char
47
+ return pairs
48
+
49
+
50
+ def basic_clean(text):
51
+ text = ftfy.fix_text(text)
52
+ text = html.unescape(html.unescape(text))
53
+ return text.strip()
54
+
55
+
56
+ def whitespace_clean(text):
57
+ text = re.sub(r'\s+', ' ', text)
58
+ text = text.strip()
59
+ return text
60
+
61
+
62
+ class SimpleTokenizer(object):
63
+ def __init__(self, bpe_path: str = default_bpe()):
64
+ self.byte_encoder = bytes_to_unicode()
65
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
66
+ merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
67
+ merges = merges[1:49152-256-2+1]
68
+ merges = [tuple(merge.split()) for merge in merges]
69
+ vocab = list(bytes_to_unicode().values())
70
+ vocab = vocab + [v+'</w>' for v in vocab]
71
+ for merge in merges:
72
+ vocab.append(''.join(merge))
73
+ vocab.extend(['<|startoftext|>', '<|endoftext|>'])
74
+ self.encoder = dict(zip(vocab, range(len(vocab))))
75
+ self.decoder = {v: k for k, v in self.encoder.items()}
76
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
77
+ self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
78
+ self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
79
+
80
+ def bpe(self, token):
81
+ if token in self.cache:
82
+ return self.cache[token]
83
+ word = tuple(token[:-1]) + ( token[-1] + '</w>',)
84
+ pairs = get_pairs(word)
85
+
86
+ if not pairs:
87
+ return token+'</w>'
88
+
89
+ while True:
90
+ bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
91
+ if bigram not in self.bpe_ranks:
92
+ break
93
+ first, second = bigram
94
+ new_word = []
95
+ i = 0
96
+ while i < len(word):
97
+ try:
98
+ j = word.index(first, i)
99
+ new_word.extend(word[i:j])
100
+ i = j
101
+ except:
102
+ new_word.extend(word[i:])
103
+ break
104
+
105
+ if word[i] == first and i < len(word)-1 and word[i+1] == second:
106
+ new_word.append(first+second)
107
+ i += 2
108
+ else:
109
+ new_word.append(word[i])
110
+ i += 1
111
+ new_word = tuple(new_word)
112
+ word = new_word
113
+ if len(word) == 1:
114
+ break
115
+ else:
116
+ pairs = get_pairs(word)
117
+ word = ' '.join(word)
118
+ self.cache[token] = word
119
+ return word
120
+
121
+ def encode(self, text):
122
+ bpe_tokens = []
123
+ text = whitespace_clean(basic_clean(text)).lower()
124
+ for token in re.findall(self.pat, text):
125
+ token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
126
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
127
+ return bpe_tokens
128
+
129
+ def decode(self, tokens):
130
+ text = ''.join([self.decoder[token] for token in tokens])
131
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
132
+ return text
clip/vitseg.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from posixpath import basename, dirname, join
3
+ # import clip
4
+ from clip.model import convert_weights
5
+ import torch
6
+ import json
7
+ from torch import nn
8
+ from torch.nn import functional as nnf
9
+ from torch.nn.modules import activation
10
+ from torch.nn.modules.activation import ReLU
11
+ from torchvision import transforms
12
+
13
+ normalize = transforms.Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711))
14
+
15
+ from torchvision.models import ResNet
16
+
17
+
18
+ def process_prompts(conditional, prompt_list, conditional_map):
19
+ # DEPRECATED
20
+
21
+ # randomly sample a synonym
22
+ words = [conditional_map[int(i)] for i in conditional]
23
+ words = [syns[torch.multinomial(torch.ones(len(syns)), 1, replacement=True).item()] for syns in words]
24
+ words = [w.replace('_', ' ') for w in words]
25
+
26
+ if prompt_list is not None:
27
+ prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True)
28
+ prompts = [prompt_list[i] for i in prompt_indices]
29
+ else:
30
+ prompts = ['a photo of {}'] * (len(words))
31
+
32
+ return [promt.format(w) for promt, w in zip(prompts, words)]
33
+
34
+
35
+ class VITDenseBase(nn.Module):
36
+
37
+ def rescaled_pos_emb(self, new_size):
38
+ assert len(new_size) == 2
39
+
40
+ a = self.model.positional_embedding[1:].T.view(1, 768, *self.token_shape)
41
+ b = nnf.interpolate(a, new_size, mode='bicubic', align_corners=False).squeeze(0).view(768, new_size[0]*new_size[1]).T
42
+ return torch.cat([self.model.positional_embedding[:1], b])
43
+
44
+ def visual_forward(self, x_inp, extract_layers=(), skip=False, mask=None):
45
+
46
+ with torch.no_grad():
47
+
48
+ x_inp = nnf.interpolate(x_inp, (384, 384))
49
+
50
+ x = self.model.patch_embed(x_inp)
51
+ cls_token = self.model.cls_token.expand(x.shape[0], -1, -1) # stole cls_tokens impl from Phil Wang, thanks
52
+ if self.model.dist_token is None:
53
+ x = torch.cat((cls_token, x), dim=1)
54
+ else:
55
+ x = torch.cat((cls_token, self.model.dist_token.expand(x.shape[0], -1, -1), x), dim=1)
56
+ x = self.model.pos_drop(x + self.model.pos_embed)
57
+
58
+ activations = []
59
+ for i, block in enumerate(self.model.blocks):
60
+ x = block(x)
61
+
62
+ if i in extract_layers:
63
+ # permute to be compatible with CLIP
64
+ activations += [x.permute(1,0,2)]
65
+
66
+ x = self.model.norm(x)
67
+ x = self.model.head(self.model.pre_logits(x[:, 0]))
68
+
69
+ # again for CLIP compatibility
70
+ # x = x.permute(1, 0, 2)
71
+
72
+ return x, activations, None
73
+
74
+ def sample_prompts(self, words, prompt_list=None):
75
+
76
+ prompt_list = prompt_list if prompt_list is not None else self.prompt_list
77
+
78
+ prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True)
79
+ prompts = [prompt_list[i] for i in prompt_indices]
80
+ return [promt.format(w) for promt, w in zip(prompts, words)]
81
+
82
+ def get_cond_vec(self, conditional, batch_size):
83
+ # compute conditional from a single string
84
+ if conditional is not None and type(conditional) == str:
85
+ cond = self.compute_conditional(conditional)
86
+ cond = cond.repeat(batch_size, 1)
87
+
88
+ # compute conditional from string list/tuple
89
+ elif conditional is not None and type(conditional) in {list, tuple} and type(conditional[0]) == str:
90
+ assert len(conditional) == batch_size
91
+ cond = self.compute_conditional(conditional)
92
+
93
+ # use conditional directly
94
+ elif conditional is not None and type(conditional) == torch.Tensor and conditional.ndim == 2:
95
+ cond = conditional
96
+
97
+ # compute conditional from image
98
+ elif conditional is not None and type(conditional) == torch.Tensor:
99
+ with torch.no_grad():
100
+ cond, _, _ = self.visual_forward(conditional)
101
+ else:
102
+ raise ValueError('invalid conditional')
103
+ return cond
104
+
105
+ def compute_conditional(self, conditional):
106
+ import clip
107
+
108
+ dev = next(self.parameters()).device
109
+
110
+ if type(conditional) in {list, tuple}:
111
+ text_tokens = clip.tokenize(conditional).to(dev)
112
+ cond = self.clip_model.encode_text(text_tokens)
113
+ else:
114
+ if conditional in self.precomputed_prompts:
115
+ cond = self.precomputed_prompts[conditional].float().to(dev)
116
+ else:
117
+ text_tokens = clip.tokenize([conditional]).to(dev)
118
+ cond = self.clip_model.encode_text(text_tokens)[0]
119
+
120
+ return cond
121
+
122
+
123
+ class VITDensePredT(VITDenseBase):
124
+
125
+ def __init__(self, extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4, prompt='fixed',
126
+ depth=3, extra_blocks=0, reduce_cond=None, fix_shift=False,
127
+ learn_trans_conv_only=False, refine=None, limit_to_clip_only=False, upsample=False,
128
+ add_calibration=False, process_cond=None, not_pretrained=False):
129
+ super().__init__()
130
+ # device = 'cpu'
131
+
132
+ self.extract_layers = extract_layers
133
+ self.cond_layer = cond_layer
134
+ self.limit_to_clip_only = limit_to_clip_only
135
+ self.process_cond = None
136
+
137
+ if add_calibration:
138
+ self.calibration_conds = 1
139
+
140
+ self.upsample_proj = nn.Conv2d(reduce_dim, 1, kernel_size=1) if upsample else None
141
+
142
+ self.add_activation1 = True
143
+
144
+ import timm
145
+ self.model = timm.create_model('vit_base_patch16_384', pretrained=True)
146
+ self.model.head = nn.Linear(768, 512 if reduce_cond is None else reduce_cond)
147
+
148
+ for p in self.model.parameters():
149
+ p.requires_grad_(False)
150
+
151
+ import clip
152
+ self.clip_model, _ = clip.load('ViT-B/16', device='cpu', jit=False)
153
+ # del self.clip_model.visual
154
+
155
+
156
+ self.token_shape = (14, 14)
157
+
158
+ # conditional
159
+ if reduce_cond is not None:
160
+ self.reduce_cond = nn.Linear(512, reduce_cond)
161
+ for p in self.reduce_cond.parameters():
162
+ p.requires_grad_(False)
163
+ else:
164
+ self.reduce_cond = None
165
+
166
+ # self.film = AVAILABLE_BLOCKS['film'](512, 128)
167
+ self.film_mul = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
168
+ self.film_add = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
169
+
170
+ # DEPRECATED
171
+ # self.conditional_map = {c['id']: c['synonyms'] for c in json.load(open(cond_map))}
172
+
173
+ assert len(self.extract_layers) == depth
174
+
175
+ self.reduces = nn.ModuleList([nn.Linear(768, reduce_dim) for _ in range(depth)])
176
+ self.blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(len(self.extract_layers))])
177
+ self.extra_blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(extra_blocks)])
178
+
179
+ trans_conv_ks = (16, 16)
180
+ self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
181
+
182
+ # refinement and trans conv
183
+
184
+ if learn_trans_conv_only:
185
+ for p in self.parameters():
186
+ p.requires_grad_(False)
187
+
188
+ for p in self.trans_conv.parameters():
189
+ p.requires_grad_(True)
190
+
191
+ if prompt == 'fixed':
192
+ self.prompt_list = ['a photo of a {}.']
193
+ elif prompt == 'shuffle':
194
+ self.prompt_list = ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.']
195
+ elif prompt == 'shuffle+':
196
+ self.prompt_list = ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.',
197
+ 'a cropped photo of a {}.', 'a good photo of a {}.', 'a photo of one {}.',
198
+ 'a bad photo of a {}.', 'a photo of the {}.']
199
+ elif prompt == 'shuffle_clip':
200
+ from models.clip_prompts import imagenet_templates
201
+ self.prompt_list = imagenet_templates
202
+
203
+ if process_cond is not None:
204
+ if process_cond == 'clamp' or process_cond[0] == 'clamp':
205
+
206
+ val = process_cond[1] if type(process_cond) in {list, tuple} else 0.2
207
+
208
+ def clamp_vec(x):
209
+ return torch.clamp(x, -val, val)
210
+
211
+ self.process_cond = clamp_vec
212
+
213
+ elif process_cond.endswith('.pth'):
214
+
215
+ shift = torch.load(process_cond)
216
+ def add_shift(x):
217
+ return x + shift.to(x.device)
218
+
219
+ self.process_cond = add_shift
220
+
221
+ import pickle
222
+ precomp = pickle.load(open('precomputed_prompt_vectors.pickle', 'rb'))
223
+ self.precomputed_prompts = {k: torch.from_numpy(v) for k, v in precomp.items()}
224
+
225
+
226
+ def forward(self, inp_image, conditional=None, return_features=False, mask=None):
227
+
228
+ assert type(return_features) == bool
229
+
230
+ # inp_image = inp_image.to(self.model.positional_embedding.device)
231
+
232
+ if mask is not None:
233
+ raise ValueError('mask not supported')
234
+
235
+ # x_inp = normalize(inp_image)
236
+ x_inp = inp_image
237
+
238
+ bs, dev = inp_image.shape[0], x_inp.device
239
+
240
+ inp_image_size = inp_image.shape[2:]
241
+
242
+ cond = self.get_cond_vec(conditional, bs)
243
+
244
+ visual_q, activations, _ = self.visual_forward(x_inp, extract_layers=[0] + list(self.extract_layers))
245
+
246
+ activation1 = activations[0]
247
+ activations = activations[1:]
248
+
249
+ a = None
250
+ for i, (activation, block, reduce) in enumerate(zip(activations[::-1], self.blocks, self.reduces)):
251
+
252
+ if a is not None:
253
+ a = reduce(activation) + a
254
+ else:
255
+ a = reduce(activation)
256
+
257
+ if i == self.cond_layer:
258
+ if self.reduce_cond is not None:
259
+ cond = self.reduce_cond(cond)
260
+
261
+ a = self.film_mul(cond) * a + self.film_add(cond)
262
+
263
+ a = block(a)
264
+
265
+ for block in self.extra_blocks:
266
+ a = a + block(a)
267
+
268
+ a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens
269
+
270
+ size = int(math.sqrt(a.shape[2]))
271
+
272
+ a = a.view(bs, a.shape[1], size, size)
273
+
274
+ if self.trans_conv is not None:
275
+ a = self.trans_conv(a)
276
+
277
+ if self.upsample_proj is not None:
278
+ a = self.upsample_proj(a)
279
+ a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear')
280
+
281
+ a = nnf.interpolate(a, inp_image_size)
282
+
283
+ if return_features:
284
+ return a, visual_q, cond, [activation1] + activations
285
+ else:
286
+ return a,
config_colab.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ clear_output: true
2
+ force_cpu: false
3
+ live_cam_start_active: false
4
+ max_threads: 3
5
+ memory_limit: 0
6
+ output_image_format: png
7
+ output_template: '{file}_{time}'
8
+ output_video_codec: libx264
9
+ output_video_format: mp4
10
+ provider: cuda
11
+ selected_theme: Default
12
+ server_name: ''
13
+ server_port: 0
14
+ server_share: true
15
+ video_quality: 14
installer/installer.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import os
4
+ import shutil
5
+ import site
6
+ import subprocess
7
+ import sys
8
+
9
+
10
+ script_dir = os.getcwd()
11
+
12
+
13
+ def run_cmd(cmd, capture_output=False, env=None):
14
+ # Run shell commands
15
+ return subprocess.run(cmd, shell=True, capture_output=capture_output, env=env)
16
+
17
+
18
+ def check_env():
19
+ # If we have access to conda, we are probably in an environment
20
+ conda_not_exist = run_cmd("conda", capture_output=True).returncode
21
+ if conda_not_exist:
22
+ print("Conda is not installed. Exiting...")
23
+ sys.exit()
24
+
25
+ # Ensure this is a new environment and not the base environment
26
+ if os.environ["CONDA_DEFAULT_ENV"] == "base":
27
+ print("Create an environment for this project and activate it. Exiting...")
28
+ sys.exit()
29
+
30
+
31
+ def install_dependencies():
32
+ # Install Git and clone repo
33
+ run_cmd("conda install -y -k git")
34
+ run_cmd("git clone https://github.com/C0untFloyd/roop-unleashed.git")
35
+ run_cmd("git checkout 8ee085322158c4eeb0cd0126a49949f1acf0f7df")
36
+ # Install the webui dependencies
37
+ update_dependencies()
38
+
39
+
40
+ def update_dependencies():
41
+ global MY_PATH
42
+
43
+ os.chdir(MY_PATH)
44
+ # do a hard reset for to update even if there are local changes
45
+ run_cmd("git fetch --all")
46
+ run_cmd("git reset --hard origin/main")
47
+ run_cmd("git pull")
48
+ # Installs/Updates dependencies from all requirements.txt
49
+ run_cmd("python -m pip install -r requirements.txt")
50
+
51
+
52
+ def start_app():
53
+ global MY_PATH
54
+
55
+ os.chdir(MY_PATH)
56
+ # forward commandline arguments
57
+ sys.argv.pop(0)
58
+ args = ' '.join(sys.argv)
59
+ print("Launching App")
60
+ run_cmd(f'python run.py {args}')
61
+
62
+
63
+ if __name__ == "__main__":
64
+ global MY_PATH
65
+
66
+ MY_PATH = "roop-unleashed"
67
+
68
+
69
+ # Verifies we are in a conda environment
70
+ check_env()
71
+
72
+ # If webui has already been installed, skip and run
73
+ if not os.path.exists(MY_PATH):
74
+ install_dependencies()
75
+ else:
76
+ # moved update from batch to here, because of batch limitations
77
+ updatechoice = input("Check for Updates? [y/n]").lower()
78
+ if updatechoice == "y":
79
+ update_dependencies()
80
+
81
+ # Run the model with webui
82
+ os.chdir(script_dir)
83
+ start_app()
mypy.ini ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [mypy]
2
+ check_untyped_defs = True
3
+ disallow_any_generics = True
4
+ disallow_untyped_calls = True
5
+ disallow_untyped_defs = True
6
+ ignore_missing_imports = True
7
+ strict_optional = False
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu118
2
+
3
+ numpy==1.26.2
4
+ gradio==3.44.2
5
+ opencv-python==4.8.1.78
6
+ onnx==1.15.0
7
+ insightface==0.7.3
8
+ psutil==5.9.6
9
+ torch==2.1.2+cu118; sys_platform != 'darwin'
10
+ torch==2.1.2; sys_platform == 'darwin'
11
+ torchvision==0.16.2+cu118; sys_platform != 'darwin'
12
+ torchvision==0.16.2; sys_platform == 'darwin'
13
+ onnxruntime==1.16.3; sys_platform == 'darwin' and platform_machine != 'arm64'
14
+ onnxruntime-silicon==1.13.1; sys_platform == 'darwin' and platform_machine == 'arm64'
15
+ onnxruntime-gpu==1.16.3; sys_platform != 'darwin'
16
+ tqdm==4.66.1
17
+ ftfy
18
+ regex
19
+ pyvirtualcam
roop-unleashed.ipynb ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4",
8
+ "collapsed_sections": [
9
+ "UdQ1VHdI8lCf"
10
+ ]
11
+ },
12
+ "kernelspec": {
13
+ "name": "python3",
14
+ "display_name": "Python 3"
15
+ },
16
+ "language_info": {
17
+ "name": "python"
18
+ },
19
+ "accelerator": "GPU"
20
+ },
21
+ "cells": [
22
+ {
23
+ "cell_type": "markdown",
24
+ "source": [
25
+ "# Colab for roop-unleashed - Gradio version\n",
26
+ "https://github.com/C0untFloyd/roop-unleashed\n"
27
+ ],
28
+ "metadata": {
29
+ "id": "G9BdiCppV6AS"
30
+ }
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "source": [
35
+ "Installing & preparing requirements"
36
+ ],
37
+ "metadata": {
38
+ "id": "0ZYRNb0AWLLW"
39
+ }
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "execution_count": null,
44
+ "metadata": {
45
+ "id": "t1yPuhdySqCq"
46
+ },
47
+ "outputs": [],
48
+ "source": [
49
+ "!git clone https://github.com/C0untFloyd/roop-unleashed.git\n",
50
+ "%cd roop-unleashed\n",
51
+ "!mv config_colab.yaml config.yaml\n",
52
+ "!pip install pip install -r requirements.txt"
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "markdown",
57
+ "source": [
58
+ "Running roop-unleashed with default config"
59
+ ],
60
+ "metadata": {
61
+ "id": "u_4JQiSlV9Fi"
62
+ }
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "source": [
67
+ "!python run.py"
68
+ ],
69
+ "metadata": {
70
+ "id": "Is6U2huqSzLE"
71
+ },
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "markdown",
77
+ "source": [
78
+ "### Download generated images folder\n",
79
+ "(only needed if you want to zip the generated output)"
80
+ ],
81
+ "metadata": {
82
+ "id": "UdQ1VHdI8lCf"
83
+ }
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "source": [
88
+ "import shutil\n",
89
+ "import os\n",
90
+ "from google.colab import files\n",
91
+ "\n",
92
+ "def zip_directory(directory_path, zip_path):\n",
93
+ " shutil.make_archive(zip_path, 'zip', directory_path)\n",
94
+ "\n",
95
+ "# Set the directory path you want to download\n",
96
+ "directory_path = '/content/roop-unleashed/output'\n",
97
+ "\n",
98
+ "# Set the zip file name\n",
99
+ "zip_filename = 'fake_output.zip'\n",
100
+ "\n",
101
+ "# Zip the directory\n",
102
+ "zip_directory(directory_path, zip_filename)\n",
103
+ "\n",
104
+ "# Download the zip file\n",
105
+ "files.download(zip_filename+'.zip')\n"
106
+ ],
107
+ "metadata": {
108
+ "colab": {
109
+ "base_uri": "https://localhost:8080/",
110
+ "height": 17
111
+ },
112
+ "id": "oYjWveAmw10X",
113
+ "outputId": "5b4c3650-f951-434a-c650-5525a8a70c1e"
114
+ },
115
+ "execution_count": null,
116
+ "outputs": [
117
+ {
118
+ "output_type": "display_data",
119
+ "data": {
120
+ "text/plain": [
121
+ "<IPython.core.display.Javascript object>"
122
+ ],
123
+ "application/javascript": [
124
+ "\n",
125
+ " async function download(id, filename, size) {\n",
126
+ " if (!google.colab.kernel.accessAllowed) {\n",
127
+ " return;\n",
128
+ " }\n",
129
+ " const div = document.createElement('div');\n",
130
+ " const label = document.createElement('label');\n",
131
+ " label.textContent = `Downloading \"${filename}\": `;\n",
132
+ " div.appendChild(label);\n",
133
+ " const progress = document.createElement('progress');\n",
134
+ " progress.max = size;\n",
135
+ " div.appendChild(progress);\n",
136
+ " document.body.appendChild(div);\n",
137
+ "\n",
138
+ " const buffers = [];\n",
139
+ " let downloaded = 0;\n",
140
+ "\n",
141
+ " const channel = await google.colab.kernel.comms.open(id);\n",
142
+ " // Send a message to notify the kernel that we're ready.\n",
143
+ " channel.send({})\n",
144
+ "\n",
145
+ " for await (const message of channel.messages) {\n",
146
+ " // Send a message to notify the kernel that we're ready.\n",
147
+ " channel.send({})\n",
148
+ " if (message.buffers) {\n",
149
+ " for (const buffer of message.buffers) {\n",
150
+ " buffers.push(buffer);\n",
151
+ " downloaded += buffer.byteLength;\n",
152
+ " progress.value = downloaded;\n",
153
+ " }\n",
154
+ " }\n",
155
+ " }\n",
156
+ " const blob = new Blob(buffers, {type: 'application/binary'});\n",
157
+ " const a = document.createElement('a');\n",
158
+ " a.href = window.URL.createObjectURL(blob);\n",
159
+ " a.download = filename;\n",
160
+ " div.appendChild(a);\n",
161
+ " a.click();\n",
162
+ " div.remove();\n",
163
+ " }\n",
164
+ " "
165
+ ]
166
+ },
167
+ "metadata": {}
168
+ },
169
+ {
170
+ "output_type": "display_data",
171
+ "data": {
172
+ "text/plain": [
173
+ "<IPython.core.display.Javascript object>"
174
+ ],
175
+ "application/javascript": [
176
+ "download(\"download_789eab11-93d2-4880-adf3-6aceee0cc5f9\", \"fake_output.zip.zip\", 80125)"
177
+ ]
178
+ },
179
+ "metadata": {}
180
+ }
181
+ ]
182
+ }
183
+ ]
184
+ }
roop/FaceSet.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ class FaceSet:
4
+ faces = []
5
+ ref_images = []
6
+ embedding_average = 'None'
7
+ embeddings_backup = None
8
+
9
+ def __init__(self):
10
+ self.faces = []
11
+ self.ref_images = []
12
+ self.embeddings_backup = None
13
+
14
+ def AverageEmbeddings(self):
15
+ if len(self.faces) > 1 and self.embeddings_backup is None:
16
+ self.embeddings_backup = self.faces[0]['embedding']
17
+ embeddings = [face.embedding for face in self.faces]
18
+
19
+ self.faces[0]['embedding'] = np.mean(embeddings, axis=0)
20
+ # try median too?
roop/ProcessEntry.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ class ProcessEntry:
2
+ def __init__(self, filename: str, start: int, end: int, fps: float):
3
+ self.filename = filename
4
+ self.finalname = None
5
+ self.startframe = start
6
+ self.endframe = end
7
+ self.fps = fps
roop/ProcessMgr.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import psutil
5
+
6
+ from roop.ProcessOptions import ProcessOptions
7
+
8
+ from roop.face_util import get_first_face, get_all_faces, rotate_image_180, rotate_anticlockwise, rotate_clockwise, clamp_cut_values
9
+ from roop.utilities import compute_cosine_distance, get_device, str_to_class
10
+ import roop.vr_util as vr
11
+
12
+ from typing import Any, List, Callable
13
+ from roop.typing import Frame, Face
14
+ from concurrent.futures import ThreadPoolExecutor, as_completed
15
+ from threading import Thread, Lock
16
+ from queue import Queue
17
+ from tqdm import tqdm
18
+ from roop.ffmpeg_writer import FFMPEG_VideoWriter
19
+ import roop.globals
20
+
21
+
22
+ def create_queue(temp_frame_paths: List[str]) -> Queue[str]:
23
+ queue: Queue[str] = Queue()
24
+ for frame_path in temp_frame_paths:
25
+ queue.put(frame_path)
26
+ return queue
27
+
28
+
29
+ def pick_queue(queue: Queue[str], queue_per_future: int) -> List[str]:
30
+ queues = []
31
+ for _ in range(queue_per_future):
32
+ if not queue.empty():
33
+ queues.append(queue.get())
34
+ return queues
35
+
36
+
37
+ class ProcessMgr():
38
+ input_face_datas = []
39
+ target_face_datas = []
40
+
41
+ processors = []
42
+ options : ProcessOptions = None
43
+
44
+ num_threads = 1
45
+ current_index = 0
46
+ processing_threads = 1
47
+ buffer_wait_time = 0.1
48
+
49
+ lock = Lock()
50
+
51
+ frames_queue = None
52
+ processed_queue = None
53
+
54
+ videowriter= None
55
+
56
+ progress_gradio = None
57
+ total_frames = 0
58
+
59
+
60
+
61
+
62
+ plugins = {
63
+ 'faceswap' : 'FaceSwapInsightFace',
64
+ 'mask_clip2seg' : 'Mask_Clip2Seg',
65
+ 'codeformer' : 'Enhance_CodeFormer',
66
+ 'gfpgan' : 'Enhance_GFPGAN',
67
+ 'dmdnet' : 'Enhance_DMDNet',
68
+ 'gpen' : 'Enhance_GPEN',
69
+ 'restoreformer' : 'Enhance_RestoreFormer',
70
+ }
71
+
72
+ def __init__(self, progress):
73
+ if progress is not None:
74
+ self.progress_gradio = progress
75
+
76
+
77
+ def initialize(self, input_faces, target_faces, options):
78
+ self.input_face_datas = input_faces
79
+ self.target_face_datas = target_faces
80
+ self.options = options
81
+
82
+ processornames = options.processors.split(",")
83
+ devicename = get_device()
84
+ if len(self.processors) < 1:
85
+ for pn in processornames:
86
+ classname = self.plugins[pn]
87
+ module = 'roop.processors.' + classname
88
+ p = str_to_class(module, classname)
89
+ p.Initialize(devicename)
90
+ self.processors.append(p)
91
+ else:
92
+ for i in range(len(self.processors) -1, -1, -1):
93
+ if not self.processors[i].processorname in processornames:
94
+ self.processors[i].Release()
95
+ del self.processors[i]
96
+
97
+ for i,pn in enumerate(processornames):
98
+ if i >= len(self.processors) or self.processors[i].processorname != pn:
99
+ p = None
100
+ classname = self.plugins[pn]
101
+ module = 'roop.processors.' + classname
102
+ p = str_to_class(module, classname)
103
+ p.Initialize(devicename)
104
+ if p is not None:
105
+ self.processors.insert(i, p)
106
+
107
+
108
+
109
+ def run_batch(self, source_files, target_files, threads:int = 1):
110
+ progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
111
+ self.total_frames = len(source_files)
112
+ self.num_threads = threads
113
+ with tqdm(total=self.total_frames, desc='Processing', unit='frame', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
114
+ with ThreadPoolExecutor(max_workers=threads) as executor:
115
+ futures = []
116
+ queue = create_queue(source_files)
117
+ queue_per_future = max(len(source_files) // threads, 1)
118
+ while not queue.empty():
119
+ future = executor.submit(self.process_frames, source_files, target_files, pick_queue(queue, queue_per_future), lambda: self.update_progress(progress))
120
+ futures.append(future)
121
+ for future in as_completed(futures):
122
+ future.result()
123
+
124
+
125
+ def process_frames(self, source_files: List[str], target_files: List[str], current_files, update: Callable[[], None]) -> None:
126
+ for f in current_files:
127
+ if not roop.globals.processing:
128
+ return
129
+
130
+ temp_frame = cv2.imread(f)
131
+ if temp_frame is not None:
132
+ resimg = self.process_frame(temp_frame)
133
+ if resimg is not None:
134
+ i = source_files.index(f)
135
+ cv2.imwrite(target_files[i], resimg)
136
+ if update:
137
+ update()
138
+
139
+
140
+
141
+ def read_frames_thread(self, cap, frame_start, frame_end, num_threads):
142
+ num_frame = 0
143
+ total_num = frame_end - frame_start
144
+ if frame_start > 0:
145
+ cap.set(cv2.CAP_PROP_POS_FRAMES,frame_start)
146
+
147
+ while True and roop.globals.processing:
148
+ ret, frame = cap.read()
149
+ if not ret:
150
+ break
151
+
152
+ self.frames_queue[num_frame % num_threads].put(frame, block=True)
153
+ num_frame += 1
154
+ if num_frame == total_num:
155
+ break
156
+
157
+ for i in range(num_threads):
158
+ self.frames_queue[i].put(None)
159
+
160
+
161
+
162
+ def process_videoframes(self, threadindex, progress) -> None:
163
+ while True:
164
+ frame = self.frames_queue[threadindex].get()
165
+ if frame is None:
166
+ self.processing_threads -= 1
167
+ self.processed_queue[threadindex].put((False, None))
168
+ return
169
+ else:
170
+ resimg = self.process_frame(frame)
171
+ self.processed_queue[threadindex].put((True, resimg))
172
+ del frame
173
+ progress()
174
+
175
+
176
+ def write_frames_thread(self):
177
+ nextindex = 0
178
+ num_producers = self.num_threads
179
+
180
+ while True:
181
+ process, frame = self.processed_queue[nextindex % self.num_threads].get()
182
+ nextindex += 1
183
+ if frame is not None:
184
+ self.videowriter.write_frame(frame)
185
+ del frame
186
+ elif process == False:
187
+ num_producers -= 1
188
+ if num_producers < 1:
189
+ return
190
+
191
+
192
+
193
+ def run_batch_inmem(self, source_video, target_video, frame_start, frame_end, fps, threads:int = 1, skip_audio=False):
194
+ cap = cv2.VideoCapture(source_video)
195
+ # frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
196
+ frame_count = (frame_end - frame_start) + 1
197
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
198
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
199
+
200
+ self.total_frames = frame_count
201
+ self.num_threads = threads
202
+
203
+ self.processing_threads = self.num_threads
204
+ self.frames_queue = []
205
+ self.processed_queue = []
206
+ for _ in range(threads):
207
+ self.frames_queue.append(Queue(1))
208
+ self.processed_queue.append(Queue(1))
209
+
210
+ self.videowriter = FFMPEG_VideoWriter(target_video, (width, height), fps, codec=roop.globals.video_encoder, crf=roop.globals.video_quality, audiofile=None)
211
+
212
+ readthread = Thread(target=self.read_frames_thread, args=(cap, frame_start, frame_end, threads))
213
+ readthread.start()
214
+
215
+ writethread = Thread(target=self.write_frames_thread)
216
+ writethread.start()
217
+
218
+ progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
219
+ with tqdm(total=self.total_frames, desc='Processing', unit='frames', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
220
+ with ThreadPoolExecutor(thread_name_prefix='swap_proc', max_workers=self.num_threads) as executor:
221
+ futures = []
222
+
223
+ for threadindex in range(threads):
224
+ future = executor.submit(self.process_videoframes, threadindex, lambda: self.update_progress(progress))
225
+ futures.append(future)
226
+
227
+ for future in as_completed(futures):
228
+ future.result()
229
+ # wait for the task to complete
230
+ readthread.join()
231
+ writethread.join()
232
+ cap.release()
233
+ self.videowriter.close()
234
+ self.frames_queue.clear()
235
+ self.processed_queue.clear()
236
+
237
+
238
+
239
+
240
+ def update_progress(self, progress: Any = None) -> None:
241
+ process = psutil.Process(os.getpid())
242
+ memory_usage = process.memory_info().rss / 1024 / 1024 / 1024
243
+ msg = 'memory_usage: ' + '{:.2f}'.format(memory_usage).zfill(5) + f' GB execution_threads {self.num_threads}'
244
+ progress.set_postfix({
245
+ 'memory_usage': '{:.2f}'.format(memory_usage).zfill(5) + 'GB',
246
+ 'execution_threads': self.num_threads
247
+ })
248
+ progress.update(1)
249
+ self.progress_gradio((progress.n, self.total_frames), desc='Processing', total=self.total_frames, unit='frames')
250
+
251
+
252
+ def on_no_face_action(self, frame:Frame):
253
+ if roop.globals.no_face_action == 0:
254
+ return None, frame
255
+ elif roop.globals.no_face_action == 2:
256
+ return None, None
257
+
258
+
259
+ faces = get_all_faces(frame)
260
+ if faces is not None:
261
+ return faces, frame
262
+ return None, frame
263
+
264
+ # https://github.com/deepinsight/insightface#third-party-re-implementation-of-arcface
265
+ # https://github.com/deepinsight/insightface/blob/master/alignment/coordinate_reg/image_infer.py
266
+ # https://github.com/deepinsight/insightface/issues/1350
267
+ # https://github.com/linghu8812/tensorrt_inference
268
+
269
+
270
+ def process_frame(self, frame:Frame):
271
+ use_original_frame = 0
272
+ retry_rotated_180 = 1
273
+ skip_frame = 2
274
+
275
+ if len(self.input_face_datas) < 1:
276
+ return frame
277
+ temp_frame = frame.copy()
278
+ num_swapped, temp_frame = self.swap_faces(frame, temp_frame)
279
+ if num_swapped > 0:
280
+ return temp_frame
281
+ if roop.globals.no_face_action == use_original_frame:
282
+ return frame
283
+ if roop.globals.no_face_action == skip_frame:
284
+ #This only works with in-mem processing, as it simply skips the frame.
285
+ #For 'extract frames' it simply leaves the unprocessed frame unprocessed and it gets used in the final output by ffmpeg.
286
+ #If we could delete that frame here, that'd work but that might cause ffmpeg to fail unless the frames are renamed, and I don't think we have the info on what frame it actually is?????
287
+ #alternatively, it could mark all the necessary frames for deletion, delete them at the end, then rename the remaining frames that might work?
288
+ return None
289
+ else:
290
+ copyframe = frame.copy()
291
+ copyframe = rotate_image_180(copyframe)
292
+ temp_frame = copyframe.copy()
293
+ num_swapped, temp_frame = self.swap_faces(copyframe, temp_frame)
294
+ if num_swapped == 0:
295
+ return frame
296
+ temp_frame = rotate_image_180(temp_frame)
297
+ return temp_frame
298
+
299
+
300
+ def swap_faces(self, frame, temp_frame):
301
+ num_faces_found = 0
302
+
303
+ if self.options.swap_mode == "first":
304
+ face = get_first_face(frame)
305
+
306
+ if face is None:
307
+ return num_faces_found, frame
308
+
309
+ num_faces_found += 1
310
+ temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
311
+ else:
312
+ faces = get_all_faces(frame)
313
+ if faces is None:
314
+ return num_faces_found, frame
315
+
316
+ if self.options.swap_mode == "all":
317
+ for face in faces:
318
+ num_faces_found += 1
319
+ temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
320
+ del face
321
+
322
+ elif self.options.swap_mode == "selected":
323
+ for i,tf in enumerate(self.target_face_datas):
324
+ for face in faces:
325
+ if compute_cosine_distance(tf.embedding, face.embedding) <= self.options.face_distance_threshold:
326
+ if i < len(self.input_face_datas):
327
+ temp_frame = self.process_face(i, face, temp_frame)
328
+ num_faces_found += 1
329
+ if not roop.globals.vr_mode:
330
+ break
331
+ del face
332
+ elif self.options.swap_mode == "all_female" or self.options.swap_mode == "all_male":
333
+ gender = 'F' if self.options.swap_mode == "all_female" else 'M'
334
+ for face in faces:
335
+ if face.sex == gender:
336
+ num_faces_found += 1
337
+ temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
338
+ del face
339
+
340
+ if roop.globals.vr_mode and num_faces_found % 2 > 0:
341
+ # stereo image, there has to be an even number of faces
342
+ num_faces_found = 0
343
+ return num_faces_found, frame
344
+ if num_faces_found == 0:
345
+ return num_faces_found, frame
346
+
347
+ maskprocessor = next((x for x in self.processors if x.processorname == 'clip2seg'), None)
348
+ if maskprocessor is not None:
349
+ temp_frame = self.process_mask(maskprocessor, frame, temp_frame)
350
+ return num_faces_found, temp_frame
351
+
352
+
353
+ def rotation_action(self, original_face:Face, frame:Frame):
354
+ (height, width) = frame.shape[:2]
355
+
356
+ bounding_box_width = original_face.bbox[2] - original_face.bbox[0]
357
+ bounding_box_height = original_face.bbox[3] - original_face.bbox[1]
358
+ horizontal_face = bounding_box_width > bounding_box_height
359
+
360
+ center_x = width // 2.0
361
+ start_x = original_face.bbox[0]
362
+ end_x = original_face.bbox[2]
363
+ bbox_center_x = start_x + (bounding_box_width // 2.0)
364
+
365
+ # need to leverage the array of landmarks as decribed here:
366
+ # https://github.com/deepinsight/insightface/tree/master/alignment/coordinate_reg
367
+ # basically, we should be able to check for the relative position of eyes and nose
368
+ # then use that to determine which way the face is actually facing when in a horizontal position
369
+ # and use that to determine the correct rotation_action
370
+
371
+ forehead_x = original_face.landmark_2d_106[72][0]
372
+ chin_x = original_face.landmark_2d_106[0][0]
373
+
374
+ if horizontal_face:
375
+ if chin_x < forehead_x:
376
+ # this is someone lying down with their face like this (:
377
+ return "rotate_anticlockwise"
378
+ elif forehead_x < chin_x:
379
+ # this is someone lying down with their face like this :)
380
+ return "rotate_clockwise"
381
+ if bbox_center_x >= center_x:
382
+ # this is someone lying down with their face in the right hand side of the frame
383
+ return "rotate_anticlockwise"
384
+ if bbox_center_x < center_x:
385
+ # this is someone lying down with their face in the left hand side of the frame
386
+ return "rotate_clockwise"
387
+
388
+ return None
389
+
390
+
391
+ def auto_rotate_frame(self, original_face, frame:Frame):
392
+ target_face = original_face
393
+ original_frame = frame
394
+
395
+ rotation_action = self.rotation_action(original_face, frame)
396
+
397
+ if rotation_action == "rotate_anticlockwise":
398
+ #face is horizontal, rotating frame anti-clockwise and getting face bounding box from rotated frame
399
+ frame = rotate_anticlockwise(frame)
400
+ elif rotation_action == "rotate_clockwise":
401
+ #face is horizontal, rotating frame clockwise and getting face bounding box from rotated frame
402
+ frame = rotate_clockwise(frame)
403
+
404
+ return target_face, frame, rotation_action
405
+
406
+
407
+ def auto_unrotate_frame(self, frame:Frame, rotation_action):
408
+ if rotation_action == "rotate_anticlockwise":
409
+ return rotate_clockwise(frame)
410
+ elif rotation_action == "rotate_clockwise":
411
+ return rotate_anticlockwise(frame)
412
+
413
+ return frame
414
+
415
+
416
+
417
+ def process_face(self,face_index, target_face:Face, frame:Frame):
418
+ enhanced_frame = None
419
+ inputface = self.input_face_datas[face_index].faces[0]
420
+
421
+ rotation_action = None
422
+ if roop.globals.autorotate_faces:
423
+ # check for sideways rotation of face
424
+ rotation_action = self.rotation_action(target_face, frame)
425
+ if rotation_action is not None:
426
+ (startX, startY, endX, endY) = target_face["bbox"].astype("int")
427
+ width = endX - startX
428
+ height = endY - startY
429
+ offs = int(max(width,height) * 0.25)
430
+ rotcutframe,startX, startY, endX, endY = self.cutout(frame, startX - offs, startY - offs, endX + offs, endY + offs)
431
+ if rotation_action == "rotate_anticlockwise":
432
+ rotcutframe = rotate_anticlockwise(rotcutframe)
433
+ elif rotation_action == "rotate_clockwise":
434
+ rotcutframe = rotate_clockwise(rotcutframe)
435
+ # rotate image and re-detect face to correct wonky landmarks
436
+ rotface = get_first_face(rotcutframe)
437
+ if rotface is None:
438
+ rotation_action = None
439
+ else:
440
+ saved_frame = frame.copy()
441
+ frame = rotcutframe
442
+ target_face = rotface
443
+
444
+
445
+
446
+ # if roop.globals.vr_mode:
447
+ # bbox = target_face.bbox
448
+ # [orig_width, orig_height, _] = frame.shape
449
+
450
+ # # Convert bounding box to ints
451
+ # x1, y1, x2, y2 = map(int, bbox)
452
+
453
+ # # Determine the center of the bounding box
454
+ # x_center = (x1 + x2) / 2
455
+ # y_center = (y1 + y2) / 2
456
+
457
+ # # Normalize coordinates to range [-1, 1]
458
+ # x_center_normalized = x_center / (orig_width / 2) - 1
459
+ # y_center_normalized = y_center / (orig_width / 2) - 1
460
+
461
+ # # Convert normalized coordinates to spherical (theta, phi)
462
+ # theta = x_center_normalized * 180 # Theta ranges from -180 to 180 degrees
463
+ # phi = -y_center_normalized * 90 # Phi ranges from -90 to 90 degrees
464
+
465
+ # img = vr.GetPerspective(frame, 90, theta, phi, 1280, 1280) # Generate perspective image
466
+
467
+ for p in self.processors:
468
+ if p.type == 'swap':
469
+ fake_frame = p.Run(inputface, target_face, frame)
470
+ scale_factor = 0.0
471
+ elif p.type == 'mask':
472
+ continue
473
+ else:
474
+ enhanced_frame, scale_factor = p.Run(self.input_face_datas[face_index], target_face, fake_frame)
475
+
476
+ upscale = 512
477
+ orig_width = fake_frame.shape[1]
478
+
479
+ fake_frame = cv2.resize(fake_frame, (upscale, upscale), cv2.INTER_CUBIC)
480
+ mask_offsets = inputface.mask_offsets
481
+
482
+ if enhanced_frame is None:
483
+ scale_factor = int(upscale / orig_width)
484
+ result = self.paste_upscale(fake_frame, fake_frame, target_face.matrix, frame, scale_factor, mask_offsets)
485
+ else:
486
+ result = self.paste_upscale(fake_frame, enhanced_frame, target_face.matrix, frame, scale_factor, mask_offsets)
487
+
488
+ if rotation_action is not None:
489
+ fake_frame = self.auto_unrotate_frame(result, rotation_action)
490
+ return self.paste_simple(fake_frame, saved_frame, startX, startY)
491
+
492
+ return result
493
+
494
+
495
+
496
+
497
+ def cutout(self, frame:Frame, start_x, start_y, end_x, end_y):
498
+ if start_x < 0:
499
+ start_x = 0
500
+ if start_y < 0:
501
+ start_y = 0
502
+ if end_x > frame.shape[1]:
503
+ end_x = frame.shape[1]
504
+ if end_y > frame.shape[0]:
505
+ end_y = frame.shape[0]
506
+ return frame[start_y:end_y, start_x:end_x], start_x, start_y, end_x, end_y
507
+
508
+ def paste_simple(self, src:Frame, dest:Frame, start_x, start_y):
509
+ end_x = start_x + src.shape[1]
510
+ end_y = start_y + src.shape[0]
511
+
512
+ start_x, end_x, start_y, end_y = clamp_cut_values(start_x, end_x, start_y, end_y, dest)
513
+ dest[start_y:end_y, start_x:end_x] = src
514
+ return dest
515
+
516
+
517
+ # Paste back adapted from here
518
+ # https://github.com/fAIseh00d/refacer/blob/main/refacer.py
519
+ # which is revised insightface paste back code
520
+
521
+ def paste_upscale(self, fake_face, upsk_face, M, target_img, scale_factor, mask_offsets):
522
+ M_scale = M * scale_factor
523
+ IM = cv2.invertAffineTransform(M_scale)
524
+
525
+ face_matte = np.full((target_img.shape[0],target_img.shape[1]), 255, dtype=np.uint8)
526
+ ##Generate white square sized as a upsk_face
527
+ img_matte = np.full((upsk_face.shape[0],upsk_face.shape[1]), 255, dtype=np.uint8)
528
+ if mask_offsets[0] > 0:
529
+ img_matte[:mask_offsets[0],:] = 0
530
+ if mask_offsets[1] > 0:
531
+ img_matte[-mask_offsets[1]:,:] = 0
532
+
533
+ ##Transform white square back to target_img
534
+ img_matte = cv2.warpAffine(img_matte, IM, (target_img.shape[1], target_img.shape[0]), flags=cv2.INTER_NEAREST, borderValue=0.0)
535
+ ##Blacken the edges of face_matte by 1 pixels (so the mask in not expanded on the image edges)
536
+ img_matte[:1,:] = img_matte[-1:,:] = img_matte[:,:1] = img_matte[:,-1:] = 0
537
+
538
+ #Detect the affine transformed white area
539
+ mask_h_inds, mask_w_inds = np.where(img_matte==255)
540
+ #Calculate the size (and diagonal size) of transformed white area width and height boundaries
541
+ mask_h = np.max(mask_h_inds) - np.min(mask_h_inds)
542
+ mask_w = np.max(mask_w_inds) - np.min(mask_w_inds)
543
+ mask_size = int(np.sqrt(mask_h*mask_w))
544
+ #Calculate the kernel size for eroding img_matte by kernel (insightface empirical guess for best size was max(mask_size//10,10))
545
+ # k = max(mask_size//12, 8)
546
+ k = max(mask_size//10, 10)
547
+ kernel = np.ones((k,k),np.uint8)
548
+ img_matte = cv2.erode(img_matte,kernel,iterations = 1)
549
+ #Calculate the kernel size for blurring img_matte by blur_size (insightface empirical guess for best size was max(mask_size//20, 5))
550
+ # k = max(mask_size//24, 4)
551
+ k = max(mask_size//20, 5)
552
+ kernel_size = (k, k)
553
+ blur_size = tuple(2*i+1 for i in kernel_size)
554
+ img_matte = cv2.GaussianBlur(img_matte, blur_size, 0)
555
+
556
+ #Normalize images to float values and reshape
557
+ img_matte = img_matte.astype(np.float32)/255
558
+ face_matte = face_matte.astype(np.float32)/255
559
+ img_matte = np.minimum(face_matte, img_matte)
560
+ img_matte = np.reshape(img_matte, [img_matte.shape[0],img_matte.shape[1],1])
561
+ ##Transform upcaled face back to target_img
562
+ paste_face = cv2.warpAffine(upsk_face, IM, (target_img.shape[1], target_img.shape[0]), borderMode=cv2.BORDER_REPLICATE)
563
+ if upsk_face is not fake_face:
564
+ fake_face = cv2.warpAffine(fake_face, IM, (target_img.shape[1], target_img.shape[0]), borderMode=cv2.BORDER_REPLICATE)
565
+ paste_face = cv2.addWeighted(paste_face, self.options.blend_ratio, fake_face, 1.0 - self.options.blend_ratio, 0)
566
+
567
+ ##Re-assemble image
568
+ paste_face = img_matte * paste_face
569
+ paste_face = paste_face + (1-img_matte) * target_img.astype(np.float32)
570
+ del img_matte
571
+ del face_matte
572
+ del upsk_face
573
+ del fake_face
574
+ return paste_face.astype(np.uint8)
575
+
576
+
577
+ def process_mask(self, processor, frame:Frame, target:Frame):
578
+ img_mask = processor.Run(frame, self.options.masking_text)
579
+ img_mask = cv2.resize(img_mask, (target.shape[1], target.shape[0]))
580
+ img_mask = np.reshape(img_mask, [img_mask.shape[0],img_mask.shape[1],1])
581
+
582
+ target = target.astype(np.float32)
583
+ result = (1-img_mask) * target
584
+ result += img_mask * frame.astype(np.float32)
585
+ return np.uint8(result)
586
+
587
+
588
+
589
+
590
+ def unload_models():
591
+ pass
592
+
593
+
594
+ def release_resources(self):
595
+ for p in self.processors:
596
+ p.Release()
597
+ self.processors.clear()
598
+
roop/ProcessOptions.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ class ProcessOptions:
2
+
3
+ def __init__(self,processors, face_distance, blend_ratio, swap_mode, selected_index, masking_text):
4
+ self.processors = processors
5
+ self.face_distance_threshold = face_distance
6
+ self.blend_ratio = blend_ratio
7
+ self.swap_mode = swap_mode
8
+ self.selected_index = selected_index
9
+ self.masking_text = masking_text
roop/__init__.py ADDED
File without changes
roop/capturer.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ import cv2
3
+
4
+ from roop.typing import Frame
5
+
6
+ def get_image_frame(filename: str):
7
+ try:
8
+ frame = cv2.imread(filename)
9
+ return frame
10
+ except:
11
+ print(f"Exception reading {filename}")
12
+ return None
13
+
14
+
15
+ def get_video_frame(video_path: str, frame_number: int = 0) -> Optional[Frame]:
16
+ capture = cv2.VideoCapture(video_path)
17
+ frame_total = capture.get(cv2.CAP_PROP_FRAME_COUNT)
18
+ capture.set(cv2.CAP_PROP_POS_FRAMES, min(frame_total, frame_number - 1))
19
+ has_frame, frame = capture.read()
20
+ capture.release()
21
+ if has_frame:
22
+ return frame
23
+ return None
24
+
25
+
26
+ def get_video_frame_total(video_path: str) -> int:
27
+ capture = cv2.VideoCapture(video_path)
28
+ video_frame_total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
29
+ capture.release()
30
+ return video_frame_total
roop/core.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import os
4
+ import sys
5
+ import shutil
6
+ # single thread doubles cuda performance - needs to be set before torch import
7
+ if any(arg.startswith('--execution-provider') for arg in sys.argv):
8
+ os.environ['OMP_NUM_THREADS'] = '1'
9
+
10
+ import warnings
11
+ from typing import List
12
+ import platform
13
+ import signal
14
+ import torch
15
+ import onnxruntime
16
+ import pathlib
17
+
18
+ from time import time
19
+
20
+ import roop.globals
21
+ import roop.metadata
22
+ import roop.utilities as util
23
+ import roop.util_ffmpeg as ffmpeg
24
+ import ui.main as main
25
+ from settings import Settings
26
+ from roop.face_util import extract_face_images
27
+ from roop.ProcessEntry import ProcessEntry
28
+ from roop.ProcessMgr import ProcessMgr
29
+ from roop.ProcessOptions import ProcessOptions
30
+ from roop.capturer import get_video_frame_total
31
+
32
+
33
+ clip_text = None
34
+
35
+ call_display_ui = None
36
+
37
+ process_mgr = None
38
+
39
+
40
+ if 'ROCMExecutionProvider' in roop.globals.execution_providers:
41
+ del torch
42
+
43
+ warnings.filterwarnings('ignore', category=FutureWarning, module='insightface')
44
+ warnings.filterwarnings('ignore', category=UserWarning, module='torchvision')
45
+
46
+
47
+ def parse_args() -> None:
48
+ signal.signal(signal.SIGINT, lambda signal_number, frame: destroy())
49
+ roop.globals.headless = False
50
+ # Always enable all processors when using GUI
51
+ if len(sys.argv) > 1:
52
+ print('No CLI args supported - use Settings Tab instead')
53
+ roop.globals.frame_processors = ['face_swapper', 'face_enhancer']
54
+
55
+
56
+ def encode_execution_providers(execution_providers: List[str]) -> List[str]:
57
+ return [execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers]
58
+
59
+
60
+ def decode_execution_providers(execution_providers: List[str]) -> List[str]:
61
+ return [provider for provider, encoded_execution_provider in zip(onnxruntime.get_available_providers(), encode_execution_providers(onnxruntime.get_available_providers()))
62
+ if any(execution_provider in encoded_execution_provider for execution_provider in execution_providers)]
63
+
64
+
65
+ def suggest_max_memory() -> int:
66
+ if platform.system().lower() == 'darwin':
67
+ return 4
68
+ return 16
69
+
70
+
71
+ def suggest_execution_providers() -> List[str]:
72
+ return encode_execution_providers(onnxruntime.get_available_providers())
73
+
74
+
75
+ def suggest_execution_threads() -> int:
76
+ if 'DmlExecutionProvider' in roop.globals.execution_providers:
77
+ return 1
78
+ if 'ROCMExecutionProvider' in roop.globals.execution_providers:
79
+ return 1
80
+ return 8
81
+
82
+
83
+ def limit_resources() -> None:
84
+ # limit memory usage
85
+ if roop.globals.max_memory:
86
+ memory = roop.globals.max_memory * 1024 ** 3
87
+ if platform.system().lower() == 'darwin':
88
+ memory = roop.globals.max_memory * 1024 ** 6
89
+ if platform.system().lower() == 'windows':
90
+ import ctypes
91
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
92
+ kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
93
+ else:
94
+ import resource
95
+ resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
96
+
97
+
98
+
99
+ def release_resources() -> None:
100
+ import gc
101
+ global process_mgr
102
+
103
+ if process_mgr is not None:
104
+ process_mgr.release_resources()
105
+ process_mgr = None
106
+
107
+ gc.collect()
108
+ # if 'CUDAExecutionProvider' in roop.globals.execution_providers and torch.cuda.is_available():
109
+ # with torch.cuda.device('cuda'):
110
+ # torch.cuda.empty_cache()
111
+ # torch.cuda.ipc_collect()
112
+
113
+
114
+ def pre_check() -> bool:
115
+ if sys.version_info < (3, 9):
116
+ update_status('Python version is not supported - please upgrade to 3.9 or higher.')
117
+ return False
118
+
119
+ download_directory_path = util.resolve_relative_path('../models')
120
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/inswapper_128.onnx'])
121
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/GFPGANv1.4.onnx'])
122
+ util.conditional_download(download_directory_path, ['https://github.com/csxmli2016/DMDNet/releases/download/v1/DMDNet.pth'])
123
+ util.conditional_download(download_directory_path, ['https://github.com/facefusion/facefusion-assets/releases/download/models/GPEN-BFR-512.onnx'])
124
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/restoreformer.onnx'])
125
+ download_directory_path = util.resolve_relative_path('../models/CLIP')
126
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/rd64-uni-refined.pth'])
127
+ download_directory_path = util.resolve_relative_path('../models/CodeFormer')
128
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/CodeFormerv0.1.onnx'])
129
+
130
+ if not shutil.which('ffmpeg'):
131
+ update_status('ffmpeg is not installed.')
132
+ return True
133
+
134
+ def set_display_ui(function):
135
+ global call_display_ui
136
+
137
+ call_display_ui = function
138
+
139
+
140
+ def update_status(message: str) -> None:
141
+ global call_display_ui
142
+
143
+ print(message)
144
+ if call_display_ui is not None:
145
+ call_display_ui(message)
146
+
147
+
148
+
149
+
150
+ def start() -> None:
151
+ if roop.globals.headless:
152
+ print('Headless mode currently unsupported - starting UI!')
153
+ # faces = extract_face_images(roop.globals.source_path, (False, 0))
154
+ # roop.globals.INPUT_FACES.append(faces[roop.globals.source_face_index])
155
+ # faces = extract_face_images(roop.globals.target_path, (False, util.has_image_extension(roop.globals.target_path)))
156
+ # roop.globals.TARGET_FACES.append(faces[roop.globals.target_face_index])
157
+ # if 'face_enhancer' in roop.globals.frame_processors:
158
+ # roop.globals.selected_enhancer = 'GFPGAN'
159
+
160
+ batch_process(None, False, None)
161
+
162
+
163
+ def get_processing_plugins(use_clip):
164
+ processors = "faceswap"
165
+ if use_clip:
166
+ processors += ",mask_clip2seg"
167
+
168
+ if roop.globals.selected_enhancer == 'GFPGAN':
169
+ processors += ",gfpgan"
170
+ elif roop.globals.selected_enhancer == 'Codeformer':
171
+ processors += ",codeformer"
172
+ elif roop.globals.selected_enhancer == 'DMDNet':
173
+ processors += ",dmdnet"
174
+ elif roop.globals.selected_enhancer == 'GPEN':
175
+ processors += ",gpen"
176
+ elif roop.globals.selected_enhancer == 'Restoreformer':
177
+ processors += ",restoreformer"
178
+ return processors
179
+
180
+
181
+ def live_swap(frame, swap_mode, use_clip, clip_text, selected_index = 0):
182
+ global process_mgr
183
+
184
+ if frame is None:
185
+ return frame
186
+
187
+ if process_mgr is None:
188
+ process_mgr = ProcessMgr(None)
189
+
190
+ options = ProcessOptions(get_processing_plugins(use_clip), roop.globals.distance_threshold, roop.globals.blend_ratio, swap_mode, selected_index, clip_text)
191
+ process_mgr.initialize(roop.globals.INPUT_FACESETS, roop.globals.TARGET_FACES, options)
192
+ newframe = process_mgr.process_frame(frame)
193
+ if newframe is None:
194
+ return frame
195
+ return newframe
196
+
197
+
198
+ def preview_mask(frame, clip_text):
199
+ import numpy as np
200
+ global process_mgr
201
+
202
+ maskimage = np.zeros((frame.shape), np.uint8)
203
+ if process_mgr is None:
204
+ process_mgr = ProcessMgr(None)
205
+ options = ProcessOptions("mask_clip2seg", roop.globals.distance_threshold, roop.globals.blend_ratio, "None", 0, clip_text)
206
+ process_mgr.initialize(roop.globals.INPUT_FACESETS, roop.globals.TARGET_FACES, options)
207
+ maskprocessor = next((x for x in process_mgr.processors if x.processorname == 'clip2seg'), None)
208
+ return process_mgr.process_mask(maskprocessor, frame, maskimage)
209
+
210
+
211
+
212
+
213
+
214
+ def batch_process(files:list[ProcessEntry], use_clip, new_clip_text, use_new_method, progress) -> None:
215
+ global clip_text, process_mgr
216
+
217
+ roop.globals.processing = True
218
+ release_resources()
219
+ limit_resources()
220
+
221
+ # limit threads for some providers
222
+ max_threads = suggest_execution_threads()
223
+ if max_threads == 1:
224
+ roop.globals.execution_threads = 1
225
+
226
+ imagefiles:list[ProcessEntry] = []
227
+ videofiles:list[ProcessEntry] = []
228
+
229
+ update_status('Sorting videos/images')
230
+
231
+
232
+ for index, f in enumerate(files):
233
+ fullname = f.filename
234
+ if util.has_image_extension(fullname):
235
+ destination = util.get_destfilename_from_path(fullname, roop.globals.output_path, f'.{roop.globals.CFG.output_image_format}')
236
+ destination = util.replace_template(destination, index=index)
237
+ pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
238
+ f.finalname = destination
239
+ imagefiles.append(f)
240
+
241
+ elif util.is_video(fullname) or util.has_extension(fullname, ['gif']):
242
+ destination = util.get_destfilename_from_path(fullname, roop.globals.output_path, f'__temp.{roop.globals.CFG.output_video_format}')
243
+ f.finalname = destination
244
+ videofiles.append(f)
245
+
246
+
247
+ if process_mgr is None:
248
+ process_mgr = ProcessMgr(progress)
249
+
250
+ options = ProcessOptions(get_processing_plugins(use_clip), roop.globals.distance_threshold, roop.globals.blend_ratio, roop.globals.face_swap_mode, 0, new_clip_text)
251
+ process_mgr.initialize(roop.globals.INPUT_FACESETS, roop.globals.TARGET_FACES, options)
252
+
253
+ if(len(imagefiles) > 0):
254
+ update_status('Processing image(s)')
255
+ origimages = []
256
+ fakeimages = []
257
+ for f in imagefiles:
258
+ origimages.append(f.filename)
259
+ fakeimages.append(f.finalname)
260
+
261
+ process_mgr.run_batch(origimages, fakeimages, roop.globals.execution_threads)
262
+ origimages.clear()
263
+ fakeimages.clear()
264
+
265
+ if(len(videofiles) > 0):
266
+ for index,v in enumerate(videofiles):
267
+ if not roop.globals.processing:
268
+ end_processing('Processing stopped!')
269
+ return
270
+ fps = v.fps if v.fps > 0 else util.detect_fps(v.filename)
271
+ if v.endframe == 0:
272
+ v.endframe = get_video_frame_total(v.filename)
273
+
274
+ update_status(f'Creating {os.path.basename(v.finalname)} with {fps} FPS...')
275
+ start_processing = time()
276
+ if roop.globals.keep_frames or not use_new_method:
277
+ util.create_temp(v.filename)
278
+ update_status('Extracting frames...')
279
+ ffmpeg.extract_frames(v.filename,v.startframe,v.endframe, fps)
280
+ if not roop.globals.processing:
281
+ end_processing('Processing stopped!')
282
+ return
283
+
284
+ temp_frame_paths = util.get_temp_frame_paths(v.filename)
285
+ process_mgr.run_batch(temp_frame_paths, temp_frame_paths, roop.globals.execution_threads)
286
+ if not roop.globals.processing:
287
+ end_processing('Processing stopped!')
288
+ return
289
+ if roop.globals.wait_after_extraction:
290
+ extract_path = os.path.dirname(temp_frame_paths[0])
291
+ util.open_folder(extract_path)
292
+ input("Press any key to continue...")
293
+ print("Resorting frames to create video")
294
+ util.sort_rename_frames(extract_path)
295
+
296
+ ffmpeg.create_video(v.filename, v.finalname, fps)
297
+ if not roop.globals.keep_frames:
298
+ util.delete_temp_frames(temp_frame_paths[0])
299
+ else:
300
+ if util.has_extension(v.filename, ['gif']):
301
+ skip_audio = True
302
+ else:
303
+ skip_audio = roop.globals.skip_audio
304
+ process_mgr.run_batch_inmem(v.filename, v.finalname, v.startframe, v.endframe, fps,roop.globals.execution_threads, skip_audio)
305
+
306
+ if not roop.globals.processing:
307
+ end_processing('Processing stopped!')
308
+ return
309
+
310
+ video_file_name = v.finalname
311
+ if os.path.isfile(video_file_name):
312
+ destination = ''
313
+ if util.has_extension(v.filename, ['gif']):
314
+ gifname = util.get_destfilename_from_path(v.filename, roop.globals.output_path, '.gif')
315
+ destination = util.replace_template(gifname, index=index)
316
+ pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
317
+
318
+ update_status('Creating final GIF')
319
+ ffmpeg.create_gif_from_video(video_file_name, destination)
320
+ if os.path.isfile(destination):
321
+ os.remove(video_file_name)
322
+ else:
323
+ skip_audio = roop.globals.skip_audio
324
+ destination = util.replace_template(video_file_name, index=index)
325
+ pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
326
+
327
+ if not skip_audio:
328
+ ffmpeg.restore_audio(video_file_name, v.filename, v.startframe, v.endframe, destination)
329
+ if os.path.isfile(destination):
330
+ os.remove(video_file_name)
331
+ else:
332
+ shutil.move(video_file_name, destination)
333
+ update_status(f'\nProcessing {os.path.basename(destination)} took {time() - start_processing} secs')
334
+
335
+ else:
336
+ update_status(f'Failed processing {os.path.basename(v.finalname)}!')
337
+ end_processing('Finished')
338
+
339
+
340
+ def end_processing(msg:str):
341
+ update_status(msg)
342
+ roop.globals.target_folder_path = None
343
+ release_resources()
344
+
345
+
346
+ def destroy() -> None:
347
+ if roop.globals.target_path:
348
+ util.clean_temp(roop.globals.target_path)
349
+ release_resources()
350
+ sys.exit()
351
+
352
+
353
+ def run() -> None:
354
+ parse_args()
355
+ if not pre_check():
356
+ return
357
+ roop.globals.CFG = Settings('config.yaml')
358
+ roop.globals.execution_threads = roop.globals.CFG.max_threads
359
+ roop.globals.video_encoder = roop.globals.CFG.output_video_codec
360
+ roop.globals.video_quality = roop.globals.CFG.video_quality
361
+ roop.globals.max_memory = roop.globals.CFG.memory_limit if roop.globals.CFG.memory_limit > 0 else None
362
+ main.run()
roop/face_util.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ from typing import Any
3
+ import insightface
4
+
5
+ import roop.globals
6
+ from roop.typing import Frame, Face
7
+
8
+ import cv2
9
+ import numpy as np
10
+ from skimage import transform as trans
11
+ from roop.capturer import get_video_frame
12
+ from roop.utilities import resolve_relative_path, conditional_download
13
+
14
+ FACE_ANALYSER = None
15
+ THREAD_LOCK_ANALYSER = threading.Lock()
16
+ THREAD_LOCK_SWAPPER = threading.Lock()
17
+ FACE_SWAPPER = None
18
+
19
+
20
+ def get_face_analyser() -> Any:
21
+ global FACE_ANALYSER
22
+
23
+ with THREAD_LOCK_ANALYSER:
24
+ if FACE_ANALYSER is None:
25
+ model_path = resolve_relative_path('..')
26
+ if roop.globals.CFG.force_cpu:
27
+ print("Forcing CPU for Face Analysis")
28
+ FACE_ANALYSER = insightface.app.FaceAnalysis(
29
+ name="buffalo_l", root=model_path, providers=["CPUExecutionProvider"]
30
+ )
31
+ else:
32
+ FACE_ANALYSER = insightface.app.FaceAnalysis(
33
+ name="buffalo_l", root=model_path, providers=roop.globals.execution_providers
34
+ )
35
+ FACE_ANALYSER.prepare(
36
+ ctx_id=0,
37
+ det_size=(640, 640) if roop.globals.default_det_size else (320, 320),
38
+ )
39
+ return FACE_ANALYSER
40
+
41
+
42
+ def get_first_face(frame: Frame) -> Any:
43
+ try:
44
+ faces = get_face_analyser().get(frame)
45
+ return min(faces, key=lambda x: x.bbox[0])
46
+ # return sorted(faces, reverse=True, key=lambda x: (x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1]))[0]
47
+ except:
48
+ return None
49
+
50
+
51
+ def get_all_faces(frame: Frame) -> Any:
52
+ try:
53
+ faces = get_face_analyser().get(frame)
54
+ return sorted(faces, key=lambda x: x.bbox[0])
55
+ except:
56
+ return None
57
+
58
+
59
+ def extract_face_images(source_filename, video_info, extra_padding=-1.0):
60
+ face_data = []
61
+ source_image = None
62
+
63
+ if video_info[0]:
64
+ frame = get_video_frame(source_filename, video_info[1])
65
+ if frame is not None:
66
+ source_image = frame
67
+ else:
68
+ return face_data
69
+ else:
70
+ source_image = cv2.imread(source_filename)
71
+
72
+ faces = get_all_faces(source_image)
73
+ if faces is None:
74
+ return face_data
75
+
76
+ i = 0
77
+ for face in faces:
78
+ (startX, startY, endX, endY) = face["bbox"].astype("int")
79
+ if extra_padding > 0.0:
80
+ if source_image.shape[:2] == (512, 512):
81
+ i += 1
82
+ face_data.append([face, source_image])
83
+ continue
84
+
85
+ found = False
86
+ for i in range(1, 3):
87
+ (startX, startY, endX, endY) = face["bbox"].astype("int")
88
+ cutout_padding = extra_padding
89
+ # top needs extra room for detection
90
+ padding = int((endY - startY) * cutout_padding)
91
+ oldY = startY
92
+ startY -= padding
93
+
94
+ factor = 0.25 if i == 1 else 0.5
95
+ cutout_padding = factor
96
+ padding = int((endY - oldY) * cutout_padding)
97
+ endY += padding
98
+ padding = int((endX - startX) * cutout_padding)
99
+ startX -= padding
100
+ endX += padding
101
+ startX, endX, startY, endY = clamp_cut_values(
102
+ startX, endX, startY, endY, source_image
103
+ )
104
+ face_temp = source_image[startY:endY, startX:endX]
105
+ face_temp = resize_image_keep_content(face_temp)
106
+ testfaces = get_all_faces(face_temp)
107
+ if testfaces is not None and len(testfaces) > 0:
108
+ i += 1
109
+ face_data.append([testfaces[0], face_temp])
110
+ found = True
111
+ break
112
+
113
+ if not found:
114
+ print("No face found after resizing, this shouldn't happen!")
115
+ continue
116
+
117
+ face_temp = source_image[startY:endY, startX:endX]
118
+ if face_temp.size < 1:
119
+ continue
120
+
121
+ i += 1
122
+ face_data.append([face, face_temp])
123
+ return face_data
124
+
125
+
126
+ def clamp_cut_values(startX, endX, startY, endY, image):
127
+ if startX < 0:
128
+ startX = 0
129
+ if endX > image.shape[1]:
130
+ endX = image.shape[1]
131
+ if startY < 0:
132
+ startY = 0
133
+ if endY > image.shape[0]:
134
+ endY = image.shape[0]
135
+ return startX, endX, startY, endY
136
+
137
+
138
+ def get_face_swapper() -> Any:
139
+ global FACE_SWAPPER
140
+
141
+ with THREAD_LOCK_SWAPPER:
142
+ if FACE_SWAPPER is None:
143
+ model_path = resolve_relative_path("../models/inswapper_128.onnx")
144
+ FACE_SWAPPER = insightface.model_zoo.get_model(
145
+ model_path, providers=roop.globals.execution_providers
146
+ )
147
+ return FACE_SWAPPER
148
+
149
+
150
+ def pre_check() -> bool:
151
+ download_directory_path = resolve_relative_path("../models")
152
+ conditional_download(
153
+ download_directory_path,
154
+ ["https://huggingface.co/countfloyd/deepfake/resolve/main/inswapper_128.onnx"],
155
+ )
156
+ return True
157
+
158
+
159
+ def swap_face(source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
160
+ return get_face_swapper().get(temp_frame, target_face, source_face, paste_back=True)
161
+
162
+
163
+ def face_offset_top(face: Face, offset):
164
+ face["bbox"][1] += offset
165
+ face["bbox"][3] += offset
166
+ lm106 = face.landmark_2d_106
167
+ add = np.full_like(lm106, [0, offset])
168
+ face["landmark_2d_106"] = lm106 + add
169
+ return face
170
+
171
+
172
+ def resize_image_keep_content(image, new_width=512, new_height=512):
173
+ dim = None
174
+ (h, w) = image.shape[:2]
175
+ if h > w:
176
+ r = new_height / float(h)
177
+ dim = (int(w * r), new_height)
178
+ else:
179
+ # Calculate the ratio of the width and construct the dimensions
180
+ r = new_width / float(w)
181
+ dim = (new_width, int(h * r))
182
+ image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
183
+ (h, w) = image.shape[:2]
184
+ if h == new_height and w == new_width:
185
+ return image
186
+ resize_img = np.zeros(shape=(new_height, new_width, 3), dtype=image.dtype)
187
+ offs = (new_width - w) if h == new_height else (new_height - h)
188
+ startoffs = int(offs // 2) if offs % 2 == 0 else int(offs // 2) + 1
189
+ offs = int(offs // 2)
190
+
191
+ if h == new_height:
192
+ resize_img[0:new_height, startoffs : new_width - offs] = image
193
+ else:
194
+ resize_img[startoffs : new_height - offs, 0:new_width] = image
195
+ return resize_img
196
+
197
+
198
+ def rotate_image_90(image, rotate=True):
199
+ if rotate:
200
+ return np.rot90(image)
201
+ else:
202
+ return np.rot90(image, 1, (1, 0))
203
+
204
+
205
+ def rotate_anticlockwise(frame):
206
+ return rotate_image_90(frame)
207
+
208
+
209
+ def rotate_clockwise(frame):
210
+ return rotate_image_90(frame, False)
211
+
212
+
213
+ def rotate_image_180(image):
214
+ return np.flip(image, 0)
215
+
216
+
217
+ # alignment code from insightface https://github.com/deepinsight/insightface/blob/master/python-package/insightface/utils/face_align.py
218
+
219
+ arcface_dst = np.array(
220
+ [
221
+ [38.2946, 51.6963],
222
+ [73.5318, 51.5014],
223
+ [56.0252, 71.7366],
224
+ [41.5493, 92.3655],
225
+ [70.7299, 92.2041],
226
+ ],
227
+ dtype=np.float32,
228
+ )
229
+
230
+
231
+ def estimate_norm(lmk, image_size=112, mode="arcface"):
232
+ assert lmk.shape == (5, 2)
233
+ assert image_size % 112 == 0 or image_size % 128 == 0
234
+ if image_size % 112 == 0:
235
+ ratio = float(image_size) / 112.0
236
+ diff_x = 0
237
+ else:
238
+ ratio = float(image_size) / 128.0
239
+ diff_x = 8.0 * ratio
240
+ dst = arcface_dst * ratio
241
+ dst[:, 0] += diff_x
242
+ tform = trans.SimilarityTransform()
243
+ tform.estimate(lmk, dst)
244
+ M = tform.params[0:2, :]
245
+ return M
246
+
247
+
248
+ def norm_crop(img, landmark, image_size=112, mode="arcface"):
249
+ M = estimate_norm(landmark, image_size, mode)
250
+ warped = cv2.warpAffine(img, M, (image_size, image_size), borderValue=0.0)
251
+ return warped
252
+
253
+
254
+ # aligned, M = norm_crop2(f[1], face.kps, 512)
255
+ def norm_crop2(img, landmark, image_size=112, mode="arcface"):
256
+ M = estimate_norm(landmark, image_size, mode)
257
+ warped = cv2.warpAffine(img, M, (image_size, image_size), borderValue=0.0)
258
+ return warped, M
259
+
260
+
261
+ def square_crop(im, S):
262
+ if im.shape[0] > im.shape[1]:
263
+ height = S
264
+ width = int(float(im.shape[1]) / im.shape[0] * S)
265
+ scale = float(S) / im.shape[0]
266
+ else:
267
+ width = S
268
+ height = int(float(im.shape[0]) / im.shape[1] * S)
269
+ scale = float(S) / im.shape[1]
270
+ resized_im = cv2.resize(im, (width, height))
271
+ det_im = np.zeros((S, S, 3), dtype=np.uint8)
272
+ det_im[: resized_im.shape[0], : resized_im.shape[1], :] = resized_im
273
+ return det_im, scale
274
+
275
+
276
+ def transform(data, center, output_size, scale, rotation):
277
+ scale_ratio = scale
278
+ rot = float(rotation) * np.pi / 180.0
279
+ # translation = (output_size/2-center[0]*scale_ratio, output_size/2-center[1]*scale_ratio)
280
+ t1 = trans.SimilarityTransform(scale=scale_ratio)
281
+ cx = center[0] * scale_ratio
282
+ cy = center[1] * scale_ratio
283
+ t2 = trans.SimilarityTransform(translation=(-1 * cx, -1 * cy))
284
+ t3 = trans.SimilarityTransform(rotation=rot)
285
+ t4 = trans.SimilarityTransform(translation=(output_size / 2, output_size / 2))
286
+ t = t1 + t2 + t3 + t4
287
+ M = t.params[0:2]
288
+ cropped = cv2.warpAffine(data, M, (output_size, output_size), borderValue=0.0)
289
+ return cropped, M
290
+
291
+
292
+ def trans_points2d(pts, M):
293
+ new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
294
+ for i in range(pts.shape[0]):
295
+ pt = pts[i]
296
+ new_pt = np.array([pt[0], pt[1], 1.0], dtype=np.float32)
297
+ new_pt = np.dot(M, new_pt)
298
+ # print('new_pt', new_pt.shape, new_pt)
299
+ new_pts[i] = new_pt[0:2]
300
+
301
+ return new_pts
302
+
303
+
304
+ def trans_points3d(pts, M):
305
+ scale = np.sqrt(M[0][0] * M[0][0] + M[0][1] * M[0][1])
306
+ # print(scale)
307
+ new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
308
+ for i in range(pts.shape[0]):
309
+ pt = pts[i]
310
+ new_pt = np.array([pt[0], pt[1], 1.0], dtype=np.float32)
311
+ new_pt = np.dot(M, new_pt)
312
+ # print('new_pt', new_pt.shape, new_pt)
313
+ new_pts[i][0:2] = new_pt[0:2]
314
+ new_pts[i][2] = pts[i][2] * scale
315
+
316
+ return new_pts
317
+
318
+
319
+ def trans_points(pts, M):
320
+ if pts.shape[1] == 2:
321
+ return trans_points2d(pts, M)
322
+ else:
323
+ return trans_points3d(pts, M)
324
+
roop/ffmpeg_writer.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FFMPEG_Writer - write set of frames to video file
3
+
4
+ original from
5
+ https://github.com/Zulko/moviepy/blob/master/moviepy/video/io/ffmpeg_writer.py
6
+
7
+ removed unnecessary dependencies
8
+
9
+ The MIT License (MIT)
10
+
11
+ Copyright (c) 2015 Zulko
12
+ Copyright (c) 2023 Janvarev Vladislav
13
+ """
14
+
15
+ import os
16
+ import subprocess as sp
17
+
18
+ PIPE = -1
19
+ STDOUT = -2
20
+ DEVNULL = -3
21
+
22
+ FFMPEG_BINARY = "ffmpeg"
23
+
24
+ class FFMPEG_VideoWriter:
25
+ """ A class for FFMPEG-based video writing.
26
+
27
+ A class to write videos using ffmpeg. ffmpeg will write in a large
28
+ choice of formats.
29
+
30
+ Parameters
31
+ -----------
32
+
33
+ filename
34
+ Any filename like 'video.mp4' etc. but if you want to avoid
35
+ complications it is recommended to use the generic extension
36
+ '.avi' for all your videos.
37
+
38
+ size
39
+ Size (width,height) of the output video in pixels.
40
+
41
+ fps
42
+ Frames per second in the output video file.
43
+
44
+ codec
45
+ FFMPEG codec. It seems that in terms of quality the hierarchy is
46
+ 'rawvideo' = 'png' > 'mpeg4' > 'libx264'
47
+ 'png' manages the same lossless quality as 'rawvideo' but yields
48
+ smaller files. Type ``ffmpeg -codecs`` in a terminal to get a list
49
+ of accepted codecs.
50
+
51
+ Note for default 'libx264': by default the pixel format yuv420p
52
+ is used. If the video dimensions are not both even (e.g. 720x405)
53
+ another pixel format is used, and this can cause problem in some
54
+ video readers.
55
+
56
+ audiofile
57
+ Optional: The name of an audio file that will be incorporated
58
+ to the video.
59
+
60
+ preset
61
+ Sets the time that FFMPEG will take to compress the video. The slower,
62
+ the better the compression rate. Possibilities are: ultrafast,superfast,
63
+ veryfast, faster, fast, medium (default), slow, slower, veryslow,
64
+ placebo.
65
+
66
+ bitrate
67
+ Only relevant for codecs which accept a bitrate. "5000k" offers
68
+ nice results in general.
69
+
70
+ """
71
+
72
+ def __init__(self, filename, size, fps, codec="libx265", crf=14, audiofile=None,
73
+ preset="medium", bitrate=None,
74
+ logfile=None, threads=None, ffmpeg_params=None):
75
+
76
+ if logfile is None:
77
+ logfile = sp.PIPE
78
+
79
+ self.filename = filename
80
+ self.codec = codec
81
+ self.ext = self.filename.split(".")[-1]
82
+ w = size[0] - 1 if size[0] % 2 != 0 else size[0]
83
+ h = size[1] - 1 if size[1] % 2 != 0 else size[1]
84
+
85
+
86
+ # order is important
87
+ cmd = [
88
+ FFMPEG_BINARY,
89
+ '-hide_banner',
90
+ '-hwaccel', 'auto',
91
+ '-y',
92
+ '-loglevel', 'error' if logfile == sp.PIPE else 'info',
93
+ '-f', 'rawvideo',
94
+ '-vcodec', 'rawvideo',
95
+ '-s', '%dx%d' % (size[0], size[1]),
96
+ #'-pix_fmt', 'rgba' if withmask else 'rgb24',
97
+ '-pix_fmt', 'bgr24',
98
+ '-r', str(fps),
99
+ '-an', '-i', '-'
100
+ ]
101
+
102
+ if audiofile is not None:
103
+ cmd.extend([
104
+ '-i', audiofile,
105
+ '-acodec', 'copy'
106
+ ])
107
+
108
+ cmd.extend([
109
+ '-vcodec', codec,
110
+ '-crf', str(crf)
111
+ #'-preset', preset,
112
+ ])
113
+ if ffmpeg_params is not None:
114
+ cmd.extend(ffmpeg_params)
115
+ if bitrate is not None:
116
+ cmd.extend([
117
+ '-b', bitrate
118
+ ])
119
+
120
+ # scale to a resolution divisible by 2 if not even
121
+ cmd.extend(['-vf', f'scale={w}:{h}' if w != size[0] or h != size[1] else 'colorspace=bt709:iall=bt601-6-625:fast=1'])
122
+
123
+ if threads is not None:
124
+ cmd.extend(["-threads", str(threads)])
125
+
126
+ cmd.extend([
127
+ '-pix_fmt', 'yuv420p',
128
+
129
+ ])
130
+ cmd.extend([
131
+ filename
132
+ ])
133
+
134
+ test = str(cmd)
135
+ print(test)
136
+
137
+ popen_params = {"stdout": DEVNULL,
138
+ "stderr": logfile,
139
+ "stdin": sp.PIPE}
140
+
141
+ # This was added so that no extra unwanted window opens on windows
142
+ # when the child process is created
143
+ if os.name == "nt":
144
+ popen_params["creationflags"] = 0x08000000 # CREATE_NO_WINDOW
145
+
146
+ self.proc = sp.Popen(cmd, **popen_params)
147
+
148
+
149
+ def write_frame(self, img_array):
150
+ """ Writes one frame in the file."""
151
+ try:
152
+ #if PY3:
153
+ self.proc.stdin.write(img_array.tobytes())
154
+ # else:
155
+ # self.proc.stdin.write(img_array.tostring())
156
+ except IOError as err:
157
+ _, ffmpeg_error = self.proc.communicate()
158
+ error = (str(err) + ("\n\nroop unleashed error: FFMPEG encountered "
159
+ "the following error while writing file %s:"
160
+ "\n\n %s" % (self.filename, str(ffmpeg_error))))
161
+
162
+ if b"Unknown encoder" in ffmpeg_error:
163
+
164
+ error = error+("\n\nThe video export "
165
+ "failed because FFMPEG didn't find the specified "
166
+ "codec for video encoding (%s). Please install "
167
+ "this codec or change the codec when calling "
168
+ "write_videofile. For instance:\n"
169
+ " >>> clip.write_videofile('myvid.webm', codec='libvpx')")%(self.codec)
170
+
171
+ elif b"incorrect codec parameters ?" in ffmpeg_error:
172
+
173
+ error = error+("\n\nThe video export "
174
+ "failed, possibly because the codec specified for "
175
+ "the video (%s) is not compatible with the given "
176
+ "extension (%s). Please specify a valid 'codec' "
177
+ "argument in write_videofile. This would be 'libx264' "
178
+ "or 'mpeg4' for mp4, 'libtheora' for ogv, 'libvpx for webm. "
179
+ "Another possible reason is that the audio codec was not "
180
+ "compatible with the video codec. For instance the video "
181
+ "extensions 'ogv' and 'webm' only allow 'libvorbis' (default) as a"
182
+ "video codec."
183
+ )%(self.codec, self.ext)
184
+
185
+ elif b"encoder setup failed" in ffmpeg_error:
186
+
187
+ error = error+("\n\nThe video export "
188
+ "failed, possibly because the bitrate you specified "
189
+ "was too high or too low for the video codec.")
190
+
191
+ elif b"Invalid encoder type" in ffmpeg_error:
192
+
193
+ error = error + ("\n\nThe video export failed because the codec "
194
+ "or file extension you provided is not a video")
195
+
196
+
197
+ raise IOError(error)
198
+
199
+ def close(self):
200
+ if self.proc:
201
+ self.proc.stdin.close()
202
+ if self.proc.stderr is not None:
203
+ self.proc.stderr.close()
204
+ self.proc.wait()
205
+
206
+ self.proc = None
207
+
208
+ # Support the Context Manager protocol, to ensure that resources are cleaned up.
209
+
210
+ def __enter__(self):
211
+ return self
212
+
213
+ def __exit__(self, exc_type, exc_value, traceback):
214
+ self.close()
215
+
216
+
217
+
218
+
roop/globals.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from settings import Settings
2
+ from typing import List
3
+
4
+ source_path = None
5
+ target_path = None
6
+ output_path = None
7
+ target_folder_path = None
8
+
9
+ frame_processors: List[str] = []
10
+ keep_fps = None
11
+ keep_frames = None
12
+ autorotate_faces = None
13
+ vr_mode = None
14
+ skip_audio = None
15
+ wait_after_extraction = None
16
+ many_faces = None
17
+ use_batch = None
18
+ source_face_index = 0
19
+ target_face_index = 0
20
+ face_position = None
21
+ video_encoder = None
22
+ video_quality = None
23
+ max_memory = None
24
+ execution_providers: List[str] = []
25
+ execution_threads = None
26
+ headless = None
27
+ log_level = 'error'
28
+ selected_enhancer = None
29
+ face_swap_mode = None
30
+ blend_ratio = 0.5
31
+ distance_threshold = 0.65
32
+ default_det_size = True
33
+
34
+ no_face_action = 0
35
+
36
+ processing = False
37
+
38
+ FACE_ENHANCER = None
39
+
40
+ INPUT_FACESETS = []
41
+ TARGET_FACES = []
42
+
43
+ IMAGE_CHAIN_PROCESSOR = None
44
+ VIDEO_CHAIN_PROCESSOR = None
45
+ BATCH_IMAGE_CHAIN_PROCESSOR = None
46
+
47
+ CFG: Settings = None
48
+
49
+
roop/metadata.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ name = 'roop unleashed'
2
+ version = '3.5.0'
roop/processors/Enhance_CodeFormer.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import threading
4
+ import numpy as np
5
+ import onnxruntime
6
+ import onnx
7
+ import roop.globals
8
+
9
+ from roop.typing import Face, Frame, FaceSet
10
+ from roop.utilities import resolve_relative_path
11
+
12
+
13
+ # THREAD_LOCK = threading.Lock()
14
+
15
+
16
+ class Enhance_CodeFormer():
17
+ model_codeformer = None
18
+ devicename = None
19
+
20
+ processorname = 'codeformer'
21
+ type = 'enhance'
22
+
23
+
24
+ def Initialize(self, devicename:str):
25
+ if self.model_codeformer is None:
26
+ # replace Mac mps with cpu for the moment
27
+ devicename = devicename.replace('mps', 'cpu')
28
+ self.devicename = devicename
29
+ model_path = resolve_relative_path('../models/CodeFormer/CodeFormerv0.1.onnx')
30
+ self.model_codeformer = onnxruntime.InferenceSession(model_path, None, providers=roop.globals.execution_providers)
31
+ self.model_inputs = self.model_codeformer.get_inputs()
32
+ model_outputs = self.model_codeformer.get_outputs()
33
+ self.io_binding = self.model_codeformer.io_binding()
34
+ self.io_binding.bind_cpu_input(self.model_inputs[1].name, np.array([0.5]))
35
+ self.io_binding.bind_output(model_outputs[0].name, self.devicename)
36
+
37
+
38
+ def Run(self, source_faceset: FaceSet, target_face: Face, temp_frame: Frame) -> Frame:
39
+ input_size = temp_frame.shape[1]
40
+ # preprocess
41
+ temp_frame = cv2.resize(temp_frame, (512, 512), cv2.INTER_CUBIC)
42
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB)
43
+ temp_frame = temp_frame.astype('float32') / 255.0
44
+ temp_frame = (temp_frame - 0.5) / 0.5
45
+ temp_frame = np.expand_dims(temp_frame, axis=0).transpose(0, 3, 1, 2)
46
+
47
+ self.io_binding.bind_cpu_input(self.model_inputs[0].name, temp_frame.astype(np.float32))
48
+ self.model_codeformer.run_with_iobinding(self.io_binding)
49
+ ort_outs = self.io_binding.copy_outputs_to_cpu()
50
+ result = ort_outs[0][0]
51
+ del ort_outs
52
+
53
+ # post-process
54
+ result = result.transpose((1, 2, 0))
55
+
56
+ un_min = -1.0
57
+ un_max = 1.0
58
+ result = np.clip(result, un_min, un_max)
59
+ result = (result - un_min) / (un_max - un_min)
60
+
61
+ result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
62
+ result = (result * 255.0).round()
63
+ scale_factor = int(result.shape[1] / input_size)
64
+ return result.astype(np.uint8), scale_factor
65
+
66
+
67
+ def Release(self):
68
+ del self.model_codeformer
69
+ self.model_codeformer = None
70
+ del self.io_binding
71
+ self.io_binding = None
72
+
roop/processors/Enhance_DMDNet.py ADDED
@@ -0,0 +1,893 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import torch.nn.utils.spectral_norm as SpectralNorm
8
+ import threading
9
+ from torchvision.ops import roi_align
10
+
11
+ from math import sqrt
12
+
13
+ from torchvision.transforms.functional import normalize
14
+
15
+ from roop.typing import Face, Frame, FaceSet
16
+
17
+
18
+ THREAD_LOCK_DMDNET = threading.Lock()
19
+
20
+
21
+ class Enhance_DMDNet():
22
+
23
+ model_dmdnet = None
24
+ torchdevice = None
25
+
26
+ processorname = 'dmdnet'
27
+ type = 'enhance'
28
+
29
+
30
+ def Initialize(self, devicename):
31
+ if self.model_dmdnet is None:
32
+ self.model_dmdnet = self.create(devicename)
33
+
34
+
35
+ # temp_frame already cropped+aligned, bbox not
36
+ def Run(self, source_faceset: FaceSet, target_face: Face, temp_frame: Frame) -> Frame:
37
+ input_size = temp_frame.shape[1]
38
+
39
+ result = self.enhance_face(source_faceset, temp_frame, target_face)
40
+ scale_factor = int(result.shape[1] / input_size)
41
+ return result.astype(np.uint8), scale_factor
42
+
43
+
44
+ def Release(self):
45
+ self.model_gfpgan = None
46
+
47
+
48
+ # https://stackoverflow.com/a/67174339
49
+ def landmarks106_to_68(self, pt106):
50
+ map106to68=[1,10,12,14,16,3,5,7,0,23,21,19,32,30,28,26,17,
51
+ 43,48,49,51,50,
52
+ 102,103,104,105,101,
53
+ 72,73,74,86,78,79,80,85,84,
54
+ 35,41,42,39,37,36,
55
+ 89,95,96,93,91,90,
56
+ 52,64,63,71,67,68,61,58,59,53,56,55,65,66,62,70,69,57,60,54
57
+ ]
58
+
59
+ pt68 = []
60
+ for i in range(68):
61
+ index = map106to68[i]
62
+ pt68.append(pt106[index])
63
+ return pt68
64
+
65
+
66
+
67
+
68
+ def check_bbox(self, imgs, boxes):
69
+ boxes = boxes.view(-1, 4, 4)
70
+ colors = [(0, 255, 0), (0, 255, 0), (255, 255, 0), (255, 0, 0)]
71
+ i = 0
72
+ for img, box in zip(imgs, boxes):
73
+ img = (img + 1)/2 * 255
74
+ img2 = img.permute(1, 2, 0).float().cpu().flip(2).numpy().copy()
75
+ for idx, point in enumerate(box):
76
+ cv2.rectangle(img2, (int(point[0]), int(point[1])), (int(point[2]), int(point[3])), color=colors[idx], thickness=2)
77
+ cv2.imwrite('dmdnet_{:02d}.png'.format(i), img2)
78
+ i += 1
79
+
80
+
81
+ def trans_points2d(self, pts, M):
82
+ new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
83
+ for i in range(pts.shape[0]):
84
+ pt = pts[i]
85
+ new_pt = np.array([pt[0], pt[1], 1.0], dtype=np.float32)
86
+ new_pt = np.dot(M, new_pt)
87
+ new_pts[i] = new_pt[0:2]
88
+
89
+ return new_pts
90
+
91
+
92
+ def enhance_face(self, ref_faceset: FaceSet, temp_frame, face: Face):
93
+ # preprocess
94
+ start_x, start_y, end_x, end_y = map(int, face['bbox'])
95
+ lm106 = face.landmark_2d_106
96
+ lq_landmarks = np.asarray(self.landmarks106_to_68(lm106))
97
+
98
+ if temp_frame.shape[0] != 512 or temp_frame.shape[1] != 512:
99
+ # scale to 512x512
100
+ scale_factor = 512 / temp_frame.shape[1]
101
+
102
+ M = face.matrix * scale_factor
103
+
104
+ lq_landmarks = self.trans_points2d(lq_landmarks, M)
105
+ temp_frame = cv2.resize(temp_frame, (512,512), interpolation = cv2.INTER_AREA)
106
+
107
+ if temp_frame.ndim == 2:
108
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_GRAY2RGB) # GGG
109
+ # else:
110
+ # temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB) # RGB
111
+
112
+ lq = read_img_tensor(temp_frame)
113
+
114
+ LQLocs = get_component_location(lq_landmarks)
115
+ # self.check_bbox(lq, LQLocs.unsqueeze(0))
116
+
117
+ # specific, change 1000 to 1 to activate
118
+ if len(ref_faceset.faces) > 1:
119
+ SpecificImgs = []
120
+ SpecificLocs = []
121
+ for i,face in enumerate(ref_faceset.faces):
122
+ lm106 = face.landmark_2d_106
123
+ lq_landmarks = np.asarray(self.landmarks106_to_68(lm106))
124
+ ref_image = ref_faceset.ref_images[i]
125
+ if ref_image.shape[0] != 512 or ref_image.shape[1] != 512:
126
+ # scale to 512x512
127
+ scale_factor = 512 / ref_image.shape[1]
128
+
129
+ M = face.matrix * scale_factor
130
+
131
+ lq_landmarks = self.trans_points2d(lq_landmarks, M)
132
+ ref_image = cv2.resize(ref_image, (512,512), interpolation = cv2.INTER_AREA)
133
+
134
+ if ref_image.ndim == 2:
135
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_GRAY2RGB) # GGG
136
+ # else:
137
+ # temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB) # RGB
138
+
139
+ ref_tensor = read_img_tensor(ref_image)
140
+ ref_locs = get_component_location(lq_landmarks)
141
+ # self.check_bbox(ref_tensor, ref_locs.unsqueeze(0))
142
+
143
+ SpecificImgs.append(ref_tensor)
144
+ SpecificLocs.append(ref_locs.unsqueeze(0))
145
+
146
+ SpecificImgs = torch.cat(SpecificImgs, dim=0)
147
+ SpecificLocs = torch.cat(SpecificLocs, dim=0)
148
+ # check_bbox(SpecificImgs, SpecificLocs)
149
+ SpMem256, SpMem128, SpMem64 = self.model_dmdnet.generate_specific_dictionary(sp_imgs = SpecificImgs.to(self.torchdevice), sp_locs = SpecificLocs)
150
+ SpMem256Para = {}
151
+ SpMem128Para = {}
152
+ SpMem64Para = {}
153
+ for k, v in SpMem256.items():
154
+ SpMem256Para[k] = v
155
+ for k, v in SpMem128.items():
156
+ SpMem128Para[k] = v
157
+ for k, v in SpMem64.items():
158
+ SpMem64Para[k] = v
159
+ else:
160
+ # generic
161
+ SpMem256Para, SpMem128Para, SpMem64Para = None, None, None
162
+
163
+ with torch.no_grad():
164
+ with THREAD_LOCK_DMDNET:
165
+ try:
166
+ GenericResult, SpecificResult = self.model_dmdnet(lq = lq.to(self.torchdevice), loc = LQLocs.unsqueeze(0), sp_256 = SpMem256Para, sp_128 = SpMem128Para, sp_64 = SpMem64Para)
167
+ except Exception as e:
168
+ print(f'Error {e} there may be something wrong with the detected component locations.')
169
+ return temp_frame
170
+
171
+ if SpecificResult is not None:
172
+ save_specific = SpecificResult * 0.5 + 0.5
173
+ save_specific = save_specific.squeeze(0).permute(1, 2, 0).flip(2) # RGB->BGR
174
+ save_specific = np.clip(save_specific.float().cpu().numpy(), 0, 1) * 255.0
175
+ temp_frame = save_specific.astype("uint8")
176
+ if False:
177
+ save_generic = GenericResult * 0.5 + 0.5
178
+ save_generic = save_generic.squeeze(0).permute(1, 2, 0).flip(2) # RGB->BGR
179
+ save_generic = np.clip(save_generic.float().cpu().numpy(), 0, 1) * 255.0
180
+ check_lq = lq * 0.5 + 0.5
181
+ check_lq = check_lq.squeeze(0).permute(1, 2, 0).flip(2) # RGB->BGR
182
+ check_lq = np.clip(check_lq.float().cpu().numpy(), 0, 1) * 255.0
183
+ cv2.imwrite('dmdnet_comparison.png', cv2.cvtColor(np.hstack((check_lq, save_generic, save_specific)),cv2.COLOR_RGB2BGR))
184
+ else:
185
+ save_generic = GenericResult * 0.5 + 0.5
186
+ save_generic = save_generic.squeeze(0).permute(1, 2, 0).flip(2) # RGB->BGR
187
+ save_generic = np.clip(save_generic.float().cpu().numpy(), 0, 1) * 255.0
188
+ temp_frame = save_generic.astype("uint8")
189
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_RGB2BGR) # RGB
190
+ return temp_frame
191
+
192
+
193
+
194
+ def create(self, devicename):
195
+ self.torchdevice = torch.device(devicename)
196
+ model_dmdnet = DMDNet().to(self.torchdevice)
197
+ weights = torch.load('./models/DMDNet.pth')
198
+ model_dmdnet.load_state_dict(weights, strict=True)
199
+
200
+ model_dmdnet.eval()
201
+ num_params = 0
202
+ for param in model_dmdnet.parameters():
203
+ num_params += param.numel()
204
+ return model_dmdnet
205
+
206
+ # print('{:>8s} : {}'.format('Using device', device))
207
+ # print('{:>8s} : {:.2f}M'.format('Model params', num_params/1e6))
208
+
209
+
210
+
211
+ def read_img_tensor(Img=None): #rgb -1~1
212
+ Img = Img.transpose((2, 0, 1))/255.0
213
+ Img = torch.from_numpy(Img).float()
214
+ normalize(Img, [0.5,0.5,0.5], [0.5,0.5,0.5], inplace=True)
215
+ ImgTensor = Img.unsqueeze(0)
216
+ return ImgTensor
217
+
218
+
219
+ def get_component_location(Landmarks, re_read=False):
220
+ if re_read:
221
+ ReadLandmark = []
222
+ with open(Landmarks,'r') as f:
223
+ for line in f:
224
+ tmp = [float(i) for i in line.split(' ') if i != '\n']
225
+ ReadLandmark.append(tmp)
226
+ ReadLandmark = np.array(ReadLandmark) #
227
+ Landmarks = np.reshape(ReadLandmark, [-1, 2]) # 68*2
228
+ Map_LE_B = list(np.hstack((range(17,22), range(36,42))))
229
+ Map_RE_B = list(np.hstack((range(22,27), range(42,48))))
230
+ Map_LE = list(range(36,42))
231
+ Map_RE = list(range(42,48))
232
+ Map_NO = list(range(29,36))
233
+ Map_MO = list(range(48,68))
234
+
235
+ Landmarks[Landmarks>504]=504
236
+ Landmarks[Landmarks<8]=8
237
+
238
+ #left eye
239
+ Mean_LE = np.mean(Landmarks[Map_LE],0)
240
+ L_LE1 = Mean_LE[1] - np.min(Landmarks[Map_LE_B,1])
241
+ L_LE1 = L_LE1 * 1.3
242
+ L_LE2 = L_LE1 / 1.9
243
+ L_LE_xy = L_LE1 + L_LE2
244
+ L_LE_lt = [L_LE_xy/2, L_LE1]
245
+ L_LE_rb = [L_LE_xy/2, L_LE2]
246
+ Location_LE = np.hstack((Mean_LE - L_LE_lt + 1, Mean_LE + L_LE_rb)).astype(int)
247
+
248
+ #right eye
249
+ Mean_RE = np.mean(Landmarks[Map_RE],0)
250
+ L_RE1 = Mean_RE[1] - np.min(Landmarks[Map_RE_B,1])
251
+ L_RE1 = L_RE1 * 1.3
252
+ L_RE2 = L_RE1 / 1.9
253
+ L_RE_xy = L_RE1 + L_RE2
254
+ L_RE_lt = [L_RE_xy/2, L_RE1]
255
+ L_RE_rb = [L_RE_xy/2, L_RE2]
256
+ Location_RE = np.hstack((Mean_RE - L_RE_lt + 1, Mean_RE + L_RE_rb)).astype(int)
257
+
258
+ #nose
259
+ Mean_NO = np.mean(Landmarks[Map_NO],0)
260
+ L_NO1 =( np.max([Mean_NO[0] - Landmarks[31][0], Landmarks[35][0] - Mean_NO[0]])) * 1.25
261
+ L_NO2 = (Landmarks[33][1] - Mean_NO[1]) * 1.1
262
+ L_NO_xy = L_NO1 * 2
263
+ L_NO_lt = [L_NO_xy/2, L_NO_xy - L_NO2]
264
+ L_NO_rb = [L_NO_xy/2, L_NO2]
265
+ Location_NO = np.hstack((Mean_NO - L_NO_lt + 1, Mean_NO + L_NO_rb)).astype(int)
266
+
267
+ #mouth
268
+ Mean_MO = np.mean(Landmarks[Map_MO],0)
269
+ L_MO = np.max((np.max(np.max(Landmarks[Map_MO],0) - np.min(Landmarks[Map_MO],0))/2,16)) * 1.1
270
+ MO_O = Mean_MO - L_MO + 1
271
+ MO_T = Mean_MO + L_MO
272
+ MO_T[MO_T>510]=510
273
+ Location_MO = np.hstack((MO_O, MO_T)).astype(int)
274
+ return torch.cat([torch.FloatTensor(Location_LE).unsqueeze(0), torch.FloatTensor(Location_RE).unsqueeze(0), torch.FloatTensor(Location_NO).unsqueeze(0), torch.FloatTensor(Location_MO).unsqueeze(0)], dim=0)
275
+
276
+
277
+
278
+
279
+ def calc_mean_std_4D(feat, eps=1e-5):
280
+ # eps is a small value added to the variance to avoid divide-by-zero.
281
+ size = feat.size()
282
+ assert (len(size) == 4)
283
+ N, C = size[:2]
284
+ feat_var = feat.view(N, C, -1).var(dim=2) + eps
285
+ feat_std = feat_var.sqrt().view(N, C, 1, 1)
286
+ feat_mean = feat.view(N, C, -1).mean(dim=2).view(N, C, 1, 1)
287
+ return feat_mean, feat_std
288
+
289
+ def adaptive_instance_normalization_4D(content_feat, style_feat): # content_feat is ref feature, style is degradate feature
290
+ size = content_feat.size()
291
+ style_mean, style_std = calc_mean_std_4D(style_feat)
292
+ content_mean, content_std = calc_mean_std_4D(content_feat)
293
+ normalized_feat = (content_feat - content_mean.expand(size)) / content_std.expand(size)
294
+ return normalized_feat * style_std.expand(size) + style_mean.expand(size)
295
+
296
+
297
+ def convU(in_channels, out_channels,conv_layer, norm_layer, kernel_size=3, stride=1,dilation=1, bias=True):
298
+ return nn.Sequential(
299
+ SpectralNorm(conv_layer(in_channels, out_channels, kernel_size=kernel_size, stride=stride, dilation=dilation, padding=((kernel_size-1)//2)*dilation, bias=bias)),
300
+ nn.LeakyReLU(0.2),
301
+ SpectralNorm(conv_layer(out_channels, out_channels, kernel_size=kernel_size, stride=stride, dilation=dilation, padding=((kernel_size-1)//2)*dilation, bias=bias)),
302
+ )
303
+
304
+
305
+ class MSDilateBlock(nn.Module):
306
+ def __init__(self, in_channels,conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, kernel_size=3, dilation=[1,1,1,1], bias=True):
307
+ super(MSDilateBlock, self).__init__()
308
+ self.conv1 = convU(in_channels, in_channels,conv_layer, norm_layer, kernel_size,dilation=dilation[0], bias=bias)
309
+ self.conv2 = convU(in_channels, in_channels,conv_layer, norm_layer, kernel_size,dilation=dilation[1], bias=bias)
310
+ self.conv3 = convU(in_channels, in_channels,conv_layer, norm_layer, kernel_size,dilation=dilation[2], bias=bias)
311
+ self.conv4 = convU(in_channels, in_channels,conv_layer, norm_layer, kernel_size,dilation=dilation[3], bias=bias)
312
+ self.convi = SpectralNorm(conv_layer(in_channels*4, in_channels, kernel_size=kernel_size, stride=1, padding=(kernel_size-1)//2, bias=bias))
313
+ def forward(self, x):
314
+ conv1 = self.conv1(x)
315
+ conv2 = self.conv2(x)
316
+ conv3 = self.conv3(x)
317
+ conv4 = self.conv4(x)
318
+ cat = torch.cat([conv1, conv2, conv3, conv4], 1)
319
+ out = self.convi(cat) + x
320
+ return out
321
+
322
+
323
+ class AdaptiveInstanceNorm(nn.Module):
324
+ def __init__(self, in_channel):
325
+ super().__init__()
326
+ self.norm = nn.InstanceNorm2d(in_channel)
327
+
328
+ def forward(self, input, style):
329
+ style_mean, style_std = calc_mean_std_4D(style)
330
+ out = self.norm(input)
331
+ size = input.size()
332
+ out = style_std.expand(size) * out + style_mean.expand(size)
333
+ return out
334
+
335
+ class NoiseInjection(nn.Module):
336
+ def __init__(self, channel):
337
+ super().__init__()
338
+ self.weight = nn.Parameter(torch.zeros(1, channel, 1, 1))
339
+ def forward(self, image, noise):
340
+ if noise is None:
341
+ b, c, h, w = image.shape
342
+ noise = image.new_empty(b, 1, h, w).normal_()
343
+ return image + self.weight * noise
344
+
345
+ class StyledUpBlock(nn.Module):
346
+ def __init__(self, in_channel, out_channel, kernel_size=3, padding=1,upsample=False, noise_inject=False):
347
+ super().__init__()
348
+
349
+ self.noise_inject = noise_inject
350
+ if upsample:
351
+ self.conv1 = nn.Sequential(
352
+ nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
353
+ SpectralNorm(nn.Conv2d(in_channel, out_channel, kernel_size, padding=padding)),
354
+ nn.LeakyReLU(0.2),
355
+ )
356
+ else:
357
+ self.conv1 = nn.Sequential(
358
+ SpectralNorm(nn.Conv2d(in_channel, out_channel, kernel_size, padding=padding)),
359
+ nn.LeakyReLU(0.2),
360
+ SpectralNorm(nn.Conv2d(out_channel, out_channel, kernel_size, padding=padding)),
361
+ )
362
+ self.convup = nn.Sequential(
363
+ nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
364
+ SpectralNorm(nn.Conv2d(out_channel, out_channel, kernel_size, padding=padding)),
365
+ nn.LeakyReLU(0.2),
366
+ SpectralNorm(nn.Conv2d(out_channel, out_channel, kernel_size, padding=padding)),
367
+ )
368
+ if self.noise_inject:
369
+ self.noise1 = NoiseInjection(out_channel)
370
+
371
+ self.lrelu1 = nn.LeakyReLU(0.2)
372
+
373
+ self.ScaleModel1 = nn.Sequential(
374
+ SpectralNorm(nn.Conv2d(in_channel,out_channel,3, 1, 1)),
375
+ nn.LeakyReLU(0.2),
376
+ SpectralNorm(nn.Conv2d(out_channel, out_channel, 3, 1, 1))
377
+ )
378
+ self.ShiftModel1 = nn.Sequential(
379
+ SpectralNorm(nn.Conv2d(in_channel,out_channel,3, 1, 1)),
380
+ nn.LeakyReLU(0.2),
381
+ SpectralNorm(nn.Conv2d(out_channel, out_channel, 3, 1, 1)),
382
+ )
383
+
384
+ def forward(self, input, style):
385
+ out = self.conv1(input)
386
+ out = self.lrelu1(out)
387
+ Shift1 = self.ShiftModel1(style)
388
+ Scale1 = self.ScaleModel1(style)
389
+ out = out * Scale1 + Shift1
390
+ if self.noise_inject:
391
+ out = self.noise1(out, noise=None)
392
+ outup = self.convup(out)
393
+ return outup
394
+
395
+
396
+ ####################################################################
397
+ ###############Face Dictionary Generator
398
+ ####################################################################
399
+ def AttentionBlock(in_channel):
400
+ return nn.Sequential(
401
+ SpectralNorm(nn.Conv2d(in_channel, in_channel, 3, 1, 1)),
402
+ nn.LeakyReLU(0.2),
403
+ SpectralNorm(nn.Conv2d(in_channel, in_channel, 3, 1, 1)),
404
+ )
405
+
406
+ class DilateResBlock(nn.Module):
407
+ def __init__(self, dim, dilation=[5,3] ):
408
+ super(DilateResBlock, self).__init__()
409
+ self.Res = nn.Sequential(
410
+ SpectralNorm(nn.Conv2d(dim, dim, 3, 1, ((3-1)//2)*dilation[0], dilation[0])),
411
+ nn.LeakyReLU(0.2),
412
+ SpectralNorm(nn.Conv2d(dim, dim, 3, 1, ((3-1)//2)*dilation[1], dilation[1])),
413
+ )
414
+ def forward(self, x):
415
+ out = x + self.Res(x)
416
+ return out
417
+
418
+
419
+ class KeyValue(nn.Module):
420
+ def __init__(self, indim, keydim, valdim):
421
+ super(KeyValue, self).__init__()
422
+ self.Key = nn.Sequential(
423
+ SpectralNorm(nn.Conv2d(indim, keydim, kernel_size=(3,3), padding=(1,1), stride=1)),
424
+ nn.LeakyReLU(0.2),
425
+ SpectralNorm(nn.Conv2d(keydim, keydim, kernel_size=(3,3), padding=(1,1), stride=1)),
426
+ )
427
+ self.Value = nn.Sequential(
428
+ SpectralNorm(nn.Conv2d(indim, valdim, kernel_size=(3,3), padding=(1,1), stride=1)),
429
+ nn.LeakyReLU(0.2),
430
+ SpectralNorm(nn.Conv2d(valdim, valdim, kernel_size=(3,3), padding=(1,1), stride=1)),
431
+ )
432
+ def forward(self, x):
433
+ return self.Key(x), self.Value(x)
434
+
435
+ class MaskAttention(nn.Module):
436
+ def __init__(self, indim):
437
+ super(MaskAttention, self).__init__()
438
+ self.conv1 = nn.Sequential(
439
+ SpectralNorm(nn.Conv2d(indim, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
440
+ nn.LeakyReLU(0.2),
441
+ SpectralNorm(nn.Conv2d(indim//3, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
442
+ )
443
+ self.conv2 = nn.Sequential(
444
+ SpectralNorm(nn.Conv2d(indim, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
445
+ nn.LeakyReLU(0.2),
446
+ SpectralNorm(nn.Conv2d(indim//3, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
447
+ )
448
+ self.conv3 = nn.Sequential(
449
+ SpectralNorm(nn.Conv2d(indim, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
450
+ nn.LeakyReLU(0.2),
451
+ SpectralNorm(nn.Conv2d(indim//3, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
452
+ )
453
+ self.convCat = nn.Sequential(
454
+ SpectralNorm(nn.Conv2d(indim//3 * 3, indim, kernel_size=(3,3), padding=(1,1), stride=1)),
455
+ nn.LeakyReLU(0.2),
456
+ SpectralNorm(nn.Conv2d(indim, indim, kernel_size=(3,3), padding=(1,1), stride=1)),
457
+ )
458
+ def forward(self, x, y, z):
459
+ c1 = self.conv1(x)
460
+ c2 = self.conv2(y)
461
+ c3 = self.conv3(z)
462
+ return self.convCat(torch.cat([c1,c2,c3], dim=1))
463
+
464
+ class Query(nn.Module):
465
+ def __init__(self, indim, quedim):
466
+ super(Query, self).__init__()
467
+ self.Query = nn.Sequential(
468
+ SpectralNorm(nn.Conv2d(indim, quedim, kernel_size=(3,3), padding=(1,1), stride=1)),
469
+ nn.LeakyReLU(0.2),
470
+ SpectralNorm(nn.Conv2d(quedim, quedim, kernel_size=(3,3), padding=(1,1), stride=1)),
471
+ )
472
+ def forward(self, x):
473
+ return self.Query(x)
474
+
475
+ def roi_align_self(input, location, target_size):
476
+ test = (target_size.item(),target_size.item())
477
+ return torch.cat([F.interpolate(input[i:i+1,:,location[i,1]:location[i,3],location[i,0]:location[i,2]],test,mode='bilinear',align_corners=False) for i in range(input.size(0))],0)
478
+
479
+ class FeatureExtractor(nn.Module):
480
+ def __init__(self, ngf = 64, key_scale = 4):#
481
+ super().__init__()
482
+
483
+ self.key_scale = 4
484
+ self.part_sizes = np.array([80,80,50,110]) #
485
+ self.feature_sizes = np.array([256,128,64]) #
486
+
487
+ self.conv1 = nn.Sequential(
488
+ SpectralNorm(nn.Conv2d(3, ngf, 3, 2, 1)),
489
+ nn.LeakyReLU(0.2),
490
+ SpectralNorm(nn.Conv2d(ngf, ngf, 3, 1, 1)),
491
+ )
492
+ self.conv2 = nn.Sequential(
493
+ SpectralNorm(nn.Conv2d(ngf, ngf, 3, 1, 1)),
494
+ nn.LeakyReLU(0.2),
495
+ SpectralNorm(nn.Conv2d(ngf, ngf, 3, 1, 1))
496
+ )
497
+ self.res1 = DilateResBlock(ngf, [5,3])
498
+ self.res2 = DilateResBlock(ngf, [5,3])
499
+
500
+
501
+ self.conv3 = nn.Sequential(
502
+ SpectralNorm(nn.Conv2d(ngf, ngf*2, 3, 2, 1)),
503
+ nn.LeakyReLU(0.2),
504
+ SpectralNorm(nn.Conv2d(ngf*2, ngf*2, 3, 1, 1)),
505
+ )
506
+ self.conv4 = nn.Sequential(
507
+ SpectralNorm(nn.Conv2d(ngf*2, ngf*2, 3, 1, 1)),
508
+ nn.LeakyReLU(0.2),
509
+ SpectralNorm(nn.Conv2d(ngf*2, ngf*2, 3, 1, 1))
510
+ )
511
+ self.res3 = DilateResBlock(ngf*2, [3,1])
512
+ self.res4 = DilateResBlock(ngf*2, [3,1])
513
+
514
+ self.conv5 = nn.Sequential(
515
+ SpectralNorm(nn.Conv2d(ngf*2, ngf*4, 3, 2, 1)),
516
+ nn.LeakyReLU(0.2),
517
+ SpectralNorm(nn.Conv2d(ngf*4, ngf*4, 3, 1, 1)),
518
+ )
519
+ self.conv6 = nn.Sequential(
520
+ SpectralNorm(nn.Conv2d(ngf*4, ngf*4, 3, 1, 1)),
521
+ nn.LeakyReLU(0.2),
522
+ SpectralNorm(nn.Conv2d(ngf*4, ngf*4, 3, 1, 1))
523
+ )
524
+ self.res5 = DilateResBlock(ngf*4, [1,1])
525
+ self.res6 = DilateResBlock(ngf*4, [1,1])
526
+
527
+ self.LE_256_Q = Query(ngf, ngf // self.key_scale)
528
+ self.RE_256_Q = Query(ngf, ngf // self.key_scale)
529
+ self.MO_256_Q = Query(ngf, ngf // self.key_scale)
530
+ self.LE_128_Q = Query(ngf * 2, ngf * 2 // self.key_scale)
531
+ self.RE_128_Q = Query(ngf * 2, ngf * 2 // self.key_scale)
532
+ self.MO_128_Q = Query(ngf * 2, ngf * 2 // self.key_scale)
533
+ self.LE_64_Q = Query(ngf * 4, ngf * 4 // self.key_scale)
534
+ self.RE_64_Q = Query(ngf * 4, ngf * 4 // self.key_scale)
535
+ self.MO_64_Q = Query(ngf * 4, ngf * 4 // self.key_scale)
536
+
537
+
538
+ def forward(self, img, locs):
539
+ le_location = locs[:,0,:].int().cpu().numpy()
540
+ re_location = locs[:,1,:].int().cpu().numpy()
541
+ no_location = locs[:,2,:].int().cpu().numpy()
542
+ mo_location = locs[:,3,:].int().cpu().numpy()
543
+
544
+
545
+ f1_0 = self.conv1(img)
546
+ f1_1 = self.res1(f1_0)
547
+ f2_0 = self.conv2(f1_1)
548
+ f2_1 = self.res2(f2_0)
549
+
550
+ f3_0 = self.conv3(f2_1)
551
+ f3_1 = self.res3(f3_0)
552
+ f4_0 = self.conv4(f3_1)
553
+ f4_1 = self.res4(f4_0)
554
+
555
+ f5_0 = self.conv5(f4_1)
556
+ f5_1 = self.res5(f5_0)
557
+ f6_0 = self.conv6(f5_1)
558
+ f6_1 = self.res6(f6_0)
559
+
560
+
561
+ ####ROI Align
562
+ le_part_256 = roi_align_self(f2_1.clone(), le_location//2, self.part_sizes[0]//2)
563
+ re_part_256 = roi_align_self(f2_1.clone(), re_location//2, self.part_sizes[1]//2)
564
+ mo_part_256 = roi_align_self(f2_1.clone(), mo_location//2, self.part_sizes[3]//2)
565
+
566
+ le_part_128 = roi_align_self(f4_1.clone(), le_location//4, self.part_sizes[0]//4)
567
+ re_part_128 = roi_align_self(f4_1.clone(), re_location//4, self.part_sizes[1]//4)
568
+ mo_part_128 = roi_align_self(f4_1.clone(), mo_location//4, self.part_sizes[3]//4)
569
+
570
+ le_part_64 = roi_align_self(f6_1.clone(), le_location//8, self.part_sizes[0]//8)
571
+ re_part_64 = roi_align_self(f6_1.clone(), re_location//8, self.part_sizes[1]//8)
572
+ mo_part_64 = roi_align_self(f6_1.clone(), mo_location//8, self.part_sizes[3]//8)
573
+
574
+
575
+ le_256_q = self.LE_256_Q(le_part_256)
576
+ re_256_q = self.RE_256_Q(re_part_256)
577
+ mo_256_q = self.MO_256_Q(mo_part_256)
578
+
579
+ le_128_q = self.LE_128_Q(le_part_128)
580
+ re_128_q = self.RE_128_Q(re_part_128)
581
+ mo_128_q = self.MO_128_Q(mo_part_128)
582
+
583
+ le_64_q = self.LE_64_Q(le_part_64)
584
+ re_64_q = self.RE_64_Q(re_part_64)
585
+ mo_64_q = self.MO_64_Q(mo_part_64)
586
+
587
+ return {'f256': f2_1, 'f128': f4_1, 'f64': f6_1,\
588
+ 'le256': le_part_256, 're256': re_part_256, 'mo256': mo_part_256, \
589
+ 'le128': le_part_128, 're128': re_part_128, 'mo128': mo_part_128, \
590
+ 'le64': le_part_64, 're64': re_part_64, 'mo64': mo_part_64, \
591
+ 'le_256_q': le_256_q, 're_256_q': re_256_q, 'mo_256_q': mo_256_q,\
592
+ 'le_128_q': le_128_q, 're_128_q': re_128_q, 'mo_128_q': mo_128_q,\
593
+ 'le_64_q': le_64_q, 're_64_q': re_64_q, 'mo_64_q': mo_64_q}
594
+
595
+
596
+ class DMDNet(nn.Module):
597
+ def __init__(self, ngf = 64, banks_num = 128):
598
+ super().__init__()
599
+ self.part_sizes = np.array([80,80,50,110]) # size for 512
600
+ self.feature_sizes = np.array([256,128,64]) # size for 512
601
+
602
+ self.banks_num = banks_num
603
+ self.key_scale = 4
604
+
605
+ self.E_lq = FeatureExtractor(key_scale = self.key_scale)
606
+ self.E_hq = FeatureExtractor(key_scale = self.key_scale)
607
+
608
+ self.LE_256_KV = KeyValue(ngf, ngf // self.key_scale, ngf)
609
+ self.RE_256_KV = KeyValue(ngf, ngf // self.key_scale, ngf)
610
+ self.MO_256_KV = KeyValue(ngf, ngf // self.key_scale, ngf)
611
+
612
+ self.LE_128_KV = KeyValue(ngf * 2 , ngf * 2 // self.key_scale, ngf * 2)
613
+ self.RE_128_KV = KeyValue(ngf * 2 , ngf * 2 // self.key_scale, ngf * 2)
614
+ self.MO_128_KV = KeyValue(ngf * 2 , ngf * 2 // self.key_scale, ngf * 2)
615
+
616
+ self.LE_64_KV = KeyValue(ngf * 4 , ngf * 4 // self.key_scale, ngf * 4)
617
+ self.RE_64_KV = KeyValue(ngf * 4 , ngf * 4 // self.key_scale, ngf * 4)
618
+ self.MO_64_KV = KeyValue(ngf * 4 , ngf * 4 // self.key_scale, ngf * 4)
619
+
620
+
621
+ self.LE_256_Attention = AttentionBlock(64)
622
+ self.RE_256_Attention = AttentionBlock(64)
623
+ self.MO_256_Attention = AttentionBlock(64)
624
+
625
+ self.LE_128_Attention = AttentionBlock(128)
626
+ self.RE_128_Attention = AttentionBlock(128)
627
+ self.MO_128_Attention = AttentionBlock(128)
628
+
629
+ self.LE_64_Attention = AttentionBlock(256)
630
+ self.RE_64_Attention = AttentionBlock(256)
631
+ self.MO_64_Attention = AttentionBlock(256)
632
+
633
+ self.LE_256_Mask = MaskAttention(64)
634
+ self.RE_256_Mask = MaskAttention(64)
635
+ self.MO_256_Mask = MaskAttention(64)
636
+
637
+ self.LE_128_Mask = MaskAttention(128)
638
+ self.RE_128_Mask = MaskAttention(128)
639
+ self.MO_128_Mask = MaskAttention(128)
640
+
641
+ self.LE_64_Mask = MaskAttention(256)
642
+ self.RE_64_Mask = MaskAttention(256)
643
+ self.MO_64_Mask = MaskAttention(256)
644
+
645
+ self.MSDilate = MSDilateBlock(ngf*4, dilation = [4,3,2,1])
646
+
647
+ self.up1 = StyledUpBlock(ngf*4, ngf*2, noise_inject=False) #
648
+ self.up2 = StyledUpBlock(ngf*2, ngf, noise_inject=False) #
649
+ self.up3 = StyledUpBlock(ngf, ngf, noise_inject=False) #
650
+ self.up4 = nn.Sequential(
651
+ SpectralNorm(nn.Conv2d(ngf, ngf, 3, 1, 1)),
652
+ nn.LeakyReLU(0.2),
653
+ UpResBlock(ngf),
654
+ UpResBlock(ngf),
655
+ SpectralNorm(nn.Conv2d(ngf, 3, kernel_size=3, stride=1, padding=1)),
656
+ nn.Tanh()
657
+ )
658
+
659
+ # define generic memory, revise register_buffer to register_parameter for backward update
660
+ self.register_buffer('le_256_mem_key', torch.randn(128,16,40,40))
661
+ self.register_buffer('re_256_mem_key', torch.randn(128,16,40,40))
662
+ self.register_buffer('mo_256_mem_key', torch.randn(128,16,55,55))
663
+ self.register_buffer('le_256_mem_value', torch.randn(128,64,40,40))
664
+ self.register_buffer('re_256_mem_value', torch.randn(128,64,40,40))
665
+ self.register_buffer('mo_256_mem_value', torch.randn(128,64,55,55))
666
+
667
+
668
+ self.register_buffer('le_128_mem_key', torch.randn(128,32,20,20))
669
+ self.register_buffer('re_128_mem_key', torch.randn(128,32,20,20))
670
+ self.register_buffer('mo_128_mem_key', torch.randn(128,32,27,27))
671
+ self.register_buffer('le_128_mem_value', torch.randn(128,128,20,20))
672
+ self.register_buffer('re_128_mem_value', torch.randn(128,128,20,20))
673
+ self.register_buffer('mo_128_mem_value', torch.randn(128,128,27,27))
674
+
675
+ self.register_buffer('le_64_mem_key', torch.randn(128,64,10,10))
676
+ self.register_buffer('re_64_mem_key', torch.randn(128,64,10,10))
677
+ self.register_buffer('mo_64_mem_key', torch.randn(128,64,13,13))
678
+ self.register_buffer('le_64_mem_value', torch.randn(128,256,10,10))
679
+ self.register_buffer('re_64_mem_value', torch.randn(128,256,10,10))
680
+ self.register_buffer('mo_64_mem_value', torch.randn(128,256,13,13))
681
+
682
+
683
+ def readMem(self, k, v, q):
684
+ sim = F.conv2d(q, k)
685
+ score = F.softmax(sim/sqrt(sim.size(1)), dim=1) #B * S * 1 * 1 6*128
686
+ sb,sn,sw,sh = score.size()
687
+ s_m = score.view(sb, -1).unsqueeze(1)#2*1*M
688
+ vb,vn,vw,vh = v.size()
689
+ v_in = v.view(vb, -1).repeat(sb,1,1)#2*M*(c*w*h)
690
+ mem_out = torch.bmm(s_m, v_in).squeeze(1).view(sb, vn, vw,vh)
691
+ max_inds = torch.argmax(score, dim=1).squeeze()
692
+ return mem_out, max_inds
693
+
694
+
695
+ def memorize(self, img, locs):
696
+ fs = self.E_hq(img, locs)
697
+ LE256_key, LE256_value = self.LE_256_KV(fs['le256'])
698
+ RE256_key, RE256_value = self.RE_256_KV(fs['re256'])
699
+ MO256_key, MO256_value = self.MO_256_KV(fs['mo256'])
700
+
701
+ LE128_key, LE128_value = self.LE_128_KV(fs['le128'])
702
+ RE128_key, RE128_value = self.RE_128_KV(fs['re128'])
703
+ MO128_key, MO128_value = self.MO_128_KV(fs['mo128'])
704
+
705
+ LE64_key, LE64_value = self.LE_64_KV(fs['le64'])
706
+ RE64_key, RE64_value = self.RE_64_KV(fs['re64'])
707
+ MO64_key, MO64_value = self.MO_64_KV(fs['mo64'])
708
+
709
+ Mem256 = {'LE256Key': LE256_key, 'LE256Value': LE256_value, 'RE256Key': RE256_key, 'RE256Value': RE256_value,'MO256Key': MO256_key, 'MO256Value': MO256_value}
710
+ Mem128 = {'LE128Key': LE128_key, 'LE128Value': LE128_value, 'RE128Key': RE128_key, 'RE128Value': RE128_value,'MO128Key': MO128_key, 'MO128Value': MO128_value}
711
+ Mem64 = {'LE64Key': LE64_key, 'LE64Value': LE64_value, 'RE64Key': RE64_key, 'RE64Value': RE64_value,'MO64Key': MO64_key, 'MO64Value': MO64_value}
712
+
713
+ FS256 = {'LE256F':fs['le256'], 'RE256F':fs['re256'], 'MO256F':fs['mo256']}
714
+ FS128 = {'LE128F':fs['le128'], 'RE128F':fs['re128'], 'MO128F':fs['mo128']}
715
+ FS64 = {'LE64F':fs['le64'], 'RE64F':fs['re64'], 'MO64F':fs['mo64']}
716
+
717
+ return Mem256, Mem128, Mem64
718
+
719
+ def enhancer(self, fs_in, sp_256=None, sp_128=None, sp_64=None):
720
+ le_256_q = fs_in['le_256_q']
721
+ re_256_q = fs_in['re_256_q']
722
+ mo_256_q = fs_in['mo_256_q']
723
+
724
+ le_128_q = fs_in['le_128_q']
725
+ re_128_q = fs_in['re_128_q']
726
+ mo_128_q = fs_in['mo_128_q']
727
+
728
+ le_64_q = fs_in['le_64_q']
729
+ re_64_q = fs_in['re_64_q']
730
+ mo_64_q = fs_in['mo_64_q']
731
+
732
+
733
+ ####for 256
734
+ le_256_mem_g, le_256_inds = self.readMem(self.le_256_mem_key, self.le_256_mem_value, le_256_q)
735
+ re_256_mem_g, re_256_inds = self.readMem(self.re_256_mem_key, self.re_256_mem_value, re_256_q)
736
+ mo_256_mem_g, mo_256_inds = self.readMem(self.mo_256_mem_key, self.mo_256_mem_value, mo_256_q)
737
+
738
+ le_128_mem_g, le_128_inds = self.readMem(self.le_128_mem_key, self.le_128_mem_value, le_128_q)
739
+ re_128_mem_g, re_128_inds = self.readMem(self.re_128_mem_key, self.re_128_mem_value, re_128_q)
740
+ mo_128_mem_g, mo_128_inds = self.readMem(self.mo_128_mem_key, self.mo_128_mem_value, mo_128_q)
741
+
742
+ le_64_mem_g, le_64_inds = self.readMem(self.le_64_mem_key, self.le_64_mem_value, le_64_q)
743
+ re_64_mem_g, re_64_inds = self.readMem(self.re_64_mem_key, self.re_64_mem_value, re_64_q)
744
+ mo_64_mem_g, mo_64_inds = self.readMem(self.mo_64_mem_key, self.mo_64_mem_value, mo_64_q)
745
+
746
+ if sp_256 is not None and sp_128 is not None and sp_64 is not None:
747
+ le_256_mem_s, _ = self.readMem(sp_256['LE256Key'], sp_256['LE256Value'], le_256_q)
748
+ re_256_mem_s, _ = self.readMem(sp_256['RE256Key'], sp_256['RE256Value'], re_256_q)
749
+ mo_256_mem_s, _ = self.readMem(sp_256['MO256Key'], sp_256['MO256Value'], mo_256_q)
750
+ le_256_mask = self.LE_256_Mask(fs_in['le256'],le_256_mem_s,le_256_mem_g)
751
+ le_256_mem = le_256_mask*le_256_mem_s + (1-le_256_mask)*le_256_mem_g
752
+ re_256_mask = self.RE_256_Mask(fs_in['re256'],re_256_mem_s,re_256_mem_g)
753
+ re_256_mem = re_256_mask*re_256_mem_s + (1-re_256_mask)*re_256_mem_g
754
+ mo_256_mask = self.MO_256_Mask(fs_in['mo256'],mo_256_mem_s,mo_256_mem_g)
755
+ mo_256_mem = mo_256_mask*mo_256_mem_s + (1-mo_256_mask)*mo_256_mem_g
756
+
757
+ le_128_mem_s, _ = self.readMem(sp_128['LE128Key'], sp_128['LE128Value'], le_128_q)
758
+ re_128_mem_s, _ = self.readMem(sp_128['RE128Key'], sp_128['RE128Value'], re_128_q)
759
+ mo_128_mem_s, _ = self.readMem(sp_128['MO128Key'], sp_128['MO128Value'], mo_128_q)
760
+ le_128_mask = self.LE_128_Mask(fs_in['le128'],le_128_mem_s,le_128_mem_g)
761
+ le_128_mem = le_128_mask*le_128_mem_s + (1-le_128_mask)*le_128_mem_g
762
+ re_128_mask = self.RE_128_Mask(fs_in['re128'],re_128_mem_s,re_128_mem_g)
763
+ re_128_mem = re_128_mask*re_128_mem_s + (1-re_128_mask)*re_128_mem_g
764
+ mo_128_mask = self.MO_128_Mask(fs_in['mo128'],mo_128_mem_s,mo_128_mem_g)
765
+ mo_128_mem = mo_128_mask*mo_128_mem_s + (1-mo_128_mask)*mo_128_mem_g
766
+
767
+ le_64_mem_s, _ = self.readMem(sp_64['LE64Key'], sp_64['LE64Value'], le_64_q)
768
+ re_64_mem_s, _ = self.readMem(sp_64['RE64Key'], sp_64['RE64Value'], re_64_q)
769
+ mo_64_mem_s, _ = self.readMem(sp_64['MO64Key'], sp_64['MO64Value'], mo_64_q)
770
+ le_64_mask = self.LE_64_Mask(fs_in['le64'],le_64_mem_s,le_64_mem_g)
771
+ le_64_mem = le_64_mask*le_64_mem_s + (1-le_64_mask)*le_64_mem_g
772
+ re_64_mask = self.RE_64_Mask(fs_in['re64'],re_64_mem_s,re_64_mem_g)
773
+ re_64_mem = re_64_mask*re_64_mem_s + (1-re_64_mask)*re_64_mem_g
774
+ mo_64_mask = self.MO_64_Mask(fs_in['mo64'],mo_64_mem_s,mo_64_mem_g)
775
+ mo_64_mem = mo_64_mask*mo_64_mem_s + (1-mo_64_mask)*mo_64_mem_g
776
+ else:
777
+ le_256_mem = le_256_mem_g
778
+ re_256_mem = re_256_mem_g
779
+ mo_256_mem = mo_256_mem_g
780
+ le_128_mem = le_128_mem_g
781
+ re_128_mem = re_128_mem_g
782
+ mo_128_mem = mo_128_mem_g
783
+ le_64_mem = le_64_mem_g
784
+ re_64_mem = re_64_mem_g
785
+ mo_64_mem = mo_64_mem_g
786
+
787
+ le_256_mem_norm = adaptive_instance_normalization_4D(le_256_mem, fs_in['le256'])
788
+ re_256_mem_norm = adaptive_instance_normalization_4D(re_256_mem, fs_in['re256'])
789
+ mo_256_mem_norm = adaptive_instance_normalization_4D(mo_256_mem, fs_in['mo256'])
790
+
791
+ ####for 128
792
+ le_128_mem_norm = adaptive_instance_normalization_4D(le_128_mem, fs_in['le128'])
793
+ re_128_mem_norm = adaptive_instance_normalization_4D(re_128_mem, fs_in['re128'])
794
+ mo_128_mem_norm = adaptive_instance_normalization_4D(mo_128_mem, fs_in['mo128'])
795
+
796
+ ####for 64
797
+ le_64_mem_norm = adaptive_instance_normalization_4D(le_64_mem, fs_in['le64'])
798
+ re_64_mem_norm = adaptive_instance_normalization_4D(re_64_mem, fs_in['re64'])
799
+ mo_64_mem_norm = adaptive_instance_normalization_4D(mo_64_mem, fs_in['mo64'])
800
+
801
+
802
+ EnMem256 = {'LE256Norm': le_256_mem_norm, 'RE256Norm': re_256_mem_norm, 'MO256Norm': mo_256_mem_norm}
803
+ EnMem128 = {'LE128Norm': le_128_mem_norm, 'RE128Norm': re_128_mem_norm, 'MO128Norm': mo_128_mem_norm}
804
+ EnMem64 = {'LE64Norm': le_64_mem_norm, 'RE64Norm': re_64_mem_norm, 'MO64Norm': mo_64_mem_norm}
805
+ Ind256 = {'LE': le_256_inds, 'RE': re_256_inds, 'MO': mo_256_inds}
806
+ Ind128 = {'LE': le_128_inds, 'RE': re_128_inds, 'MO': mo_128_inds}
807
+ Ind64 = {'LE': le_64_inds, 'RE': re_64_inds, 'MO': mo_64_inds}
808
+ return EnMem256, EnMem128, EnMem64, Ind256, Ind128, Ind64
809
+
810
+ def reconstruct(self, fs_in, locs, memstar):
811
+ le_256_mem_norm, re_256_mem_norm, mo_256_mem_norm = memstar[0]['LE256Norm'], memstar[0]['RE256Norm'], memstar[0]['MO256Norm']
812
+ le_128_mem_norm, re_128_mem_norm, mo_128_mem_norm = memstar[1]['LE128Norm'], memstar[1]['RE128Norm'], memstar[1]['MO128Norm']
813
+ le_64_mem_norm, re_64_mem_norm, mo_64_mem_norm = memstar[2]['LE64Norm'], memstar[2]['RE64Norm'], memstar[2]['MO64Norm']
814
+
815
+ le_256_final = self.LE_256_Attention(le_256_mem_norm - fs_in['le256']) * le_256_mem_norm + fs_in['le256']
816
+ re_256_final = self.RE_256_Attention(re_256_mem_norm - fs_in['re256']) * re_256_mem_norm + fs_in['re256']
817
+ mo_256_final = self.MO_256_Attention(mo_256_mem_norm - fs_in['mo256']) * mo_256_mem_norm + fs_in['mo256']
818
+
819
+ le_128_final = self.LE_128_Attention(le_128_mem_norm - fs_in['le128']) * le_128_mem_norm + fs_in['le128']
820
+ re_128_final = self.RE_128_Attention(re_128_mem_norm - fs_in['re128']) * re_128_mem_norm + fs_in['re128']
821
+ mo_128_final = self.MO_128_Attention(mo_128_mem_norm - fs_in['mo128']) * mo_128_mem_norm + fs_in['mo128']
822
+
823
+ le_64_final = self.LE_64_Attention(le_64_mem_norm - fs_in['le64']) * le_64_mem_norm + fs_in['le64']
824
+ re_64_final = self.RE_64_Attention(re_64_mem_norm - fs_in['re64']) * re_64_mem_norm + fs_in['re64']
825
+ mo_64_final = self.MO_64_Attention(mo_64_mem_norm - fs_in['mo64']) * mo_64_mem_norm + fs_in['mo64']
826
+
827
+
828
+ le_location = locs[:,0,:]
829
+ re_location = locs[:,1,:]
830
+ mo_location = locs[:,3,:]
831
+
832
+ # Somehow with latest Torch it doesn't like numpy wrappers anymore
833
+
834
+ # le_location = le_location.cpu().int().numpy()
835
+ # re_location = re_location.cpu().int().numpy()
836
+ # mo_location = mo_location.cpu().int().numpy()
837
+ le_location = le_location.cpu().int()
838
+ re_location = re_location.cpu().int()
839
+ mo_location = mo_location.cpu().int()
840
+
841
+ up_in_256 = fs_in['f256'].clone()# * 0
842
+ up_in_128 = fs_in['f128'].clone()# * 0
843
+ up_in_64 = fs_in['f64'].clone()# * 0
844
+
845
+ for i in range(fs_in['f256'].size(0)):
846
+ up_in_256[i:i+1,:,le_location[i,1]//2:le_location[i,3]//2,le_location[i,0]//2:le_location[i,2]//2] = F.interpolate(le_256_final[i:i+1,:,:,:].clone(), (le_location[i,3]//2-le_location[i,1]//2,le_location[i,2]//2-le_location[i,0]//2),mode='bilinear',align_corners=False)
847
+ up_in_256[i:i+1,:,re_location[i,1]//2:re_location[i,3]//2,re_location[i,0]//2:re_location[i,2]//2] = F.interpolate(re_256_final[i:i+1,:,:,:].clone(), (re_location[i,3]//2-re_location[i,1]//2,re_location[i,2]//2-re_location[i,0]//2),mode='bilinear',align_corners=False)
848
+ up_in_256[i:i+1,:,mo_location[i,1]//2:mo_location[i,3]//2,mo_location[i,0]//2:mo_location[i,2]//2] = F.interpolate(mo_256_final[i:i+1,:,:,:].clone(), (mo_location[i,3]//2-mo_location[i,1]//2,mo_location[i,2]//2-mo_location[i,0]//2),mode='bilinear',align_corners=False)
849
+
850
+ up_in_128[i:i+1,:,le_location[i,1]//4:le_location[i,3]//4,le_location[i,0]//4:le_location[i,2]//4] = F.interpolate(le_128_final[i:i+1,:,:,:].clone(), (le_location[i,3]//4-le_location[i,1]//4,le_location[i,2]//4-le_location[i,0]//4),mode='bilinear',align_corners=False)
851
+ up_in_128[i:i+1,:,re_location[i,1]//4:re_location[i,3]//4,re_location[i,0]//4:re_location[i,2]//4] = F.interpolate(re_128_final[i:i+1,:,:,:].clone(), (re_location[i,3]//4-re_location[i,1]//4,re_location[i,2]//4-re_location[i,0]//4),mode='bilinear',align_corners=False)
852
+ up_in_128[i:i+1,:,mo_location[i,1]//4:mo_location[i,3]//4,mo_location[i,0]//4:mo_location[i,2]//4] = F.interpolate(mo_128_final[i:i+1,:,:,:].clone(), (mo_location[i,3]//4-mo_location[i,1]//4,mo_location[i,2]//4-mo_location[i,0]//4),mode='bilinear',align_corners=False)
853
+
854
+ up_in_64[i:i+1,:,le_location[i,1]//8:le_location[i,3]//8,le_location[i,0]//8:le_location[i,2]//8] = F.interpolate(le_64_final[i:i+1,:,:,:].clone(), (le_location[i,3]//8-le_location[i,1]//8,le_location[i,2]//8-le_location[i,0]//8),mode='bilinear',align_corners=False)
855
+ up_in_64[i:i+1,:,re_location[i,1]//8:re_location[i,3]//8,re_location[i,0]//8:re_location[i,2]//8] = F.interpolate(re_64_final[i:i+1,:,:,:].clone(), (re_location[i,3]//8-re_location[i,1]//8,re_location[i,2]//8-re_location[i,0]//8),mode='bilinear',align_corners=False)
856
+ up_in_64[i:i+1,:,mo_location[i,1]//8:mo_location[i,3]//8,mo_location[i,0]//8:mo_location[i,2]//8] = F.interpolate(mo_64_final[i:i+1,:,:,:].clone(), (mo_location[i,3]//8-mo_location[i,1]//8,mo_location[i,2]//8-mo_location[i,0]//8),mode='bilinear',align_corners=False)
857
+
858
+ ms_in_64 = self.MSDilate(fs_in['f64'].clone())
859
+ fea_up1 = self.up1(ms_in_64, up_in_64)
860
+ fea_up2 = self.up2(fea_up1, up_in_128) #
861
+ fea_up3 = self.up3(fea_up2, up_in_256) #
862
+ output = self.up4(fea_up3) #
863
+ return output
864
+
865
+ def generate_specific_dictionary(self, sp_imgs=None, sp_locs=None):
866
+ return self.memorize(sp_imgs, sp_locs)
867
+
868
+ def forward(self, lq=None, loc=None, sp_256 = None, sp_128 = None, sp_64 = None):
869
+ try:
870
+ fs_in = self.E_lq(lq, loc) # low quality images
871
+ except Exception as e:
872
+ print(e)
873
+
874
+ GeMemNorm256, GeMemNorm128, GeMemNorm64, Ind256, Ind128, Ind64 = self.enhancer(fs_in)
875
+ GeOut = self.reconstruct(fs_in, loc, memstar = [GeMemNorm256, GeMemNorm128, GeMemNorm64])
876
+ if sp_256 is not None and sp_128 is not None and sp_64 is not None:
877
+ GSMemNorm256, GSMemNorm128, GSMemNorm64, _, _, _ = self.enhancer(fs_in, sp_256, sp_128, sp_64)
878
+ GSOut = self.reconstruct(fs_in, loc, memstar = [GSMemNorm256, GSMemNorm128, GSMemNorm64])
879
+ else:
880
+ GSOut = None
881
+ return GeOut, GSOut
882
+
883
+ class UpResBlock(nn.Module):
884
+ def __init__(self, dim, conv_layer = nn.Conv2d, norm_layer = nn.BatchNorm2d):
885
+ super(UpResBlock, self).__init__()
886
+ self.Model = nn.Sequential(
887
+ SpectralNorm(conv_layer(dim, dim, 3, 1, 1)),
888
+ nn.LeakyReLU(0.2),
889
+ SpectralNorm(conv_layer(dim, dim, 3, 1, 1)),
890
+ )
891
+ def forward(self, x):
892
+ out = x + self.Model(x)
893
+ return out
roop/processors/Enhance_GFPGAN.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import numpy as np
4
+ import onnxruntime
5
+ import roop.globals
6
+
7
+ from roop.typing import Face, Frame, FaceSet
8
+ from roop.utilities import resolve_relative_path
9
+
10
+
11
+ # THREAD_LOCK = threading.Lock()
12
+
13
+
14
+ class Enhance_GFPGAN():
15
+
16
+ model_gfpgan = None
17
+ name = None
18
+ devicename = None
19
+
20
+ processorname = 'gfpgan'
21
+ type = 'enhance'
22
+
23
+
24
+ def Initialize(self, devicename):
25
+ if self.model_gfpgan is None:
26
+ model_path = resolve_relative_path('../models/GFPGANv1.4.onnx')
27
+ self.model_gfpgan = onnxruntime.InferenceSession(model_path, None, providers=roop.globals.execution_providers)
28
+ # replace Mac mps with cpu for the moment
29
+ devicename = devicename.replace('mps', 'cpu')
30
+ self.devicename = devicename
31
+
32
+ self.name = self.model_gfpgan.get_inputs()[0].name
33
+
34
+ def Run(self, source_faceset: FaceSet, target_face: Face, temp_frame: Frame) -> Frame:
35
+ # preprocess
36
+ input_size = temp_frame.shape[1]
37
+ temp_frame = cv2.resize(temp_frame, (512, 512), cv2.INTER_CUBIC)
38
+
39
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB)
40
+ temp_frame = temp_frame.astype('float32') / 255.0
41
+ temp_frame = (temp_frame - 0.5) / 0.5
42
+ temp_frame = np.expand_dims(temp_frame, axis=0).transpose(0, 3, 1, 2)
43
+
44
+ io_binding = self.model_gfpgan.io_binding()
45
+ io_binding.bind_cpu_input("input", temp_frame)
46
+ io_binding.bind_output("1288", self.devicename)
47
+ self.model_gfpgan.run_with_iobinding(io_binding)
48
+ ort_outs = io_binding.copy_outputs_to_cpu()
49
+ result = ort_outs[0][0]
50
+
51
+ # post-process
52
+ result = np.clip(result, -1, 1)
53
+ result = (result + 1) / 2
54
+ result = result.transpose(1, 2, 0) * 255.0
55
+ result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
56
+ scale_factor = int(result.shape[1] / input_size)
57
+ return result.astype(np.uint8), scale_factor
58
+
59
+
60
+ def Release(self):
61
+ self.model_gfpgan = None
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
roop/processors/Enhance_GPEN.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import numpy as np
4
+ import onnxruntime
5
+ import roop.globals
6
+
7
+ from roop.typing import Face, Frame, FaceSet
8
+ from roop.utilities import resolve_relative_path
9
+
10
+
11
+ class Enhance_GPEN():
12
+
13
+ model_gpen = None
14
+ name = None
15
+ devicename = None
16
+
17
+ processorname = 'gpen'
18
+ type = 'enhance'
19
+
20
+
21
+ def Initialize(self, devicename):
22
+ if self.model_gpen is None:
23
+ model_path = resolve_relative_path('../models/GPEN-BFR-512.onnx')
24
+ self.model_gpen = onnxruntime.InferenceSession(model_path, None, providers=roop.globals.execution_providers)
25
+ # replace Mac mps with cpu for the moment
26
+ devicename = devicename.replace('mps', 'cpu')
27
+ self.devicename = devicename
28
+
29
+ self.name = self.model_gpen.get_inputs()[0].name
30
+
31
+ def Run(self, source_faceset: FaceSet, target_face: Face, temp_frame: Frame) -> Frame:
32
+ # preprocess
33
+ input_size = temp_frame.shape[1]
34
+ temp_frame = cv2.resize(temp_frame, (512, 512), cv2.INTER_CUBIC)
35
+
36
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB)
37
+ temp_frame = temp_frame.astype('float32') / 255.0
38
+ temp_frame = (temp_frame - 0.5) / 0.5
39
+ temp_frame = np.expand_dims(temp_frame, axis=0).transpose(0, 3, 1, 2)
40
+
41
+ io_binding = self.model_gpen.io_binding()
42
+ io_binding.bind_cpu_input("input", temp_frame)
43
+ io_binding.bind_output("output", self.devicename)
44
+ self.model_gpen.run_with_iobinding(io_binding)
45
+ ort_outs = io_binding.copy_outputs_to_cpu()
46
+ result = ort_outs[0][0]
47
+
48
+ # post-process
49
+ result = np.clip(result, -1, 1)
50
+ result = (result + 1) / 2
51
+ result = result.transpose(1, 2, 0) * 255.0
52
+ result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
53
+ scale_factor = int(result.shape[1] / input_size)
54
+ return result.astype(np.uint8), scale_factor
55
+
56
+
57
+ def Release(self):
58
+ self.model_gpen = None
roop/processors/Enhance_RestoreFormer.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import numpy as np
4
+ import onnxruntime
5
+ import roop.globals
6
+
7
+ from roop.typing import Face, Frame, FaceSet
8
+ from roop.utilities import resolve_relative_path
9
+
10
+
11
+ # THREAD_LOCK = threading.Lock()
12
+
13
+
14
+ class Enhance_RestoreFormer():
15
+ model_restoreformer = None
16
+ devicename = None
17
+ name = None
18
+
19
+ processorname = 'restoreformer'
20
+ type = 'enhance'
21
+
22
+
23
+ def Initialize(self, devicename:str):
24
+ if self.model_restoreformer is None:
25
+ # replace Mac mps with cpu for the moment
26
+ devicename = devicename.replace('mps', 'cpu')
27
+ self.devicename = devicename
28
+ model_path = resolve_relative_path('../models/restoreformer.onnx')
29
+ self.model_restoreformer = onnxruntime.InferenceSession(model_path, None, providers=roop.globals.execution_providers)
30
+ self.model_inputs = self.model_restoreformer.get_inputs()
31
+ model_outputs = self.model_restoreformer.get_outputs()
32
+ self.io_binding = self.model_restoreformer.io_binding()
33
+ self.io_binding.bind_output(model_outputs[0].name, self.devicename)
34
+
35
+ def Run(self, source_faceset: FaceSet, target_face: Face, temp_frame: Frame) -> Frame:
36
+ # preprocess
37
+ input_size = temp_frame.shape[1]
38
+ temp_frame = cv2.resize(temp_frame, (512, 512), cv2.INTER_CUBIC)
39
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB)
40
+ temp_frame = temp_frame.astype('float32') / 255.0
41
+ temp_frame = (temp_frame - 0.5) / 0.5
42
+ temp_frame = np.expand_dims(temp_frame, axis=0).transpose(0, 3, 1, 2)
43
+
44
+ self.io_binding.bind_cpu_input(self.model_inputs[0].name, temp_frame) # .astype(np.float32)
45
+ self.model_restoreformer.run_with_iobinding(self.io_binding)
46
+ ort_outs = self.io_binding.copy_outputs_to_cpu()
47
+ result = ort_outs[0][0]
48
+ del ort_outs
49
+
50
+ result = np.clip(result, -1, 1)
51
+ result = (result + 1) / 2
52
+ result = result.transpose(1, 2, 0) * 255.0
53
+ result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
54
+ scale_factor = int(result.shape[1] / input_size)
55
+ return result.astype(np.uint8), scale_factor
56
+
57
+
58
+ def Release(self):
59
+ del self.model_restoreformer
60
+ self.model_restoreformer = None
61
+ del self.io_binding
62
+ self.io_binding = None
63
+
roop/processors/FaceSwapInsightFace.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import roop.globals
3
+ import insightface
4
+ import cv2
5
+ import numpy as np
6
+
7
+ from roop.typing import Face, Frame
8
+ from roop.utilities import resolve_relative_path
9
+
10
+
11
+
12
+ class FaceSwapInsightFace():
13
+ model_swap_insightface = None
14
+
15
+
16
+ processorname = 'faceswap'
17
+ type = 'swap'
18
+
19
+
20
+ def Initialize(self, devicename):
21
+ if self.model_swap_insightface is None:
22
+ model_path = resolve_relative_path('../models/inswapper_128.onnx')
23
+ self.model_swap_insightface = insightface.model_zoo.get_model(model_path, providers=roop.globals.execution_providers)
24
+
25
+
26
+ def Run(self, source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
27
+ img_fake, M = self.model_swap_insightface.get(temp_frame, target_face, source_face, paste_back=False)
28
+ target_face.matrix = M
29
+ return img_fake
30
+
31
+
32
+ def Release(self):
33
+ del self.model_swap_insightface
34
+ self.model_swap_insightface = None
35
+
36
+
37
+
38
+
39
+
40
+
roop/processors/Mask_Clip2Seg.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import torch
5
+ import threading
6
+ from torchvision import transforms
7
+ from clip.clipseg import CLIPDensePredT
8
+ from numpy import asarray
9
+ from typing import Any, List, Callable
10
+ import numpy as np
11
+
12
+ from roop.typing import Face, Frame
13
+ from roop.utilities import resolve_relative_path
14
+
15
+ THREAD_LOCK_CLIP = threading.Lock()
16
+
17
+
18
+ class Mask_Clip2Seg():
19
+
20
+ model_clip = None
21
+
22
+ processorname = 'clip2seg'
23
+ type = 'mask'
24
+
25
+
26
+ def Initialize(self, devicename):
27
+ if self.model_clip is None:
28
+ self.model_clip = CLIPDensePredT(version='ViT-B/16', reduce_dim=64, complex_trans_conv=True)
29
+ self.model_clip.eval();
30
+ self.model_clip.load_state_dict(torch.load('models/CLIP/rd64-uni-refined.pth', map_location=torch.device('cpu')), strict=False)
31
+
32
+ device = torch.device(devicename)
33
+ self.model_clip.to(device)
34
+
35
+
36
+ def Run(self, img1, keywords:str) -> Frame:
37
+ if keywords is None or len(keywords) < 1 or img1 is None:
38
+ return img1
39
+
40
+ source_image_small = cv2.resize(img1, (256,256))
41
+
42
+ img_mask = np.full((source_image_small.shape[0],source_image_small.shape[1]), 0, dtype=np.float32)
43
+ mask_border = 1
44
+ l = 0
45
+ t = 0
46
+ r = 1
47
+ b = 1
48
+
49
+ mask_blur = 5
50
+ clip_blur = 5
51
+
52
+ img_mask = cv2.rectangle(img_mask, (mask_border+int(l), mask_border+int(t)),
53
+ (256 - mask_border-int(r), 256-mask_border-int(b)), (255, 255, 255), -1)
54
+ img_mask = cv2.GaussianBlur(img_mask, (mask_blur*2+1,mask_blur*2+1), 0)
55
+ img_mask /= 255
56
+
57
+
58
+ input_image = source_image_small
59
+
60
+ transform = transforms.Compose([
61
+ transforms.ToTensor(),
62
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
63
+ transforms.Resize((256, 256)),
64
+ ])
65
+ img = transform(input_image).unsqueeze(0)
66
+
67
+ thresh = 0.5
68
+ prompts = keywords.split(',')
69
+ with THREAD_LOCK_CLIP:
70
+ with torch.no_grad():
71
+ preds = self.model_clip(img.repeat(len(prompts),1,1,1), prompts)[0]
72
+ clip_mask = torch.sigmoid(preds[0][0])
73
+ for i in range(len(prompts)-1):
74
+ clip_mask += torch.sigmoid(preds[i+1][0])
75
+
76
+ clip_mask = clip_mask.data.cpu().numpy()
77
+ np.clip(clip_mask, 0, 1)
78
+
79
+ clip_mask[clip_mask>thresh] = 1.0
80
+ clip_mask[clip_mask<=thresh] = 0.0
81
+ kernel = np.ones((5, 5), np.float32)
82
+ clip_mask = cv2.dilate(clip_mask, kernel, iterations=1)
83
+ clip_mask = cv2.GaussianBlur(clip_mask, (clip_blur*2+1,clip_blur*2+1), 0)
84
+
85
+ img_mask *= clip_mask
86
+ img_mask[img_mask<0.0] = 0.0
87
+ return img_mask
88
+
89
+
90
+
91
+ def Release(self):
92
+ self.model_clip = None
93
+
roop/processors/__init__.py ADDED
File without changes
roop/processors/frame/__init__.py ADDED
File without changes
roop/processors/frame/face_swapper.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import insightface
4
+ import threading
5
+
6
+ import roop.globals
7
+ import roop.processors.frame.core
8
+ from roop.face_util import get_first_face, get_all_faces
9
+ from roop.typing import Face, Frame
10
+ from roop.utilities import conditional_download, resolve_relative_path, is_image, is_video, compute_cosine_distance, get_destfilename_from_path
11
+
12
+ FACE_SWAPPER = None
13
+ THREAD_LOCK = threading.Lock()
14
+ NAME = 'ROOP.FACE-SWAPPER'
15
+
16
+ DIST_THRESHOLD = 0.65
17
+
18
+
19
+ def get_face_swapper() -> Any:
20
+ global FACE_SWAPPER
21
+
22
+ with THREAD_LOCK:
23
+ if FACE_SWAPPER is None:
24
+ model_path = resolve_relative_path('../models/inswapper_128.onnx')
25
+ FACE_SWAPPER = insightface.model_zoo.get_model(model_path, providers=roop.globals.execution_providers)
26
+ return FACE_SWAPPER
27
+
28
+
29
+ def pre_check() -> bool:
30
+ download_directory_path = resolve_relative_path('../models')
31
+ conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/inswapper_128.onnx'])
32
+ return True
33
+
34
+
35
+ def pre_start() -> bool:
36
+ return True
37
+
38
+
39
+ def post_process() -> None:
40
+ global FACE_SWAPPER
41
+
42
+ FACE_SWAPPER = None
43
+
44
+
45
+ def swap_face(source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
46
+ return get_face_swapper().get(temp_frame, target_face, source_face, paste_back=True)
47
+
48
+
49
+ def process_frame(source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
50
+ global DIST_THRESHOLD
51
+
52
+ if roop.globals.many_faces:
53
+ many_faces = get_all_faces(temp_frame)
54
+ if many_faces is not None:
55
+ for target_face in many_faces:
56
+ if target_face['det_score'] > 0.65:
57
+ temp_frame = swap_face(source_face, target_face, temp_frame)
58
+ else:
59
+ if target_face:
60
+ target_embedding = target_face.embedding
61
+ many_faces = get_all_faces(temp_frame)
62
+ target_face = None
63
+ for dest_face in many_faces:
64
+ dest_embedding = dest_face.embedding
65
+ if compute_cosine_distance(target_embedding, dest_embedding) <= DIST_THRESHOLD:
66
+ target_face = dest_face
67
+ break
68
+ if target_face:
69
+ temp_frame = swap_face(source_face, target_face, temp_frame)
70
+ return temp_frame
71
+
72
+ target_face = get_first_face(temp_frame)
73
+ if target_face is not None:
74
+ temp_frame = swap_face(source_face, target_face, temp_frame)
75
+ return temp_frame
76
+
77
+
78
+
79
+ def process_frames(is_batch: bool, source_face: Face, target_face: Face, temp_frame_paths: List[str], update: Callable[[], None]) -> None:
80
+ for temp_frame_path in temp_frame_paths:
81
+ temp_frame = cv2.imread(temp_frame_path)
82
+ if temp_frame is not None:
83
+ result = process_frame(source_face, target_face, temp_frame)
84
+ if result is not None:
85
+ if is_batch:
86
+ tf = get_destfilename_from_path(temp_frame_path, roop.globals.output_path, '_fake.png')
87
+ cv2.imwrite(tf, result)
88
+ else:
89
+ cv2.imwrite(temp_frame_path, result)
90
+ if update:
91
+ update()
92
+
93
+
94
+ def process_image(source_face: Any, target_face: Any, target_path: str, output_path: str) -> None:
95
+ global DIST_THRESHOLD
96
+
97
+ target_frame = cv2.imread(target_path)
98
+ if target_frame is not None:
99
+ result = process_frame(source_face, target_face, target_frame)
100
+ if result is not None:
101
+ cv2.imwrite(output_path, result)
102
+
103
+
104
+ def process_video(source_face: Any, target_face: Any, temp_frame_paths: List[str]) -> None:
105
+ global DIST_THRESHOLD
106
+
107
+ roop.processors.frame.core.process_video(source_face, target_face, temp_frame_paths, process_frames)
108
+
109
+
110
+ def process_batch_images(source_face: Any, target_face: Any, temp_frame_paths: List[str]) -> None:
111
+ global DIST_THRESHOLD
112
+
113
+ roop.processors.frame.core.process_batch(source_face, target_face, temp_frame_paths, process_frames)
roop/template_parser.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from datetime import datetime
3
+
4
+ template_functions = {
5
+ "timestamp": lambda data: str(int(datetime.now().timestamp())),
6
+ "i": lambda data: data.get("index", False),
7
+ "file": lambda data: data.get("file", False),
8
+ "date": lambda data: datetime.now().strftime("%Y-%m-%d"),
9
+ "time": lambda data: datetime.now().strftime("%H-%M-%S"),
10
+ }
11
+
12
+
13
+ def parse(text: str, data: dict):
14
+ pattern = r"\{([^}]+)\}"
15
+
16
+ matches = re.findall(pattern, text)
17
+
18
+ for match in matches:
19
+ replacement = template_functions[match](data)
20
+ if replacement is not False:
21
+ text = text.replace(f"{{{match}}}", replacement)
22
+
23
+ return text
roop/typing.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from insightface.app.common import Face
4
+ from roop.FaceSet import FaceSet
5
+ import numpy
6
+
7
+ Face = Face
8
+ FaceSet = FaceSet
9
+ Frame = numpy.ndarray[Any, Any]
roop/util_ffmpeg.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import subprocess
4
+ import roop.globals
5
+ import roop.utilities as util
6
+
7
+ from typing import List, Any
8
+
9
+ def run_ffmpeg(args: List[str]) -> bool:
10
+ commands = ['ffmpeg', '-hide_banner', '-hwaccel', 'auto', '-y', '-loglevel', roop.globals.log_level]
11
+ commands.extend(args)
12
+ print (" ".join(commands))
13
+ try:
14
+ subprocess.check_output(commands, stderr=subprocess.STDOUT)
15
+ return True
16
+ except Exception as e:
17
+ print(e)
18
+ return False
19
+
20
+
21
+ # commands = [ 'ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=r_frame_rate', '-of', 'json', target_path ]
22
+ # output = subprocess.check_output(commands).decode().strip()
23
+ # try:
24
+ # entries = json.loads(output)
25
+ # for stream in entries.get('streams'):
26
+ # numerator, denominator = map(int, stream.get('r_frame_rate').split('/'))
27
+ # return numerator / denominator
28
+ # return None
29
+ # except (ValueError, ZeroDivisionError):
30
+ # return 24
31
+
32
+
33
+ def cut_video(original_video: str, cut_video: str, start_frame: int, end_frame: int):
34
+ fps = util.detect_fps(original_video)
35
+ start_time = start_frame / fps
36
+ num_frames = end_frame - start_frame
37
+
38
+ run_ffmpeg(['-ss', str(start_time), '-i', original_video, '-c:v', roop.globals.video_encoder, '-c:a', 'aac', '-frames:v', str(num_frames), cut_video])
39
+
40
+ def join_videos(videos: List[str], dest_filename: str, simple: bool):
41
+ if simple:
42
+ txtfilename = util.resolve_relative_path('../temp')
43
+ txtfilename = os.path.join(txtfilename, 'joinvids.txt')
44
+ with open(txtfilename, "w", encoding="utf-8") as f:
45
+ for v in videos:
46
+ v = v.replace('\\', '/')
47
+ f.write(f"file {v}\n")
48
+ commands = ['-f', 'concat', '-safe', '0', '-i', f'{txtfilename}', '-vcodec', 'copy', f'{dest_filename}']
49
+ run_ffmpeg(commands)
50
+
51
+ else:
52
+ inputs = []
53
+ filter = ''
54
+ for i,v in enumerate(videos):
55
+ inputs.append('-i')
56
+ inputs.append(v)
57
+ filter += f'[{i}:v:0][{i}:a:0]'
58
+ run_ffmpeg([" ".join(inputs), '-filter_complex', f'"{filter}concat=n={len(videos)}:v=1:a=1[outv][outa]"', '-map', '"[outv]"', '-map', '"[outa]"', dest_filename])
59
+
60
+
61
+
62
+ def extract_frames(target_path : str, trim_frame_start, trim_frame_end, fps : float) -> bool:
63
+ util.create_temp(target_path)
64
+ temp_directory_path = util.get_temp_directory_path(target_path)
65
+ commands = ['-i', target_path, '-q:v', '1', '-pix_fmt', 'rgb24', ]
66
+ if trim_frame_start is not None and trim_frame_end is not None:
67
+ commands.extend([ '-vf', 'trim=start_frame=' + str(trim_frame_start) + ':end_frame=' + str(trim_frame_end) + ',fps=' + str(fps) ])
68
+ commands.extend(['-vsync', '0', os.path.join(temp_directory_path, '%06d.' + roop.globals.CFG.output_image_format)])
69
+ return run_ffmpeg(commands)
70
+
71
+
72
+ def create_video(target_path: str, dest_filename: str, fps: float = 24.0, temp_directory_path: str = None) -> None:
73
+ if temp_directory_path is None:
74
+ temp_directory_path = util.get_temp_directory_path(target_path)
75
+ run_ffmpeg(['-r', str(fps), '-i', os.path.join(temp_directory_path, f'%06d.{roop.globals.CFG.output_image_format}'), '-c:v', roop.globals.video_encoder, '-crf', str(roop.globals.video_quality), '-pix_fmt', 'yuv420p', '-vf', 'colorspace=bt709:iall=bt601-6-625:fast=1', '-y', dest_filename])
76
+ return dest_filename
77
+
78
+
79
+ def create_gif_from_video(video_path: str, gif_path):
80
+ from roop.capturer import get_video_frame
81
+
82
+ fps = util.detect_fps(video_path)
83
+ frame = get_video_frame(video_path)
84
+
85
+ run_ffmpeg(['-i', video_path, '-vf', f'fps={fps},scale={frame.shape[0]}:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse', '-loop', '0', gif_path])
86
+
87
+
88
+ def restore_audio(intermediate_video: str, original_video: str, trim_frame_start, trim_frame_end, final_video : str) -> None:
89
+ fps = util.detect_fps(original_video)
90
+ commands = [ '-i', intermediate_video ]
91
+ if trim_frame_start is None and trim_frame_end is None:
92
+ commands.extend([ '-c:a', 'copy' ])
93
+ else:
94
+ # if trim_frame_start is not None:
95
+ # start_time = trim_frame_start / fps
96
+ # commands.extend([ '-ss', format(start_time, ".2f")])
97
+ # else:
98
+ # commands.extend([ '-ss', '0' ])
99
+ # if trim_frame_end is not None:
100
+ # end_time = trim_frame_end / fps
101
+ # commands.extend([ '-to', format(end_time, ".2f")])
102
+ # commands.extend([ '-c:a', 'aac' ])
103
+ if trim_frame_start is not None:
104
+ start_time = trim_frame_start / fps
105
+ commands.extend([ '-ss', format(start_time, ".2f")])
106
+ else:
107
+ commands.extend([ '-ss', '0' ])
108
+ if trim_frame_end is not None:
109
+ end_time = trim_frame_end / fps
110
+ commands.extend([ '-to', format(end_time, ".2f")])
111
+ commands.extend([ '-i', original_video, "-c", "copy" ])
112
+
113
+ commands.extend([ '-map', '0:v:0', '-map', '1:a:0?', '-shortest', final_video ])
114
+ run_ffmpeg(commands)
roop/utilities.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import mimetypes
3
+ import os
4
+ import platform
5
+ import shutil
6
+ import ssl
7
+ import subprocess
8
+ import sys
9
+ import urllib
10
+ import torch
11
+ import gradio
12
+ import tempfile
13
+ import cv2
14
+ import zipfile
15
+ import traceback
16
+
17
+ from pathlib import Path
18
+ from typing import List, Any
19
+ from tqdm import tqdm
20
+ from scipy.spatial import distance
21
+
22
+ import roop.template_parser as template_parser
23
+
24
+ import roop.globals
25
+
26
+ TEMP_FILE = 'temp.mp4'
27
+ TEMP_DIRECTORY = 'temp'
28
+
29
+ # monkey patch ssl for mac
30
+ if platform.system().lower() == 'darwin':
31
+ ssl._create_default_https_context = ssl._create_unverified_context
32
+
33
+
34
+
35
+
36
+ # https://github.com/facefusion/facefusion/blob/master/facefusion
37
+ def detect_fps(target_path : str) -> float:
38
+ fps = 24.0
39
+ cap = cv2.VideoCapture(target_path)
40
+ if cap.isOpened():
41
+ fps = cap.get(cv2.CAP_PROP_FPS)
42
+ cap.release()
43
+ return fps
44
+
45
+
46
+ # Gradio wants Images in RGB
47
+ def convert_to_gradio(image):
48
+ if image is None:
49
+ return None
50
+ return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
51
+
52
+
53
+ def sort_filenames_ignore_path(filenames):
54
+ """Sorts a list of filenames containing a complete path by their filename,
55
+ while retaining their original path.
56
+
57
+ Args:
58
+ filenames: A list of filenames containing a complete path.
59
+
60
+ Returns:
61
+ A sorted list of filenames containing a complete path.
62
+ """
63
+ filename_path_tuples = [(os.path.split(filename)[1], filename) for filename in filenames]
64
+ sorted_filename_path_tuples = sorted(filename_path_tuples, key=lambda x: x[0])
65
+ return [filename_path_tuple[1] for filename_path_tuple in sorted_filename_path_tuples]
66
+
67
+
68
+ def sort_rename_frames(path: str):
69
+ filenames = os.listdir(path)
70
+ filenames.sort()
71
+ for i in range(len(filenames)):
72
+ of = os.path.join(path, filenames[i])
73
+ newidx = i+1
74
+ new_filename = os.path.join(path, f"{newidx:06d}." + roop.globals.CFG.output_image_format)
75
+ os.rename(of, new_filename)
76
+
77
+
78
+ def get_temp_frame_paths(target_path: str) -> List[str]:
79
+ temp_directory_path = get_temp_directory_path(target_path)
80
+ return glob.glob((os.path.join(glob.escape(temp_directory_path), f'*.{roop.globals.CFG.output_image_format}')))
81
+
82
+
83
+ def get_temp_directory_path(target_path: str) -> str:
84
+ target_name, _ = os.path.splitext(os.path.basename(target_path))
85
+ target_directory_path = os.path.dirname(target_path)
86
+ return os.path.join(target_directory_path, TEMP_DIRECTORY, target_name)
87
+
88
+
89
+ def get_temp_output_path(target_path: str) -> str:
90
+ temp_directory_path = get_temp_directory_path(target_path)
91
+ return os.path.join(temp_directory_path, TEMP_FILE)
92
+
93
+
94
+ def normalize_output_path(source_path: str, target_path: str, output_path: str) -> Any:
95
+ if source_path and target_path:
96
+ source_name, _ = os.path.splitext(os.path.basename(source_path))
97
+ target_name, target_extension = os.path.splitext(os.path.basename(target_path))
98
+ if os.path.isdir(output_path):
99
+ return os.path.join(output_path, source_name + '-' + target_name + target_extension)
100
+ return output_path
101
+
102
+
103
+ def get_destfilename_from_path(srcfilepath: str, destfilepath: str, extension: str) -> str:
104
+ fn, ext = os.path.splitext(os.path.basename(srcfilepath))
105
+ if '.' in extension:
106
+ return os.path.join(destfilepath, f'{fn}{extension}')
107
+ return os.path.join(destfilepath, f'{fn}{extension}{ext}')
108
+
109
+ def replace_template(file_path: str, index: int = 0):
110
+ fn, ext = os.path.splitext(os.path.basename(file_path))
111
+
112
+ # Remove the "__temp" placeholder that was used as a temporary filename
113
+ fn = fn.replace('__temp', '')
114
+
115
+ template = roop.globals.CFG.output_template
116
+ replaced_filename = template_parser.parse(template, {
117
+ 'index': str(index),
118
+ 'file': fn
119
+ })
120
+
121
+ return os.path.join(roop.globals.output_path, f'{replaced_filename}{ext}')
122
+
123
+
124
+
125
+ def create_temp(target_path: str) -> None:
126
+ temp_directory_path = get_temp_directory_path(target_path)
127
+ Path(temp_directory_path).mkdir(parents=True, exist_ok=True)
128
+
129
+
130
+ def move_temp(target_path: str, output_path: str) -> None:
131
+ temp_output_path = get_temp_output_path(target_path)
132
+ if os.path.isfile(temp_output_path):
133
+ if os.path.isfile(output_path):
134
+ os.remove(output_path)
135
+ shutil.move(temp_output_path, output_path)
136
+
137
+
138
+ def clean_temp(target_path: str) -> None:
139
+ temp_directory_path = get_temp_directory_path(target_path)
140
+ parent_directory_path = os.path.dirname(temp_directory_path)
141
+ if not roop.globals.keep_frames and os.path.isdir(temp_directory_path):
142
+ shutil.rmtree(temp_directory_path)
143
+ if os.path.exists(parent_directory_path) and not os.listdir(parent_directory_path):
144
+ os.rmdir(parent_directory_path)
145
+
146
+ def delete_temp_frames(filename: str) -> None:
147
+ dir = os.path.dirname(os.path.dirname(filename))
148
+ shutil.rmtree(dir)
149
+
150
+
151
+
152
+
153
+ def has_image_extension(image_path: str) -> bool:
154
+ return image_path.lower().endswith(('png', 'jpg', 'jpeg', 'webp'))
155
+
156
+ def has_extension(filepath: str, extensions: List[str]) -> bool:
157
+ return filepath.lower().endswith(tuple(extensions))
158
+
159
+
160
+ def is_image(image_path: str) -> bool:
161
+ if image_path and os.path.isfile(image_path):
162
+ mimetype, _ = mimetypes.guess_type(image_path)
163
+ return bool(mimetype and mimetype.startswith('image/'))
164
+ return False
165
+
166
+
167
+ def is_video(video_path: str) -> bool:
168
+ if video_path and os.path.isfile(video_path):
169
+ mimetype, _ = mimetypes.guess_type(video_path)
170
+ return bool(mimetype and mimetype.startswith('video/'))
171
+ return False
172
+
173
+
174
+ def conditional_download(download_directory_path: str, urls: List[str]) -> None:
175
+ if not os.path.exists(download_directory_path):
176
+ os.makedirs(download_directory_path)
177
+ for url in urls:
178
+ download_file_path = os.path.join(download_directory_path, os.path.basename(url))
179
+ if not os.path.exists(download_file_path):
180
+ request = urllib.request.urlopen(url) # type: ignore[attr-defined]
181
+ total = int(request.headers.get('Content-Length', 0))
182
+ with tqdm(total=total, desc=f'Downloading {url}', unit='B', unit_scale=True, unit_divisor=1024) as progress:
183
+ urllib.request.urlretrieve(url, download_file_path, reporthook=lambda count, block_size, total_size: progress.update(block_size)) # type: ignore[attr-defined]
184
+
185
+
186
+ def get_local_files_from_folder(folder:str):
187
+ if not os.path.exists(folder) or not os.path.isdir(folder):
188
+ return None
189
+ files = [os.path.join(folder, f) for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
190
+ return files
191
+
192
+
193
+ def resolve_relative_path(path: str) -> str:
194
+ return os.path.abspath(os.path.join(os.path.dirname(__file__), path))
195
+
196
+ def get_device() -> str:
197
+ if len(roop.globals.execution_providers) < 1:
198
+ roop.globals.execution_providers = ['CPUExecutionProvider']
199
+
200
+ prov = roop.globals.execution_providers[0]
201
+ if 'CUDAExecutionProvider' == prov:
202
+ return 'cuda'
203
+ if 'CoreMLExecutionProvider' == prov:
204
+ return 'mps'
205
+ return 'cpu'
206
+
207
+
208
+ def str_to_class(module_name, class_name):
209
+ from importlib import import_module
210
+ try:
211
+ module_ = import_module(module_name)
212
+ try:
213
+ class_ = getattr(module_, class_name)()
214
+ except AttributeError:
215
+ print(f'Class {class_name} does not exist')
216
+ except ImportError:
217
+ print(f'Module {module_name} does not exist')
218
+ return class_ or None
219
+
220
+
221
+ # Taken from https://stackoverflow.com/a/68842705
222
+ def get_platform():
223
+ if sys.platform == 'linux':
224
+ try:
225
+ proc_version = open('/proc/version').read()
226
+ if 'Microsoft' in proc_version:
227
+ return 'wsl'
228
+ except:
229
+ pass
230
+ return sys.platform
231
+
232
+ def open_with_default_app(filename):
233
+ if filename == None:
234
+ return
235
+ platform = get_platform()
236
+ if platform == 'darwin':
237
+ subprocess.call(('open', filename))
238
+ elif platform in ['win64', 'win32']:
239
+ os.startfile(filename.replace('/','\\'))
240
+ elif platform == 'wsl':
241
+ subprocess.call('cmd.exe /C start'.split() + [filename])
242
+ else: # linux variants
243
+ subprocess.call('xdg-open', filename)
244
+
245
+ def prepare_for_batch(target_files):
246
+ print("Preparing temp files")
247
+ tempfolder = os.path.join(tempfile.gettempdir(), "rooptmp")
248
+ if os.path.exists(tempfolder):
249
+ shutil.rmtree(tempfolder)
250
+ Path(tempfolder).mkdir(parents=True, exist_ok=True)
251
+ for f in target_files:
252
+ newname = os.path.basename(f.name)
253
+ shutil.move(f.name, os.path.join(tempfolder, newname))
254
+ return tempfolder
255
+
256
+
257
+ def zip(files, zipname):
258
+ with zipfile.ZipFile(zipname, "w") as zip_file:
259
+ for f in files:
260
+ zip_file.write(f, os.path.basename(f))
261
+
262
+ def unzip(zipfilename:str, target_path:str):
263
+ with zipfile.ZipFile(zipfilename, "r") as zip_file:
264
+ zip_file.extractall(target_path)
265
+
266
+
267
+ def mkdir_with_umask(directory):
268
+ oldmask = os.umask(0)
269
+ # mode needs octal
270
+ os.makedirs(directory, mode=0o775, exist_ok=True)
271
+ os.umask(oldmask)
272
+
273
+ def open_folder(path:str):
274
+ platform = get_platform()
275
+ try:
276
+ if platform == 'darwin':
277
+ subprocess.call(('open', path))
278
+ elif platform in ['win64', 'win32']:
279
+ open_with_default_app(path)
280
+ elif platform == 'wsl':
281
+ subprocess.call('cmd.exe /C start'.split() + [path])
282
+ else: # linux variants
283
+ subprocess.Popen(['xdg-open', path])
284
+ except Exception as e:
285
+ traceback.print_exc()
286
+ pass
287
+ #import webbrowser
288
+ #webbrowser.open(url)
289
+
290
+
291
+
292
+ def create_version_html():
293
+ python_version = ".".join([str(x) for x in sys.version_info[0:3]])
294
+ versions_html = f"""
295
+ python: <span title="{sys.version}">{python_version}</span>
296
+
297
+ torch: {getattr(torch, '__long_version__',torch.__version__)}
298
+
299
+ gradio: {gradio.__version__}
300
+ """
301
+ return versions_html
302
+
303
+
304
+ def compute_cosine_distance(emb1, emb2):
305
+ return distance.cosine(emb1, emb2)
roop/virtualcam.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import roop.globals
3
+ import pyvirtualcam
4
+ import threading
5
+ import time
6
+
7
+
8
+ cam_active = False
9
+ cam_thread = None
10
+ vcam = None
11
+
12
+ def virtualcamera(cam_num):
13
+ from roop.core import live_swap
14
+ global cam_active
15
+
16
+ time.sleep(2)
17
+ print('Starting capture')
18
+ cap = cv2.VideoCapture(cam_num, cv2.CAP_DSHOW)
19
+ if not cap.isOpened():
20
+ print("Cannot open camera")
21
+ cap.release()
22
+ del cap
23
+ return
24
+
25
+ pref_width = 1280
26
+ pref_height = 720
27
+ pref_fps_in = 30
28
+ cap.set(cv2.CAP_PROP_FRAME_WIDTH, pref_width)
29
+ cap.set(cv2.CAP_PROP_FRAME_HEIGHT, pref_height)
30
+ cap.set(cv2.CAP_PROP_FPS, pref_fps_in)
31
+ print('Starting VCAM')
32
+ cam_active = True
33
+
34
+ # native format UYVY
35
+
36
+ with pyvirtualcam.Camera(width=pref_width, height=pref_height, fps=pref_fps_in, fmt=pyvirtualcam.PixelFormat.BGR, print_fps=True) as cam:
37
+
38
+ print(f'Using virtual camera: {cam.device}')
39
+ print(f'Using {cam.native_fmt}')
40
+
41
+ # RGB
42
+
43
+ while cam_active:
44
+ ret, frame = cap.read()
45
+ if not ret:
46
+ break
47
+
48
+ if len(roop.globals.INPUT_FACESETS) > 0:
49
+ frame = live_swap(frame, "all", False, None)
50
+ cam.send(frame)
51
+ else:
52
+ cam.send(frame)
53
+ cam.sleep_until_next_frame()
54
+
55
+ cap.release()
56
+ print('End cam')
57
+
58
+
59
+
60
+ def start_virtual_cam(cam_number):
61
+ global cam_thread, cam_active
62
+
63
+ if not cam_active:
64
+ cam_thread = threading.Thread(target=virtualcamera, args=[cam_number])
65
+ cam_thread.start()
66
+
67
+
68
+
69
+ def stop_virtual_cam():
70
+ global cam_active
71
+
72
+ cam_active = False
73
+
74
+
roop/vr_util.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+ # VR Lense Distortion
5
+ # Taken from https://github.com/g0kuvonlange/vrswap
6
+
7
+
8
+ def get_perspective(img, FOV, THETA, PHI, height, width):
9
+ #
10
+ # THETA is left/right angle, PHI is up/down angle, both in degree
11
+ #
12
+ [orig_width, orig_height, _] = img.shape
13
+ equ_h = orig_height
14
+ equ_w = orig_width
15
+ equ_cx = (equ_w - 1) / 2.0
16
+ equ_cy = (equ_h - 1) / 2.0
17
+
18
+ wFOV = FOV
19
+ hFOV = float(height) / width * wFOV
20
+
21
+ w_len = np.tan(np.radians(wFOV / 2.0))
22
+ h_len = np.tan(np.radians(hFOV / 2.0))
23
+
24
+ x_map = np.ones([height, width], np.float32)
25
+ y_map = np.tile(np.linspace(-w_len, w_len, width), [height, 1])
26
+ z_map = -np.tile(np.linspace(-h_len, h_len, height), [width, 1]).T
27
+
28
+ D = np.sqrt(x_map**2 + y_map**2 + z_map**2)
29
+ xyz = np.stack((x_map, y_map, z_map), axis=2) / np.repeat(
30
+ D[:, :, np.newaxis], 3, axis=2
31
+ )
32
+
33
+ y_axis = np.array([0.0, 1.0, 0.0], np.float32)
34
+ z_axis = np.array([0.0, 0.0, 1.0], np.float32)
35
+ [R1, _] = cv2.Rodrigues(z_axis * np.radians(THETA))
36
+ [R2, _] = cv2.Rodrigues(np.dot(R1, y_axis) * np.radians(-PHI))
37
+
38
+ xyz = xyz.reshape([height * width, 3]).T
39
+ xyz = np.dot(R1, xyz)
40
+ xyz = np.dot(R2, xyz).T
41
+ lat = np.arcsin(xyz[:, 2])
42
+ lon = np.arctan2(xyz[:, 1], xyz[:, 0])
43
+
44
+ lon = lon.reshape([height, width]) / np.pi * 180
45
+ lat = -lat.reshape([height, width]) / np.pi * 180
46
+
47
+ lon = lon / 180 * equ_cx + equ_cx
48
+ lat = lat / 90 * equ_cy + equ_cy
49
+
50
+ persp = cv2.remap(
51
+ img,
52
+ lon.astype(np.float32),
53
+ lat.astype(np.float32),
54
+ cv2.INTER_CUBIC,
55
+ borderMode=cv2.BORDER_WRAP,
56
+ )
57
+ return persp
run.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from roop import core
4
+
5
+ if __name__ == '__main__':
6
+ core.run()
settings.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yaml
2
+
3
+ class Settings:
4
+ def __init__(self, config_file):
5
+ self.config_file = config_file
6
+ self.load()
7
+
8
+ def default_get(_, data, name, default):
9
+ value = default
10
+ try:
11
+ value = data.get(name, default)
12
+ except:
13
+ pass
14
+ return value
15
+
16
+
17
+ def load(self):
18
+ try:
19
+ with open(self.config_file, 'r') as f:
20
+ data = yaml.load(f, Loader=yaml.FullLoader)
21
+ except:
22
+ data = None
23
+
24
+ self.selected_theme = self.default_get(data, 'selected_theme', "Default")
25
+ self.server_name = self.default_get(data, 'server_name', "")
26
+ self.server_port = self.default_get(data, 'server_port', 0)
27
+ self.server_share = self.default_get(data, 'server_share', False)
28
+ self.output_image_format = self.default_get(data, 'output_image_format', 'png')
29
+ self.output_video_format = self.default_get(data, 'output_video_format', 'mp4')
30
+ self.output_video_codec = self.default_get(data, 'output_video_codec', 'libx264')
31
+ self.video_quality = self.default_get(data, 'video_quality', 14)
32
+ self.clear_output = self.default_get(data, 'clear_output', True)
33
+ self.live_cam_start_active = self.default_get(data, 'live_cam_start_active', False)
34
+ self.max_threads = self.default_get(data, 'max_threads', 2)
35
+ self.memory_limit = self.default_get(data, 'memory_limit', 0)
36
+ self.provider = self.default_get(data, 'provider', 'cuda')
37
+ self.force_cpu = self.default_get(data, 'force_cpu', False)
38
+ self.output_template = self.default_get(data, 'output_template', '{file}_{time}')
39
+ self.use_os_temp_folder = self.default_get(data, 'use_os_temp_folder', False)
40
+
41
+
42
+
43
+
44
+
45
+ def save(self):
46
+ data = {
47
+ 'selected_theme': self.selected_theme,
48
+ 'server_name': self.server_name,
49
+ 'server_port': self.server_port,
50
+ 'server_share': self.server_share,
51
+ 'output_image_format' : self.output_image_format,
52
+ 'output_video_format' : self.output_video_format,
53
+ 'output_video_codec' : self.output_video_codec,
54
+ 'video_quality' : self.video_quality,
55
+ 'clear_output' : self.clear_output,
56
+ 'live_cam_start_active' : self.live_cam_start_active,
57
+ 'max_threads' : self.max_threads,
58
+ 'memory_limit' : self.memory_limit,
59
+ 'provider' : self.provider,
60
+ 'force_cpu' : self.force_cpu,
61
+ 'output_template' : self.output_template,
62
+ 'use_os_temp_folder' : self.use_os_temp_folder
63
+ }
64
+ with open(self.config_file, 'w') as f:
65
+ yaml.dump(data, f)
66
+
67
+
68
+
ui/globals.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ui_restart_server = False
2
+
3
+ SELECTION_FACES_DATA = None
4
+ ui_SELECTED_INPUT_FACE_INDEX = 0
5
+
6
+ ui_selected_enhancer = None
7
+ ui_blend_ratio = None
8
+ ui_input_thumbs = []
9
+ ui_target_thumbs = []
10
+
11
+ ui_live_cam_active = False
12
+
13
+
14
+
15
+
16
+
ui/main.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import gradio as gr
4
+ import roop.globals
5
+ import roop.metadata
6
+ import roop.utilities as util
7
+ import ui.globals as uii
8
+
9
+ from ui.tabs.faceswap_tab import faceswap_tab
10
+ from ui.tabs.livecam_tab import livecam_tab
11
+ from ui.tabs.facemgr_tab import facemgr_tab
12
+ from ui.tabs.extras_tab import extras_tab
13
+ from ui.tabs.settings_tab import settings_tab
14
+
15
+ roop.globals.keep_fps = None
16
+ roop.globals.keep_frames = None
17
+ roop.globals.skip_audio = None
18
+ roop.globals.use_batch = None
19
+
20
+
21
+ def prepare_environment():
22
+ roop.globals.output_path = os.path.abspath(os.path.join(os.getcwd(), "output"))
23
+ os.makedirs(roop.globals.output_path, exist_ok=True)
24
+ if not roop.globals.CFG.use_os_temp_folder:
25
+ os.environ["TEMP"] = os.environ["TMP"] = os.path.abspath(os.path.join(os.getcwd(), "temp"))
26
+ os.makedirs(os.environ["TEMP"], exist_ok=True)
27
+ os.environ["GRADIO_TEMP_DIR"] = os.environ["TEMP"]
28
+
29
+
30
+ def run():
31
+ from roop.core import decode_execution_providers, set_display_ui
32
+
33
+ prepare_environment()
34
+
35
+ set_display_ui(show_msg)
36
+ roop.globals.execution_providers = decode_execution_providers([roop.globals.CFG.provider])
37
+ print(f'Using provider {roop.globals.execution_providers} - Device:{util.get_device()}')
38
+
39
+ run_server = True
40
+ uii.ui_restart_server = False
41
+ mycss = """
42
+ span {color: var(--block-info-text-color)}
43
+ #fixedheight {
44
+ max-height: 238.4px;
45
+ overflow-y: auto !important;
46
+ }
47
+ """
48
+ uii.ui_live_cam_active = roop.globals.CFG.live_cam_start_active
49
+
50
+ while run_server:
51
+ server_name = roop.globals.CFG.server_name
52
+ if server_name is None or len(server_name) < 1:
53
+ server_name = None
54
+ server_port = roop.globals.CFG.server_port
55
+ if server_port <= 0:
56
+ server_port = None
57
+ ssl_verify = False if server_name == '0.0.0.0' else True
58
+ with gr.Blocks(title=f'{roop.metadata.name} {roop.metadata.version}', theme=roop.globals.CFG.selected_theme, css=mycss) as ui:
59
+ with gr.Row(variant='compact'):
60
+ gr.Markdown(f"### [{roop.metadata.name} {roop.metadata.version}](https://github.com/C0untFloyd/roop-unleashed)")
61
+ gr.HTML(util.create_version_html(), elem_id="versions")
62
+ faceswap_tab()
63
+ livecam_tab()
64
+ facemgr_tab()
65
+ extras_tab()
66
+ settings_tab()
67
+
68
+ uii.ui_restart_server = False
69
+ try:
70
+ ui.queue().launch(inbrowser=True, server_name=server_name, server_port=server_port, share=roop.globals.CFG.server_share, ssl_verify=ssl_verify, prevent_thread_lock=True, show_error=True)
71
+ except Exception as e:
72
+ print(f'Exception {e} when launching Gradio Server!')
73
+ uii.ui_restart_server = True
74
+ run_server = False
75
+ try:
76
+ while uii.ui_restart_server == False:
77
+ time.sleep(1.0)
78
+ except (KeyboardInterrupt, OSError):
79
+ print("Keyboard interruption in main thread... closing server.")
80
+ run_server = False
81
+ ui.close()
82
+
83
+
84
+ def show_msg(msg: str):
85
+ gr.Info(msg)
86
+
ui/tabs/extras_tab.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import roop.utilities as util
4
+ import roop.util_ffmpeg as ffmpeg
5
+ import roop.globals
6
+
7
+ def extras_tab():
8
+ with gr.Tab("🎉 Extras"):
9
+ with gr.Row():
10
+ files_to_process = gr.Files(label='File(s) to process', file_count="multiple", file_types=["image", "video"])
11
+ # with gr.Row(variant='panel'):
12
+ # with gr.Accordion(label="Post process", open=False):
13
+ # with gr.Column():
14
+ # selected_post_enhancer = gr.Dropdown(["None", "Codeformer", "GFPGAN"], value="None", label="Select post-processing")
15
+ # with gr.Column():
16
+ # gr.Button("Start").click(fn=lambda: gr.Info('Not yet implemented...'))
17
+ with gr.Row(variant='panel'):
18
+ with gr.Accordion(label="Video/GIF", open=False):
19
+ with gr.Row(variant='panel'):
20
+ with gr.Column():
21
+ gr.Markdown("""
22
+ # Cut video
23
+ Be aware that this means re-encoding the video which might take a longer time.
24
+ Encoding uses your configuration from the Settings Tab.
25
+ """)
26
+ with gr.Column():
27
+ cut_start_time = gr.Slider(0, 1000000, value=0, label="Start Frame", step=1.0, interactive=True)
28
+ with gr.Column():
29
+ cut_end_time = gr.Slider(1, 1000000, value=1, label="End Frame", step=1.0, interactive=True)
30
+ with gr.Column():
31
+ start_cut_video = gr.Button("Cut video")
32
+ start_extract_frames = gr.Button("Extract frames")
33
+
34
+ with gr.Row(variant='panel'):
35
+ with gr.Column():
36
+ gr.Markdown("""
37
+ # Join videos
38
+ """)
39
+ with gr.Column():
40
+ extras_chk_encode = gr.Checkbox(label='Re-encode video (necessary for videos with different codecs)', value=False)
41
+ start_join_videos = gr.Button("Start")
42
+ with gr.Row(variant='panel'):
43
+ with gr.Column():
44
+ gr.Markdown("""
45
+ # Create video/gif from images
46
+ """)
47
+ with gr.Column():
48
+ extras_fps = gr.Slider(minimum=0, maximum=120, value=30, label="Video FPS", step=1.0, interactive=True)
49
+ extras_images_folder = gr.Textbox(show_label=False, placeholder="/content/", interactive=True)
50
+ with gr.Column():
51
+ extras_chk_creategif = gr.Checkbox(label='Create GIF from video', value=False)
52
+ extras_create_video=gr.Button("Create")
53
+ with gr.Row():
54
+ gr.Button("👀 Open Output Folder", size='sm').click(fn=lambda: util.open_folder(roop.globals.output_path))
55
+ with gr.Row():
56
+ extra_files_output = gr.Files(label='Resulting output files', file_count="multiple")
57
+
58
+ start_cut_video.click(fn=on_cut_video, inputs=[files_to_process, cut_start_time, cut_end_time], outputs=[extra_files_output])
59
+ start_extract_frames.click(fn=on_extras_extract_frames, inputs=[files_to_process], outputs=[extra_files_output])
60
+ start_join_videos.click(fn=on_join_videos, inputs=[files_to_process, extras_chk_encode], outputs=[extra_files_output])
61
+ extras_create_video.click(fn=on_extras_create_video, inputs=[extras_images_folder, extras_fps, extras_chk_creategif], outputs=[extra_files_output])
62
+
63
+
64
+ def on_cut_video(files, cut_start_frame, cut_end_frame):
65
+ if files is None:
66
+ return None
67
+
68
+ resultfiles = []
69
+ for tf in files:
70
+ f = tf.name
71
+ destfile = util.get_destfilename_from_path(f, roop.globals.output_path, '_cut')
72
+ ffmpeg.cut_video(f, destfile, cut_start_frame, cut_end_frame)
73
+ if os.path.isfile(destfile):
74
+ resultfiles.append(destfile)
75
+ else:
76
+ gr.Error('Cutting video failed!')
77
+ return resultfiles
78
+
79
+
80
+ def on_join_videos(files, chk_encode):
81
+ if files is None:
82
+ return None
83
+
84
+ filenames = []
85
+ for f in files:
86
+ filenames.append(f.name)
87
+ destfile = util.get_destfilename_from_path(filenames[0], roop.globals.output_path, '_join')
88
+ sorted_filenames = util.sort_filenames_ignore_path(filenames)
89
+ ffmpeg.join_videos(sorted_filenames, destfile, not chk_encode)
90
+ resultfiles = []
91
+ if os.path.isfile(destfile):
92
+ resultfiles.append(destfile)
93
+ else:
94
+ gr.Error('Joining videos failed!')
95
+ return resultfiles
96
+
97
+
98
+
99
+ def on_extras_create_video(images_path,fps, create_gif):
100
+ util.sort_rename_frames(os.path.dirname(images_path))
101
+ destfilename = os.path.join(roop.globals.output_path, "img2video." + roop.globals.CFG.output_video_format)
102
+ ffmpeg.create_video('', destfilename, fps, images_path)
103
+ resultfiles = []
104
+ if os.path.isfile(destfilename):
105
+ resultfiles.append(destfilename)
106
+ else:
107
+ return None
108
+ if create_gif:
109
+ gifname = util.get_destfilename_from_path(destfilename, './output', '.gif')
110
+ ffmpeg.create_gif_from_video(destfilename, gifname)
111
+ if os.path.isfile(destfilename):
112
+ resultfiles.append(gifname)
113
+ return resultfiles
114
+
115
+
116
+ def on_extras_extract_frames(files):
117
+ if files is None:
118
+ return None
119
+
120
+ resultfiles = []
121
+ for tf in files:
122
+ f = tf.name
123
+ resfolder = ffmpeg.extract_frames(f)
124
+ for file in os.listdir(resfolder):
125
+ outfile = os.path.join(resfolder, file)
126
+ if os.path.isfile(outfile):
127
+ resultfiles.append(outfile)
128
+ return resultfiles
129
+
ui/tabs/facemgr_tab.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import cv2
4
+ import gradio as gr
5
+ import roop.utilities as util
6
+ import roop.globals
7
+ from roop.face_util import extract_face_images
8
+
9
+ selected_face_index = -1
10
+ thumbs = []
11
+ images = []
12
+
13
+
14
+ def facemgr_tab():
15
+ with gr.Tab("👨‍👩‍👧‍👦 Face Management"):
16
+ with gr.Row():
17
+ gr.Markdown("""
18
+ # Create blending facesets
19
+ Add multiple reference images into a faceset file.
20
+ """)
21
+ with gr.Row():
22
+ fb_facesetfile = gr.Files(label='Faceset', file_count='single', file_types=['.fsz'], interactive=True)
23
+ fb_files = gr.Files(label='Input Files', file_count="multiple", file_types=["image"], interactive=True)
24
+ with gr.Row():
25
+ with gr.Column():
26
+ gr.Button("👀 Open Output Folder", size='sm').click(fn=lambda: util.open_folder(roop.globals.output_path))
27
+ with gr.Column():
28
+ gr.Markdown(' ')
29
+ with gr.Row():
30
+ faces = gr.Gallery(label="Faces in this Faceset", allow_preview=True, preview=True, height=128, object_fit="scale-down")
31
+ with gr.Row():
32
+ fb_remove = gr.Button("Remove selected", variant='secondary')
33
+ fb_update = gr.Button("Create/Update Faceset file", variant='primary')
34
+ fb_clear = gr.Button("Clear all", variant='stop')
35
+
36
+ fb_facesetfile.change(fn=on_faceset_changed, inputs=[fb_facesetfile], outputs=[faces])
37
+ fb_files.change(fn=on_fb_files_changed, inputs=[fb_files], outputs=[faces])
38
+ fb_update.click(fn=on_update_clicked, outputs=[fb_facesetfile])
39
+ fb_remove.click(fn=on_remove_clicked, outputs=[faces])
40
+ fb_clear.click(fn=on_clear_clicked, outputs=[faces, fb_files, fb_facesetfile])
41
+ faces.select(fn=on_face_selected)
42
+
43
+ def on_faceset_changed(faceset, progress=gr.Progress()):
44
+ global thumbs, images
45
+
46
+ if faceset is None:
47
+ return thumbs
48
+
49
+ thumbs.clear()
50
+ filename = faceset.name
51
+
52
+ if filename.lower().endswith('fsz'):
53
+ progress(0, desc="Retrieving faces from Faceset File", )
54
+ unzipfolder = os.path.join(os.environ["TEMP"], 'faceset')
55
+ if os.path.isdir(unzipfolder):
56
+ shutil.rmtree(unzipfolder)
57
+ util.mkdir_with_umask(unzipfolder)
58
+ util.unzip(filename, unzipfolder)
59
+ for file in os.listdir(unzipfolder):
60
+ if file.endswith(".png"):
61
+ SELECTION_FACES_DATA = extract_face_images(os.path.join(unzipfolder,file), (False, 0), 0.5)
62
+ if len(SELECTION_FACES_DATA) < 1:
63
+ gr.Warning(f"No face detected in {file}!")
64
+ for f in SELECTION_FACES_DATA:
65
+ image = f[1]
66
+ images.append(image)
67
+ thumbs.append(util.convert_to_gradio(image))
68
+
69
+ return thumbs
70
+
71
+
72
+ def on_fb_files_changed(inputfiles, progress=gr.Progress()):
73
+ global thumbs, images
74
+
75
+ if inputfiles is None or len(inputfiles) < 1:
76
+ return thumbs
77
+
78
+ progress(0, desc="Retrieving faces from images", )
79
+ for f in inputfiles:
80
+ source_path = f.name
81
+ if util.has_image_extension(source_path):
82
+ roop.globals.source_path = source_path
83
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.source_path, (False, 0), 0.5)
84
+ for f in SELECTION_FACES_DATA:
85
+ image = f[1]
86
+ images.append(image)
87
+ thumbs.append(util.convert_to_gradio(image))
88
+ return thumbs
89
+
90
+ def on_face_selected(evt: gr.SelectData):
91
+ global selected_face_index
92
+
93
+ if evt is not None:
94
+ selected_face_index = evt.index
95
+
96
+ def on_remove_clicked():
97
+ global thumbs, images, selected_face_index
98
+
99
+ if len(thumbs) > selected_face_index:
100
+ f = thumbs.pop(selected_face_index)
101
+ del f
102
+ f = images.pop(selected_face_index)
103
+ del f
104
+ return thumbs
105
+
106
+ def on_clear_clicked():
107
+ global thumbs, images
108
+
109
+ thumbs.clear()
110
+ images.clear()
111
+ return thumbs, None, None
112
+
113
+
114
+
115
+
116
+
117
+ def on_update_clicked():
118
+ if len(images) < 1:
119
+ gr.Warning(f"No faces to create faceset from!")
120
+ return None
121
+
122
+ imgnames = []
123
+ for index,img in enumerate(images):
124
+ filename = os.path.join(roop.globals.output_path, f'{index}.png')
125
+ # if img.shape[0] != 512 or img.shape[1] != 512:
126
+ # cv2.imwrite(filename, resize_image_keep_content(img, 512, 512))
127
+ # removed resizing
128
+ cv2.imwrite(filename, img)
129
+ imgnames.append(filename)
130
+
131
+ finalzip = os.path.join(roop.globals.output_path, 'faceset.fsz')
132
+ util.zip(imgnames, finalzip)
133
+ return finalzip
134
+
135
+
ui/tabs/faceswap_tab.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import pathlib
4
+ import gradio as gr
5
+ import roop.utilities as util
6
+ import roop.globals
7
+ import ui.globals
8
+ from roop.face_util import extract_face_images
9
+ from roop.capturer import get_video_frame, get_video_frame_total, get_image_frame
10
+ from roop.ProcessEntry import ProcessEntry
11
+ from roop.FaceSet import FaceSet
12
+
13
+ last_image = None
14
+
15
+
16
+ IS_INPUT = True
17
+ SELECTED_FACE_INDEX = 0
18
+
19
+ SELECTED_INPUT_FACE_INDEX = 0
20
+ SELECTED_TARGET_FACE_INDEX = 0
21
+
22
+ input_faces = None
23
+ target_faces = None
24
+ face_selection = None
25
+
26
+ selected_preview_index = 0
27
+
28
+ is_processing = False
29
+
30
+ list_files_process : list[ProcessEntry] = []
31
+ no_face_choices = ["Use untouched original frame","Retry rotated", "Skip Frame"]
32
+
33
+
34
+ def faceswap_tab():
35
+ global no_face_choices
36
+
37
+ with gr.Tab("🎭 Face Swap"):
38
+ with gr.Row(variant='panel'):
39
+ with gr.Column(scale=2):
40
+ with gr.Row():
41
+ with gr.Column(min_width=160):
42
+ input_faces = gr.Gallery(label="Input faces", allow_preview=True, preview=True, height=128, object_fit="scale-down")
43
+ with gr.Accordion(label="Advanced Settings", open=False):
44
+ mask_top = gr.Slider(0, 256, value=0, label="Offset Face Top", step=1.0, interactive=True)
45
+ mask_bottom = gr.Slider(0, 256, value=0, label="Offset Face Bottom", step=1.0, interactive=True)
46
+ bt_remove_selected_input_face = gr.Button("❌ Remove selected", size='sm')
47
+ bt_clear_input_faces = gr.Button("💥 Clear all", variant='stop', size='sm')
48
+ with gr.Column(min_width=160):
49
+ target_faces = gr.Gallery(label="Target faces", allow_preview=True, preview=True, height=128, object_fit="scale-down")
50
+ bt_remove_selected_target_face = gr.Button("❌ Remove selected", size='sm')
51
+ bt_add_local = gr.Button('Add local files from', size='sm')
52
+ local_folder = gr.Textbox(show_label=False, placeholder="/content/", interactive=True)
53
+ with gr.Row(variant='panel'):
54
+ bt_srcfiles = gr.Files(label='Source File(s)', file_count="multiple", file_types=["image", ".fsz"], elem_id='filelist', height=233)
55
+ bt_destfiles = gr.Files(label='Target File(s)', file_count="multiple", file_types=["image", "video"], elem_id='filelist', height=233)
56
+ with gr.Row(variant='panel'):
57
+ gr.Markdown('')
58
+ forced_fps = gr.Slider(minimum=0, maximum=120, value=0, label="Video FPS", info='Overrides detected fps if not 0', step=1.0, interactive=True, container=True)
59
+
60
+ with gr.Column(scale=2):
61
+ previewimage = gr.Image(label="Preview Image", height=576, interactive=False)
62
+ with gr.Row(variant='panel'):
63
+ fake_preview = gr.Checkbox(label="Face swap frames", value=False)
64
+ bt_refresh_preview = gr.Button("🔄 Refresh", variant='secondary', size='sm')
65
+ bt_use_face_from_preview = gr.Button("Use Face from this Frame", variant='primary', size='sm')
66
+ with gr.Row():
67
+ preview_frame_num = gr.Slider(0, 0, value=0, label="Frame Number", step=1.0, interactive=True)
68
+ with gr.Row():
69
+ text_frame_clip = gr.Markdown('Processing frame range [0 - 0]')
70
+ set_frame_start = gr.Button("⬅ Set as Start", size='sm')
71
+ set_frame_end = gr.Button("➡ Set as End", size='sm')
72
+ with gr.Row(visible=False) as dynamic_face_selection:
73
+ with gr.Column(scale=2):
74
+ face_selection = gr.Gallery(label="Detected faces", allow_preview=True, preview=True, height=256, object_fit="scale-down")
75
+ with gr.Column():
76
+ bt_faceselect = gr.Button("☑ Use selected face", size='sm')
77
+ bt_cancelfaceselect = gr.Button("Done", size='sm')
78
+ with gr.Column():
79
+ gr.Markdown(' ')
80
+
81
+ with gr.Row(variant='panel'):
82
+ with gr.Column(scale=1):
83
+ selected_face_detection = gr.Dropdown(["First found", "All faces", "Selected face", "All female", "All male"], value="First found", label="Select face selection for swapping")
84
+ max_face_distance = gr.Slider(0.01, 1.0, value=0.65, label="Max Face Similarity Threshold")
85
+ video_swapping_method = gr.Dropdown(["Extract Frames to media","In-Memory processing"], value="In-Memory processing", label="Select video processing method", interactive=True)
86
+ no_face_action = gr.Dropdown(choices=no_face_choices, value=no_face_choices[0], label="Action on no face detected", interactive=True)
87
+ vr_mode = gr.Checkbox(label="VR Mode", value=False)
88
+ with gr.Column(scale=1):
89
+ ui.globals.ui_selected_enhancer = gr.Dropdown(["None", "Codeformer", "DMDNet", "GFPGAN", "GPEN", "Restoreformer"], value="None", label="Select post-processing")
90
+ ui.globals.ui_blend_ratio = gr.Slider(0.0, 1.0, value=0.65, label="Original/Enhanced image blend ratio")
91
+ with gr.Box():
92
+ autorotate = gr.Checkbox(label="Auto rotate horizontal Faces", value=True)
93
+ roop.globals.skip_audio = gr.Checkbox(label="Skip audio", value=False)
94
+ roop.globals.keep_frames = gr.Checkbox(label="Keep Frames (relevant only when extracting frames)", value=False)
95
+ roop.globals.wait_after_extraction = gr.Checkbox(label="Wait for user key press before creating video ", value=False)
96
+ with gr.Column(scale=1):
97
+ chk_useclip = gr.Checkbox(label="Use Text Masking", value=False)
98
+ clip_text = gr.Textbox(label="List of objects to mask and restore back on fake image", value="cup,hands,hair,banana" ,elem_id='tooltip')
99
+ gr.Dropdown(["Clip2Seg"], value="Clip2Seg", label="Engine")
100
+ bt_preview_mask = gr.Button("👥 Show Mask Preview", variant='secondary')
101
+
102
+ with gr.Row(variant='panel'):
103
+ with gr.Column():
104
+ bt_start = gr.Button("▶ Start", variant='primary')
105
+ gr.Button("👀 Open Output Folder", size='sm').click(fn=lambda: util.open_folder(roop.globals.output_path))
106
+ with gr.Column():
107
+ bt_stop = gr.Button("⏹ Stop", variant='secondary')
108
+ with gr.Column(scale=2):
109
+ gr.Markdown(' ')
110
+ with gr.Row(variant='panel'):
111
+ with gr.Column():
112
+ resultfiles = gr.Files(label='Processed File(s)', interactive=False)
113
+ with gr.Column():
114
+ resultimage = gr.Image(type='filepath', label='Final Image', interactive=False )
115
+ resultvideo = gr.Video(label='Final Video', interactive=False, visible=False)
116
+
117
+ previewinputs = [preview_frame_num, bt_destfiles, fake_preview, ui.globals.ui_selected_enhancer, selected_face_detection,
118
+ max_face_distance, ui.globals.ui_blend_ratio, chk_useclip, clip_text, no_face_action, vr_mode, autorotate]
119
+ input_faces.select(on_select_input_face, None, None).then(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top, mask_bottom])
120
+ bt_remove_selected_input_face.click(fn=remove_selected_input_face, outputs=[input_faces])
121
+ bt_srcfiles.change(fn=on_srcfile_changed, show_progress='full', inputs=bt_srcfiles, outputs=[dynamic_face_selection, face_selection, input_faces])
122
+
123
+ mask_top.input(fn=on_mask_top_changed, inputs=[mask_top], show_progress='hidden')
124
+ mask_bottom.input(fn=on_mask_bottom_changed, inputs=[mask_bottom], show_progress='hidden')
125
+
126
+
127
+ target_faces.select(on_select_target_face, None, None)
128
+ bt_remove_selected_target_face.click(fn=remove_selected_target_face, outputs=[target_faces])
129
+
130
+ forced_fps.change(fn=on_fps_changed, inputs=[forced_fps], show_progress='hidden')
131
+ bt_destfiles.change(fn=on_destfiles_changed, inputs=[bt_destfiles], outputs=[preview_frame_num, text_frame_clip], show_progress='hidden').then(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top, mask_bottom], show_progress='full')
132
+ bt_destfiles.select(fn=on_destfiles_selected, outputs=[preview_frame_num, text_frame_clip, forced_fps], show_progress='hidden').then(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top, mask_bottom], show_progress='hidden')
133
+ bt_destfiles.clear(fn=on_clear_destfiles, outputs=[target_faces])
134
+ resultfiles.select(fn=on_resultfiles_selected, inputs=[resultfiles], outputs=[resultimage, resultvideo])
135
+
136
+ face_selection.select(on_select_face, None, None)
137
+ bt_faceselect.click(fn=on_selected_face, outputs=[input_faces, target_faces, selected_face_detection])
138
+ bt_cancelfaceselect.click(fn=on_end_face_selection, outputs=[dynamic_face_selection, face_selection])
139
+
140
+ bt_clear_input_faces.click(fn=on_clear_input_faces, outputs=[input_faces])
141
+
142
+
143
+ bt_add_local.click(fn=on_add_local_folder, inputs=[local_folder], outputs=[bt_destfiles])
144
+ bt_preview_mask.click(fn=on_preview_mask, inputs=[preview_frame_num, bt_destfiles, clip_text], outputs=[previewimage])
145
+
146
+ start_event = bt_start.click(fn=start_swap,
147
+ inputs=[ui.globals.ui_selected_enhancer, selected_face_detection, roop.globals.keep_frames, roop.globals.wait_after_extraction,
148
+ roop.globals.skip_audio, max_face_distance, ui.globals.ui_blend_ratio, chk_useclip, clip_text,video_swapping_method, no_face_action, vr_mode, autorotate],
149
+ outputs=[bt_start, resultfiles])
150
+ after_swap_event = start_event.then(fn=on_resultfiles_finished, inputs=[resultfiles], outputs=[resultimage, resultvideo])
151
+
152
+ bt_stop.click(fn=stop_swap, cancels=[start_event, after_swap_event], queue=False)
153
+
154
+ bt_refresh_preview.click(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top, mask_bottom])
155
+ fake_preview.change(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top, mask_bottom])
156
+ preview_frame_num.change(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top, mask_bottom], show_progress='hidden')
157
+ bt_use_face_from_preview.click(fn=on_use_face_from_selected, show_progress='full', inputs=[bt_destfiles, preview_frame_num], outputs=[dynamic_face_selection, face_selection, target_faces, selected_face_detection])
158
+ set_frame_start.click(fn=on_set_frame, inputs=[set_frame_start, preview_frame_num], outputs=[text_frame_clip])
159
+ set_frame_end.click(fn=on_set_frame, inputs=[set_frame_end, preview_frame_num], outputs=[text_frame_clip])
160
+
161
+
162
+
163
+ def on_mask_top_changed(mask_offset):
164
+ global SELECTED_INPUT_FACE_INDEX
165
+
166
+ if len(roop.globals.INPUT_FACESETS) > SELECTED_INPUT_FACE_INDEX:
167
+ roop.globals.INPUT_FACESETS[SELECTED_INPUT_FACE_INDEX].faces[0].mask_offsets[0] = mask_offset
168
+
169
+ def on_mask_bottom_changed(mask_offset):
170
+ global SELECTED_INPUT_FACE_INDEX
171
+
172
+ if len(roop.globals.INPUT_FACESETS) > SELECTED_INPUT_FACE_INDEX:
173
+ roop.globals.INPUT_FACESETS[SELECTED_INPUT_FACE_INDEX].faces[0].mask_offsets[1] = mask_offset
174
+
175
+
176
+
177
+
178
+ def on_add_local_folder(folder):
179
+ files = util.get_local_files_from_folder(folder)
180
+ if files is None:
181
+ gr.Warning("Empty folder or folder not found!")
182
+ return files
183
+
184
+
185
+ def on_srcfile_changed(srcfiles, progress=gr.Progress()):
186
+ from roop.face_util import norm_crop2
187
+ global SELECTION_FACES_DATA, IS_INPUT, input_faces, face_selection, last_image
188
+
189
+ IS_INPUT = True
190
+
191
+ if srcfiles is None or len(srcfiles) < 1:
192
+ return gr.Column.update(visible=False), None, ui.globals.ui_input_thumbs
193
+
194
+ thumbs = []
195
+ for f in srcfiles:
196
+ source_path = f.name
197
+ if source_path.lower().endswith('fsz'):
198
+ progress(0, desc="Retrieving faces from Faceset File", )
199
+ unzipfolder = os.path.join(os.environ["TEMP"], 'faceset')
200
+ if os.path.isdir(unzipfolder):
201
+ files = os.listdir(unzipfolder)
202
+ for file in files:
203
+ os.remove(os.path.join(unzipfolder, file))
204
+ else:
205
+ os.makedirs(unzipfolder)
206
+ util.mkdir_with_umask(unzipfolder)
207
+ util.unzip(source_path, unzipfolder)
208
+ is_first = True
209
+ face_set = FaceSet()
210
+ for file in os.listdir(unzipfolder):
211
+ if file.endswith(".png"):
212
+ filename = os.path.join(unzipfolder,file)
213
+ progress.update()
214
+ SELECTION_FACES_DATA = extract_face_images(filename, (False, 0))
215
+ for f in SELECTION_FACES_DATA:
216
+ face = f[0]
217
+ face.mask_offsets = (0,0)
218
+ face_set.faces.append(face)
219
+ if is_first:
220
+ image = util.convert_to_gradio(f[1])
221
+ ui.globals.ui_input_thumbs.append(image)
222
+ is_first = False
223
+ face_set.ref_images.append(get_image_frame(filename))
224
+ if len(face_set.faces) > 0:
225
+ if len(face_set.faces) > 1:
226
+ face_set.AverageEmbeddings()
227
+ roop.globals.INPUT_FACESETS.append(face_set)
228
+
229
+ elif util.has_image_extension(source_path):
230
+ progress(0, desc="Retrieving faces from image", )
231
+ roop.globals.source_path = source_path
232
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.source_path, (False, 0))
233
+ progress(0.5, desc="Retrieving faces from image")
234
+ for f in SELECTION_FACES_DATA:
235
+ face_set = FaceSet()
236
+ face = f[0]
237
+ face.mask_offsets = (0,0)
238
+ face_set.faces.append(face)
239
+ image = util.convert_to_gradio(f[1])
240
+ ui.globals.ui_input_thumbs.append(image)
241
+ roop.globals.INPUT_FACESETS.append(face_set)
242
+
243
+ progress(1.0)
244
+
245
+ # old style with selecting input faces commented out
246
+ # if len(thumbs) < 1:
247
+ # return gr.Column.update(visible=False), None, ui.globals.ui_input_thumbs
248
+ # return gr.Column.update(visible=True), thumbs, gr.Gallery.update(visible=True)
249
+
250
+ return gr.Column.update(visible=False), None, ui.globals.ui_input_thumbs
251
+
252
+
253
+ def on_select_input_face(evt: gr.SelectData):
254
+ global SELECTED_INPUT_FACE_INDEX
255
+
256
+ SELECTED_INPUT_FACE_INDEX = evt.index
257
+
258
+
259
+ def remove_selected_input_face():
260
+ global SELECTED_INPUT_FACE_INDEX
261
+
262
+ if len(roop.globals.INPUT_FACESETS) > SELECTED_INPUT_FACE_INDEX:
263
+ f = roop.globals.INPUT_FACESETS.pop(SELECTED_INPUT_FACE_INDEX)
264
+ del f
265
+ if len(ui.globals.ui_input_thumbs) > SELECTED_INPUT_FACE_INDEX:
266
+ f = ui.globals.ui_input_thumbs.pop(SELECTED_INPUT_FACE_INDEX)
267
+ del f
268
+
269
+ return ui.globals.ui_input_thumbs
270
+
271
+ def on_select_target_face(evt: gr.SelectData):
272
+ global SELECTED_TARGET_FACE_INDEX
273
+
274
+ SELECTED_TARGET_FACE_INDEX = evt.index
275
+
276
+ def remove_selected_target_face():
277
+ if len(roop.globals.TARGET_FACES) > SELECTED_TARGET_FACE_INDEX:
278
+ f = roop.globals.TARGET_FACES.pop(SELECTED_TARGET_FACE_INDEX)
279
+ del f
280
+ if len(ui.globals.ui_target_thumbs) > SELECTED_TARGET_FACE_INDEX:
281
+ f = ui.globals.ui_target_thumbs.pop(SELECTED_TARGET_FACE_INDEX)
282
+ del f
283
+ return ui.globals.ui_target_thumbs
284
+
285
+
286
+
287
+
288
+
289
+ def on_use_face_from_selected(files, frame_num):
290
+ global IS_INPUT, SELECTION_FACES_DATA
291
+
292
+ IS_INPUT = False
293
+ thumbs = []
294
+
295
+ roop.globals.target_path = files[selected_preview_index].name
296
+ if util.is_image(roop.globals.target_path) and not roop.globals.target_path.lower().endswith(('gif')):
297
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.target_path, (False, 0))
298
+ if len(SELECTION_FACES_DATA) > 0:
299
+ for f in SELECTION_FACES_DATA:
300
+ image = util.convert_to_gradio(f[1])
301
+ thumbs.append(image)
302
+ else:
303
+ gr.Info('No faces detected!')
304
+ roop.globals.target_path = None
305
+
306
+ elif util.is_video(roop.globals.target_path) or roop.globals.target_path.lower().endswith(('gif')):
307
+ selected_frame = frame_num
308
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.target_path, (True, selected_frame))
309
+ if len(SELECTION_FACES_DATA) > 0:
310
+ for f in SELECTION_FACES_DATA:
311
+ image = util.convert_to_gradio(f[1])
312
+ thumbs.append(image)
313
+ else:
314
+ gr.Info('No faces detected!')
315
+ roop.globals.target_path = None
316
+
317
+ if len(thumbs) == 1:
318
+ roop.globals.TARGET_FACES.append(SELECTION_FACES_DATA[0][0])
319
+ ui.globals.ui_target_thumbs.append(thumbs[0])
320
+ return gr.Row.update(visible=False), None, ui.globals.ui_target_thumbs, gr.Dropdown.update(value='Selected face')
321
+
322
+ return gr.Row.update(visible=True), thumbs, gr.Gallery.update(visible=True), gr.Dropdown.update(visible=True)
323
+
324
+
325
+
326
+ def on_select_face(evt: gr.SelectData): # SelectData is a subclass of EventData
327
+ global SELECTED_FACE_INDEX
328
+ SELECTED_FACE_INDEX = evt.index
329
+
330
+
331
+ def on_selected_face():
332
+ global IS_INPUT, SELECTED_FACE_INDEX, SELECTION_FACES_DATA
333
+
334
+ fd = SELECTION_FACES_DATA[SELECTED_FACE_INDEX]
335
+ image = util.convert_to_gradio(fd[1])
336
+ if IS_INPUT:
337
+ face_set = FaceSet()
338
+ fd[0].mask_offsets = (0,0)
339
+ face_set.faces.append(fd[0])
340
+ roop.globals.INPUT_FACESETS.append(face_set)
341
+ ui.globals.ui_input_thumbs.append(image)
342
+ return ui.globals.ui_input_thumbs, gr.Gallery.update(visible=True), gr.Dropdown.update(visible=True)
343
+ else:
344
+ roop.globals.TARGET_FACES.append(fd[0])
345
+ ui.globals.ui_target_thumbs.append(image)
346
+ return gr.Gallery.update(visible=True), ui.globals.ui_target_thumbs, gr.Dropdown.update(value='Selected face')
347
+
348
+ # bt_faceselect.click(fn=on_selected_face, outputs=[dynamic_face_selection, face_selection, input_faces, target_faces])
349
+
350
+ def on_end_face_selection():
351
+ return gr.Column.update(visible=False), None
352
+
353
+
354
+ def on_preview_frame_changed(frame_num, files, fake_preview, enhancer, detection, face_distance, blend_ratio, use_clip, clip_text, no_face_action, vr_mode, auto_rotate):
355
+ global SELECTED_INPUT_FACE_INDEX, is_processing
356
+
357
+ from roop.core import live_swap
358
+
359
+ mask_offsets = (0,0)
360
+ if len(roop.globals.INPUT_FACESETS) > SELECTED_INPUT_FACE_INDEX:
361
+ if not hasattr(roop.globals.INPUT_FACESETS[SELECTED_INPUT_FACE_INDEX].faces[0], 'mask_offsets'):
362
+ roop.globals.INPUT_FACESETS[SELECTED_INPUT_FACE_INDEX].faces[0].mask_offsets = mask_offsets
363
+ mask_offsets = roop.globals.INPUT_FACESETS[SELECTED_INPUT_FACE_INDEX].faces[0].mask_offsets
364
+
365
+ if is_processing or files is None or selected_preview_index >= len(files) or frame_num is None:
366
+ return None, mask_offsets[0], mask_offsets[1]
367
+
368
+ filename = files[selected_preview_index].name
369
+ # time.sleep(0.3)
370
+ if util.is_video(filename) or filename.lower().endswith('gif'):
371
+ current_frame = get_video_frame(filename, frame_num)
372
+ else:
373
+ current_frame = get_image_frame(filename)
374
+ if current_frame is None:
375
+ return None, mask_offsets[0], mask_offsets[1]
376
+
377
+
378
+ if not fake_preview or len(roop.globals.INPUT_FACESETS) < 1:
379
+ return util.convert_to_gradio(current_frame), mask_offsets[0], mask_offsets[1]
380
+
381
+ roop.globals.face_swap_mode = translate_swap_mode(detection)
382
+ roop.globals.selected_enhancer = enhancer
383
+ roop.globals.distance_threshold = face_distance
384
+ roop.globals.blend_ratio = blend_ratio
385
+ roop.globals.no_face_action = index_of_no_face_action(no_face_action)
386
+ roop.globals.vr_mode = vr_mode
387
+ roop.globals.autorotate_faces = auto_rotate
388
+
389
+ if use_clip and clip_text is None or len(clip_text) < 1:
390
+ use_clip = False
391
+
392
+ roop.globals.execution_threads = roop.globals.CFG.max_threads
393
+ current_frame = live_swap(current_frame, roop.globals.face_swap_mode, use_clip, clip_text, SELECTED_INPUT_FACE_INDEX)
394
+ if current_frame is None:
395
+ return None, mask_offsets[0], mask_offsets[1]
396
+ return util.convert_to_gradio(current_frame), mask_offsets[0], mask_offsets[1]
397
+
398
+
399
+ def gen_processing_text(start, end):
400
+ return f'Processing frame range [{start} - {end}]'
401
+
402
+ def on_set_frame(sender:str, frame_num):
403
+ global selected_preview_index, list_files_process
404
+
405
+ idx = selected_preview_index
406
+ if list_files_process[idx].endframe == 0:
407
+ return gen_processing_text(0,0)
408
+
409
+ start = list_files_process[idx].startframe
410
+ end = list_files_process[idx].endframe
411
+ if sender.lower().endswith('start'):
412
+ list_files_process[idx].startframe = min(frame_num, end)
413
+ else:
414
+ list_files_process[idx].endframe = max(frame_num, start)
415
+
416
+ return gen_processing_text(list_files_process[idx].startframe,list_files_process[idx].endframe)
417
+
418
+
419
+
420
+ def on_preview_mask(frame_num, files, clip_text):
421
+ from roop.core import preview_mask
422
+ global is_processing
423
+
424
+ if is_processing:
425
+ return None
426
+
427
+ filename = files[selected_preview_index].name
428
+ if util.is_video(filename) or filename.lower().endswith('gif'):
429
+ current_frame = get_video_frame(filename, frame_num)
430
+ else:
431
+ current_frame = get_image_frame(filename)
432
+ if current_frame is None:
433
+ return None
434
+
435
+ current_frame = preview_mask(current_frame, clip_text)
436
+ return util.convert_to_gradio(current_frame)
437
+
438
+
439
+ def on_clear_input_faces():
440
+ ui.globals.ui_input_thumbs.clear()
441
+ roop.globals.INPUT_FACESETS.clear()
442
+ return ui.globals.ui_input_thumbs
443
+
444
+ def on_clear_destfiles():
445
+ roop.globals.TARGET_FACES.clear()
446
+ ui.globals.ui_target_thumbs.clear()
447
+ return ui.globals.ui_target_thumbs
448
+
449
+
450
+ def index_of_no_face_action(dropdown_text):
451
+ global no_face_choices
452
+
453
+ return no_face_choices.index(dropdown_text)
454
+
455
+ def translate_swap_mode(dropdown_text):
456
+ if dropdown_text == "Selected face":
457
+ return "selected"
458
+ elif dropdown_text == "First found":
459
+ return "first"
460
+ elif dropdown_text == "Single face frames only [auto-rotate]":
461
+ return "single_face_frames_only"
462
+ elif dropdown_text == "All female":
463
+ return "all_female"
464
+ elif dropdown_text == "All male":
465
+ return "all_male"
466
+
467
+ return "all"
468
+
469
+
470
+
471
+ def start_swap( enhancer, detection, keep_frames, wait_after_extraction, skip_audio, face_distance, blend_ratio,
472
+ use_clip, clip_text, processing_method, no_face_action, vr_mode, autorotate, progress=gr.Progress(track_tqdm=False)):
473
+ from ui.main import prepare_environment
474
+ from roop.core import batch_process
475
+ global is_processing, list_files_process
476
+
477
+ if list_files_process is None or len(list_files_process) <= 0:
478
+ return gr.Button.update(variant="primary"), None
479
+
480
+ if roop.globals.CFG.clear_output:
481
+ shutil.rmtree(roop.globals.output_path)
482
+
483
+
484
+ prepare_environment()
485
+
486
+ roop.globals.selected_enhancer = enhancer
487
+ roop.globals.target_path = None
488
+ roop.globals.distance_threshold = face_distance
489
+ roop.globals.blend_ratio = blend_ratio
490
+ roop.globals.keep_frames = keep_frames
491
+ roop.globals.wait_after_extraction = wait_after_extraction
492
+ roop.globals.skip_audio = skip_audio
493
+ roop.globals.face_swap_mode = translate_swap_mode(detection)
494
+ roop.globals.no_face_action = index_of_no_face_action(no_face_action)
495
+ roop.globals.vr_mode = vr_mode
496
+ roop.globals.autorotate_faces = autorotate
497
+ if use_clip and clip_text is None or len(clip_text) < 1:
498
+ use_clip = False
499
+
500
+ if roop.globals.face_swap_mode == 'selected':
501
+ if len(roop.globals.TARGET_FACES) < 1:
502
+ gr.Error('No Target Face selected!')
503
+ return gr.Button.update(variant="primary"), None
504
+
505
+ is_processing = True
506
+ yield gr.Button.update(variant="secondary"), None
507
+ roop.globals.execution_threads = roop.globals.CFG.max_threads
508
+ roop.globals.video_encoder = roop.globals.CFG.output_video_codec
509
+ roop.globals.video_quality = roop.globals.CFG.video_quality
510
+ roop.globals.max_memory = roop.globals.CFG.memory_limit if roop.globals.CFG.memory_limit > 0 else None
511
+
512
+ batch_process(list_files_process, use_clip, clip_text, processing_method == "In-Memory processing", progress)
513
+ is_processing = False
514
+ outdir = pathlib.Path(roop.globals.output_path)
515
+ outfiles = [item for item in outdir.rglob("*") if item.is_file()]
516
+ if len(outfiles) > 0:
517
+ yield gr.Button.update(variant="primary"),gr.Files.update(value=outfiles)
518
+ else:
519
+ yield gr.Button.update(variant="primary"),None
520
+
521
+
522
+ def stop_swap():
523
+ roop.globals.processing = False
524
+ gr.Info('Aborting processing - please wait for the remaining threads to be stopped')
525
+
526
+
527
+ def on_fps_changed(fps):
528
+ global selected_preview_index, list_files_process
529
+
530
+ if len(list_files_process) < 1 or list_files_process[selected_preview_index].endframe < 1:
531
+ return
532
+ list_files_process[selected_preview_index].fps = fps
533
+
534
+
535
+ def on_destfiles_changed(destfiles):
536
+ global selected_preview_index, list_files_process
537
+
538
+ if destfiles is None or len(destfiles) < 1:
539
+ list_files_process.clear()
540
+ return gr.Slider.update(value=0, maximum=0), ''
541
+
542
+ for f in destfiles:
543
+ list_files_process.append(ProcessEntry(f.name, 0,0, 0))
544
+
545
+ selected_preview_index = 0
546
+ idx = selected_preview_index
547
+
548
+ filename = list_files_process[idx].filename
549
+
550
+ if util.is_video(filename) or filename.lower().endswith('gif'):
551
+ total_frames = get_video_frame_total(filename)
552
+ else:
553
+ total_frames = 0
554
+ list_files_process[idx].endframe = total_frames
555
+ if total_frames > 0:
556
+ return gr.Slider.update(value=0, maximum=total_frames), gen_processing_text(list_files_process[idx].startframe,list_files_process[idx].endframe)
557
+ return gr.Slider.update(value=0, maximum=total_frames), ''
558
+
559
+
560
+
561
+
562
+ def on_destfiles_selected(evt: gr.SelectData):
563
+ global selected_preview_index, list_files_process
564
+
565
+ if evt is not None:
566
+ selected_preview_index = evt.index
567
+ idx = selected_preview_index
568
+ filename = list_files_process[idx].filename
569
+ fps = list_files_process[idx].fps
570
+ if util.is_video(filename) or filename.lower().endswith('gif'):
571
+ total_frames = get_video_frame_total(filename)
572
+ if list_files_process[idx].endframe == 0:
573
+ list_files_process[idx].endframe = total_frames
574
+ else:
575
+ total_frames = 0
576
+
577
+ if total_frames > 0:
578
+ return gr.Slider.update(value=list_files_process[idx].startframe, maximum=total_frames), gen_processing_text(list_files_process[idx].startframe,list_files_process[idx].endframe), fps
579
+ return gr.Slider.update(value=0, maximum=total_frames), gen_processing_text(0,0), fps
580
+
581
+
582
+
583
+
584
+ def on_resultfiles_selected(evt: gr.SelectData, files):
585
+ selected_index = evt.index
586
+ filename = files[selected_index].name
587
+ if util.is_video(filename):
588
+ return gr.update(visible=False), gr.update(visible=True, value=filename)
589
+ else:
590
+ if filename.lower().endswith('gif'):
591
+ current_frame = get_video_frame(filename)
592
+ else:
593
+ current_frame = get_image_frame(filename)
594
+ return gr.update(visible=True, value=util.convert_to_gradio(current_frame)), gr.update(visible=False)
595
+
596
+
597
+
598
+ def on_resultfiles_finished(files):
599
+ selected_index = 0
600
+ if files is None or len(files) < 1:
601
+ return None, None
602
+
603
+ filename = files[selected_index].name
604
+ if util.is_video(filename):
605
+ return gr.update(visible=False), gr.update(visible=True, value=filename)
606
+ else:
607
+ if filename.lower().endswith('gif'):
608
+ current_frame = get_video_frame(filename)
609
+ else:
610
+ current_frame = get_image_frame(filename)
611
+ return gr.update(visible=True, value=util.convert_to_gradio(current_frame)), gr.update(visible=False)
ui/tabs/livecam_tab.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import roop.globals
3
+ import ui.globals
4
+
5
+ fake_cam_image = None
6
+
7
+ current_cam_image = None
8
+ cam_swapping = False
9
+ camthread = None
10
+
11
+ def livecam_tab():
12
+ with gr.Tab("🎥 Live Cam"):
13
+ with gr.Row():
14
+ with gr.Column(scale=2):
15
+ cam_toggle = gr.Checkbox(label='Activate', value=ui.globals.ui_live_cam_active)
16
+ with gr.Column(scale=1):
17
+ vcam_toggle = gr.Checkbox(label='Stream to virtual camera', value=False)
18
+ with gr.Column(scale=1):
19
+ camera_num = gr.Slider(0, 2, value=0, label="Camera Number", step=1.0, interactive=True)
20
+
21
+ if ui.globals.ui_live_cam_active:
22
+ with gr.Row():
23
+ with gr.Column():
24
+ cam = gr.Webcam(label='Camera', source='webcam', interactive=True, streaming=False)
25
+ with gr.Column():
26
+ fake_cam_image = gr.Image(label='Fake Camera Output', interactive=False)
27
+
28
+ cam_toggle.change(fn=on_cam_toggle, inputs=[cam_toggle])
29
+
30
+ if ui.globals.ui_live_cam_active:
31
+ vcam_toggle.change(fn=on_vcam_toggle, inputs=[vcam_toggle, camera_num], outputs=[cam, fake_cam_image])
32
+ cam.stream(on_stream_swap_cam, inputs=[cam, ui.globals.ui_selected_enhancer, ui.globals.ui_blend_ratio], outputs=[fake_cam_image], preprocess=True, postprocess=True, show_progress="hidden")
33
+
34
+ def on_cam_toggle(state):
35
+ ui.globals.ui_live_cam_active = state
36
+ gr.Warning('Server will be restarted for this change!')
37
+ ui.globals.ui_restart_server = True
38
+
39
+ def on_vcam_toggle(state, num):
40
+ from roop.virtualcam import stop_virtual_cam, start_virtual_cam
41
+
42
+ if state:
43
+ yield gr.Webcam.update(interactive=False), None
44
+ start_virtual_cam(num)
45
+ return gr.Webcam.update(interactive=False), None
46
+ else:
47
+ stop_virtual_cam()
48
+ return gr.Webcam.update(interactive=True), None
49
+
50
+
51
+
52
+ def on_stream_swap_cam(camimage, enhancer, blend_ratio):
53
+ from roop.core import live_swap
54
+ global current_cam_image, cam_swapping, fake_cam_image
55
+
56
+ roop.globals.selected_enhancer = enhancer
57
+ roop.globals.blend_ratio = blend_ratio
58
+
59
+ if not cam_swapping:
60
+ cam_swapping = True
61
+ if len(roop.globals.INPUT_FACESETS) > 0:
62
+ current_cam_image = live_swap(camimage, "all", False, None, ui.globals.ui_SELECTED_INPUT_FACE_INDEX)
63
+ else:
64
+ current_cam_image = camimage
65
+ cam_swapping = False
66
+ return current_cam_image
67
+
68
+
ui/tabs/settings_tab.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ import os
3
+ import gradio as gr
4
+ import roop.globals
5
+ import ui.globals
6
+
7
+ available_themes = ["Default", "gradio/glass", "gradio/monochrome", "gradio/seafoam", "gradio/soft", "gstaff/xkcd", "freddyaboulton/dracula_revamped", "ysharma/steampunk"]
8
+ image_formats = ['jpg','png', 'webp']
9
+ video_formats = ['avi','mkv', 'mp4', 'webm']
10
+ video_codecs = ['libx264', 'libx265', 'libvpx-vp9', 'h264_nvenc', 'hevc_nvenc']
11
+ providerlist = None
12
+
13
+ settings_controls = []
14
+
15
+ def settings_tab():
16
+ from roop.core import suggest_execution_providers
17
+ global providerlist
18
+
19
+ providerlist = suggest_execution_providers()
20
+ with gr.Tab("⚙ Settings"):
21
+ with gr.Row():
22
+ with gr.Column():
23
+ themes = gr.Dropdown(available_themes, label="Theme", info="Change needs complete restart", value=roop.globals.CFG.selected_theme)
24
+ with gr.Column():
25
+ settings_controls.append(gr.Checkbox(label="Public Server", value=roop.globals.CFG.server_share, elem_id='server_share', interactive=True))
26
+ settings_controls.append(gr.Checkbox(label='Clear output folder before each run', value=roop.globals.CFG.clear_output, elem_id='clear_output', interactive=True))
27
+ output_template = gr.Textbox(label="Filename Output Template", info="(file extension is added automatically)", lines=1, placeholder='{file}_{time}', value=roop.globals.CFG.output_template)
28
+ with gr.Column():
29
+ input_server_name = gr.Textbox(label="Server Name", lines=1, info="Leave blank to run locally", value=roop.globals.CFG.server_name)
30
+ with gr.Column():
31
+ input_server_port = gr.Number(label="Server Port", precision=0, info="Leave at 0 to use default", value=roop.globals.CFG.server_port)
32
+ with gr.Row():
33
+ with gr.Column():
34
+ settings_controls.append(gr.Dropdown(providerlist, label="Provider", value=roop.globals.CFG.provider, elem_id='provider', interactive=True))
35
+ chk_det_size = gr.Checkbox(label="Use default Det-Size", value=True, elem_id='default_det_size', interactive=True)
36
+ settings_controls.append(gr.Checkbox(label="Force CPU for Face Analyser", value=roop.globals.CFG.force_cpu, elem_id='force_cpu', interactive=True))
37
+ max_threads = gr.Slider(1, 32, value=roop.globals.CFG.max_threads, label="Max. Number of Threads", info='default: 3', step=1.0, interactive=True)
38
+ with gr.Column():
39
+ memory_limit = gr.Slider(0, 128, value=roop.globals.CFG.memory_limit, label="Max. Memory to use (Gb)", info='0 meaning no limit', step=1.0, interactive=True)
40
+ settings_controls.append(gr.Dropdown(image_formats, label="Image Output Format", info='default: png', value=roop.globals.CFG.output_image_format, elem_id='output_image_format', interactive=True))
41
+ with gr.Column():
42
+ settings_controls.append(gr.Dropdown(video_codecs, label="Video Codec", info='default: libx264', value=roop.globals.CFG.output_video_codec, elem_id='output_video_codec', interactive=True))
43
+ settings_controls.append(gr.Dropdown(video_formats, label="Video Output Format", info='default: mp4', value=roop.globals.CFG.output_video_format, elem_id='output_video_format', interactive=True))
44
+ video_quality = gr.Slider(0, 100, value=roop.globals.CFG.video_quality, label="Video Quality (crf)", info='default: 14', step=1.0, interactive=True)
45
+ with gr.Column():
46
+ button_apply_restart = gr.Button("Restart Server", variant='primary')
47
+ with gr.Box():
48
+ settings_controls.append(gr.Checkbox(label='Start with active live cam', value=roop.globals.CFG.live_cam_start_active, elem_id='live_cam_start_active', interactive=True))
49
+ settings_controls.append(gr.Checkbox(label='Use OS temp folder', value=roop.globals.CFG.use_os_temp_folder, elem_id='use_os_temp_folder', interactive=True))
50
+ button_clean_temp = gr.Button("Clean temp folder")
51
+ button_apply_settings = gr.Button("Apply Settings")
52
+
53
+ chk_det_size.select(fn=on_option_changed)
54
+
55
+ # Settings
56
+ for s in settings_controls:
57
+ s.select(fn=on_settings_changed)
58
+ max_threads.input(fn=lambda a,b='max_threads':on_settings_changed_misc(a,b), inputs=[max_threads])
59
+ memory_limit.input(fn=lambda a,b='memory_limit':on_settings_changed_misc(a,b), inputs=[memory_limit])
60
+ video_quality.input(fn=lambda a,b='video_quality':on_settings_changed_misc(a,b), inputs=[video_quality])
61
+
62
+ # button_clean_temp.click(fn=clean_temp, outputs=[bt_srcfiles, input_faces, target_faces, bt_destfiles])
63
+ button_clean_temp.click(fn=clean_temp)
64
+ button_apply_settings.click(apply_settings, inputs=[themes, input_server_name, input_server_port, output_template])
65
+ button_apply_restart.click(restart)
66
+
67
+
68
+ def on_option_changed(evt: gr.SelectData):
69
+ attribname = evt.target.elem_id
70
+ if isinstance(evt.target, gr.Checkbox):
71
+ if hasattr(roop.globals, attribname):
72
+ setattr(roop.globals, attribname, evt.selected)
73
+ return
74
+ elif isinstance(evt.target, gr.Dropdown):
75
+ if hasattr(roop.globals, attribname):
76
+ setattr(roop.globals, attribname, evt.value)
77
+ return
78
+ raise gr.Error(f'Unhandled Setting for {evt.target}')
79
+
80
+
81
+ def on_settings_changed_misc(new_val, attribname):
82
+ if hasattr(roop.globals.CFG, attribname):
83
+ setattr(roop.globals.CFG, attribname, new_val)
84
+ else:
85
+ print("Didn't find attrib!")
86
+
87
+
88
+
89
+ def on_settings_changed(evt: gr.SelectData):
90
+ attribname = evt.target.elem_id
91
+ if isinstance(evt.target, gr.Checkbox):
92
+ if hasattr(roop.globals.CFG, attribname):
93
+ setattr(roop.globals.CFG, attribname, evt.selected)
94
+ return
95
+ elif isinstance(evt.target, gr.Dropdown):
96
+ if hasattr(roop.globals.CFG, attribname):
97
+ setattr(roop.globals.CFG, attribname, evt.value)
98
+ return
99
+
100
+ raise gr.Error(f'Unhandled Setting for {evt.target}')
101
+
102
+ def clean_temp():
103
+ from ui.main import prepare_environment
104
+
105
+ if not roop.globals.CFG.use_os_temp_folder:
106
+ shutil.rmtree(os.environ["TEMP"])
107
+ prepare_environment()
108
+
109
+ ui.globals.ui_input_thumbs.clear()
110
+ roop.globals.INPUT_FACESETS.clear()
111
+ roop.globals.TARGET_FACES.clear()
112
+ ui.globals.ui_target_thumbs = []
113
+ gr.Info('Temp Files removed')
114
+ return None,None,None,None
115
+
116
+
117
+ def apply_settings(themes, input_server_name, input_server_port, output_template):
118
+ from ui.main import show_msg
119
+
120
+ roop.globals.CFG.selected_theme = themes
121
+ roop.globals.CFG.server_name = input_server_name
122
+ roop.globals.CFG.server_port = input_server_port
123
+ roop.globals.CFG.output_template = output_template
124
+ roop.globals.CFG.save()
125
+ show_msg('Settings saved')
126
+
127
+
128
+ def restart():
129
+ ui.globals.ui_restart_server = True