Added ganonymization

This commit is contained in:
2025-07-21 18:16:35 +02:00
parent 26b0cb79b7
commit b909c103e4
456 changed files with 19859 additions and 5 deletions
@@ -0,0 +1,54 @@
# FILES
*.yaml
*.pkl
*.flist
*.zip
*.out
*.npy
*.gz
*.ckpt
*.pth
*.log
*.pyc
*.csv
*.yml
*.ods
*.ods#
*.json
build_docker.sh
# Images / Videos
#*.png
#*.jpg
*.jpeg
*.m4a
*.mkv
*.mp4
# Directories created by inpaintron
.cache/
test_examples/
.vscode
__pycache__
.debug/
**/.ipynb_checkpoints/**
outputs/
# From pip setup
build/
*.egg-info
*.egg
.npm/
# From dockerfile
.bash_history
.viminfo
.local/
*.pickle
*.onnx
sbatch_files/
figures/
image_dump/
@@ -0,0 +1,6 @@
Collecting av
Using cached av-15.0.0.tar.gz (3.8 MB)
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'error'
@@ -0,0 +1,13 @@
# Changelog
## 23.03.2023
- Quality of life improvements
- Add support for refined keypoints for the FDH dataset.
- Add FDF128 dataset loader with webdataset.
- Support for using detector and anonymizer from DeepPrivacy1.
- Update visualization of keypoints
- Fix bug for upsampling/downsampling in the anonymization pipeline.
- Support for keypoint-guided face anonymization.
- Add ViTPose + Mask-RCNN detection model for keypoint-guided full-body anonymization.
- Set caching of detections to False as default, as it can produce unexpected behaviour. For example, using a different score threshold requires re-run of detector.
- Add Gradio Demos for face and body anonymization
@@ -0,0 +1,50 @@
FROM nvcr.io/nvidia/pytorch:22.08-py3
ARG BASE_IMAGE=nvcr.io/nvidia/pytorch:24.03-py3 # new variable
FROM ${BASE_IMAGE}
ARG UID=1000
ARG UNAME=testuser
ARG WANDB_API_KEY
RUN useradd -ms /bin/bash -u $UID $UNAME && \
mkdir -p /home/${UNAME} &&\
chown -R $UID /home/${UNAME}
WORKDIR /home/${UNAME}
ENV DEBIAN_FRONTEND="noninteractive"
ENV WANDB_API_KEY=$WANDB_API_KEY
ENV TORCH_HOME=/home/${UNAME}/.cache
# OPTIONAL - DeepPrivacy2 uses these environment variables to set directories outside the current working directory
#ENV BASE_DATASET_DIR=/work/haakohu/datasets
#ENV BASE_OUTPUT_DIR=/work/haakohu/outputs
#ENV FBA_METRICS_CACHE=/work/haakohu/metrics_cache
RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 qt5-default -y
RUN pip install git+https://github.com/facebookresearch/detectron2@96c752ce821a3340e27edd51c28a00665dd32a30#subdirectory=projects/DensePose
COPY setup.py setup.py
RUN pip install \
numpy>=1.20 \
matplotlib \
cython \
tensorboard \
tqdm \
ninja==1.10.2 \
opencv-python-headless==4.5.5.64 \
ftfy==6.1.3 \
moviepy \
pyspng \
git+https://github.com/hukkelas/DSFD-Pytorch-Inference \
wandb \
termcolor \
git+https://github.com/hukkelas/torch_ops.git \
git+https://github.com/wmuron/motpy@c77f85d27e371c0a298e9a88ca99292d9b9cbe6b \
fast_pytorch_kmeans \
einops_exts \
einops \
regex \
setuptools==59.5.0 \
resize_right==0.0.2 \
pillow \
scipy==1.7.1 \
webdataset==0.2.26 \
scikit-image \
timm==0.6.7
RUN pip install --no-deps torch_fidelity==0.3.0 clip@git+https://github.com/openai/CLIP.git@b46f5ac7587d2e1862f8b7b1573179d80dcdd620
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,367 @@
import cv2
import torch
import tops
import tqdm
import click
import hashlib
import numpy as np
from dp2 import utils
from PIL import Image
from tops import logger
from pathlib import Path
from typing import Optional
import moviepy.editor as mp
from tops.config import instantiate
from detectron2.data.detection_utils import _apply_exif_orientation
from dp2.utils.bufferless_video_capture import BufferlessVideoCapture
def show_video(video_path):
video_cap = cv2.VideoCapture(str(video_path))
while video_cap.isOpened():
ret, frame = video_cap.read()
cv2.imshow("Frame", frame)
key = cv2.waitKey(25)
if key == ord("q"):
break
video_cap.release()
cv2.destroyAllWindows()
class ImageIndexTracker:
def __init__(self, fn) -> None:
self.fn = fn
self.idx = 0
def fl_image(self, frame):
self.idx += 1
return self.fn(frame, self.idx - 1)
def anonymize_video(
video_path,
output_path: Path,
anonymizer,
visualize: bool,
max_res: int,
start_time: int,
fps: int,
end_time: int,
visualize_detection: bool,
track: bool,
synthesis_kwargs,
**kwargs,
):
video = mp.VideoFileClip(str(video_path))
if track:
anonymizer.initialize_tracker(video.fps)
def process_frame(frame, idx):
frame = np.array(resize(Image.fromarray(frame), max_res))
cache_id = hashlib.md5(frame).hexdigest()
frame = utils.im2torch(frame, to_float=False, normalize=False)[0]
cache_id_ = cache_id + str(idx)
synthesis_kwargs["cache_id"] = cache_id_
if visualize_detection:
anonymized = anonymizer.visualize_detection(frame, cache_id=cache_id_)
else:
anonymized = anonymizer(frame, **synthesis_kwargs)
anonymized = utils.im2numpy(anonymized)
if visualize:
cv2.imshow("frame", anonymized[:, :, ::-1])
key = cv2.waitKey(1)
if key == ord("q"):
exit()
return anonymized
video: mp.VideoClip = video.subclip(start_time, end_time)
if fps is not None:
video = video.set_fps(fps)
video = video.fl_image(ImageIndexTracker(process_frame).fl_image)
if str(output_path).endswith(".avi"):
output_path = str(output_path).replace(".avi", ".mp4")
if not output_path.parent.exists():
output_path.parent.mkdir(parents=True)
video.write_videofile(str(output_path))
def resize(frame: Image.Image, max_res):
if max_res is None:
return frame
f = max(*[x / max_res for x in frame.size], 1)
if f == 1:
return frame
new_shape = [int(x / f) for x in frame.size]
return frame.resize(new_shape, resample=Image.BILINEAR)
def anonymize_image(
image_path,
output_path: Path,
visualize: bool,
anonymizer,
max_res: int,
visualize_detection: bool,
synthesis_kwargs,
**kwargs,
):
with Image.open(image_path) as im:
im = _apply_exif_orientation(im)
orig_im_mode = im.mode
im = im.convert("RGB")
im = resize(im, max_res)
im = np.array(im)
md5_ = hashlib.md5(im).hexdigest()
im = utils.im2torch(np.array(im), to_float=False, normalize=False)[0]
synthesis_kwargs["cache_id"] = md5_
if visualize_detection:
im_ = anonymizer.visualize_detection(tops.to_cuda(im), cache_id=md5_)
else:
im_ = anonymizer(im, **synthesis_kwargs)
im_ = utils.im2numpy(im_)
if visualize:
while True:
cv2.imshow("frame", im_[:, :, ::-1])
key = cv2.waitKey(0)
if key == ord("q"):
break
elif key == ord("u"):
im_ = utils.im2numpy(anonymizer(im, **synthesis_kwargs))
im = Image.fromarray(im_).convert(orig_im_mode)
if output_path is not None:
output_path.parent.mkdir(exist_ok=True, parents=True)
im.save(output_path, optimize=False, quality=100)
print(f"Saved to: {output_path}")
def anonymize_file(input_path: Path, output_path: Optional[Path], **kwargs):
if output_path is not None and output_path.is_file():
logger.warn(f"Overwriting previous file: {output_path}")
if tops.is_image(input_path):
anonymize_image(input_path, output_path, **kwargs)
elif tops.is_video(input_path):
anonymize_video(input_path, output_path, **kwargs)
else:
logger.log(f"Filepath not a video or image file: {input_path}")
def anonymize_directory(input_dir: Path, output_dir: Path, **kwargs):
for childname in tqdm.tqdm(input_dir.iterdir()):
childpath = input_dir.joinpath(childname.name)
output_path = output_dir.joinpath(childname.name)
if not childpath.is_file():
anonymize_directory(childpath, output_path, **kwargs)
else:
assert childpath.is_file()
anonymize_file(childpath, output_path, **kwargs)
def anonymize_webcam(
anonymizer,
max_res: int,
synthesis_kwargs,
visualize_detection,
track: bool,
**kwargs,
):
import time
cap = BufferlessVideoCapture(0, width=1920, height=1080)
t = time.time()
frames = 0
if track:
anonymizer.initialize_tracker(fps=5) # FPS used for tracking objects
while True:
# Capture frame-by-frame
ret, frame = cap.read()
frame = Image.fromarray(frame[:, :, ::-1])
frame = resize(frame, max_res)
frame = np.array(frame)
im = utils.im2torch(np.array(frame), to_float=False, normalize=False)[0]
if visualize_detection:
im_ = anonymizer.visualize_detection(tops.to_cuda(im))
else:
im_ = anonymizer(im, **synthesis_kwargs)
im_ = utils.im2numpy(im_)
frames += 1
delta = time.time() - t
fps = "?"
if delta > 1e-6:
fps = frames / delta
print(f"FPS: {fps:.3f}", end="\r")
cv2.imshow("frame", im_[:, :, ::-1])
if cv2.waitKey(1) & 0xFF == ord("q"):
break
@click.command()
@click.argument("config_path", type=click.Path(exists=True))
@click.option(
"-i",
"--input_path",
help="Input path. Accepted inputs: images, videos, directories.",
)
@click.option(
"-o",
"--output_path",
default=None,
type=click.Path(),
help="Output path to save. Can be directory or file.",
)
@click.option(
"-v", "--visualize", default=False, is_flag=True, help="Visualize the result"
)
@click.option(
"--max-res", default=None, type=int, help="Maximum resolution of height/wideo"
)
@click.option(
"--start-time",
"--st",
default=0,
type=int,
help="Start time (second) for vide anonymization",
)
@click.option(
"--end-time",
"--et",
default=None,
type=int,
help="End time (second) for vide anonymization",
)
@click.option("--fps", default=None, type=int, help="FPS for anonymization")
@click.option(
"--detection-score-threshold",
"--dst",
default=0.3,
type=click.FloatRange(0, 1),
help="Detection threshold, threshold applied for all detection models.",
)
@click.option(
"--visualize-detection",
"--vd",
default=False,
is_flag=True,
help="Visualize only detections without running anonymization.",
)
@click.option(
"--multi-modal-truncation",
"--mt",
default=False,
is_flag=True,
help="Enable multi-modal truncation proposed by: https://arxiv.org/pdf/2202.12211.pdf",
)
@click.option(
"--cache",
default=False,
is_flag=True,
help="Enable detection caching. Will save and load detections from cache.",
)
@click.option(
"--amp",
default=True,
is_flag=True,
help="Use automatic mixed precision for generator forward pass",
)
@click.option(
"-t",
"--truncation_value",
default=0,
type=click.FloatRange(0, 1),
help="Latent interpolation truncation value.",
)
@click.option(
"--track",
default=False,
is_flag=True,
help="Track detections over frames. Will use the same latent variable (z) for tracked identities.",
)
@click.option(
"--seed", default=0, type=int, help="Set random seed for generating images."
)
@click.option(
"--person-generator",
default=None,
help="Config path to unconditional person generator",
type=click.Path(),
)
@click.option(
"--cse-person-generator",
default=None,
help="Config path to CSE-guided person generator",
type=click.Path(),
)
@click.option(
"--webcam", default=False, is_flag=True, help="Read image from webcam feed."
)
@click.option(
"--text-prompt",
default=None,
type=str,
help="Text prompt for attribute guided anonymization. Requires the validation dataset downloaded.",
)
@click.option(
"--text-prompt-strength",
default=0.5,
type=float,
help="Strength for attribute-guided anonymization",
)
def anonymize_path(
config_path,
input_path,
output_path,
detection_score_threshold: float,
visualize_detection: bool,
cache: bool,
seed: int,
person_generator: str,
cse_person_generator: str,
webcam: bool,
**kwargs,
):
"""
config_path: Specify the path to the anonymization model to use.
"""
tops.set_seed(seed)
cfg = utils.load_config(config_path)
if person_generator is not None:
cfg.anonymizer.person_G_cfg = person_generator
if cse_person_generator is not None:
cfg.anonymizer.cse_person_G_cfg = cse_person_generator
cfg.detector.score_threshold = detection_score_threshold
utils.print_config(cfg)
anonymizer = instantiate(cfg.anonymizer, load_cache=cache)
synthesis_kwargs = [
"amp",
"multi_modal_truncation",
"truncation_value",
"text_prompt",
"text_prompt_strength",
]
synthesis_kwargs = {k: kwargs.pop(k) for k in synthesis_kwargs}
kwargs["anonymizer"] = anonymizer
kwargs["visualize_detection"] = visualize_detection
kwargs["synthesis_kwargs"] = synthesis_kwargs
if webcam:
anonymize_webcam(**kwargs)
return
input_path = Path(input_path)
output_path = Path(output_path) if output_path is not None else None
if output_path is None and not kwargs["visualize"]:
logger.log("Output path not set. Setting visualize to True")
kwargs["visualize"] = True
if input_path.is_dir():
assert output_path is None or not output_path.is_file()
anonymize_directory(input_path, output_path, **kwargs)
else:
anonymize_file(input_path, output_path, **kwargs)
if __name__ == "__main__":
anonymize_path()
@@ -0,0 +1,160 @@
from collections import defaultdict
import gradio
import click
import numpy as np
import torch
import cv2
from PIL import Image
from dp2 import utils
from tops.config import instantiate
import tops
import gradio.inputs
from stylemc import get_and_cache_direction, get_stylesW, init_affine_modules
class GuidedDemo:
def __init__(self, anonymizer, cfg_face) -> None:
self.anonymizer = anonymizer
assert sum([x is not None for x in list(anonymizer.generators.values())]) == 1
self.generator = [x for x in list(anonymizer.generators.values()) if x is not None][0]
cfg = list(anonymizer.generator_cfgs.values())[0]
cfg.train.batch_size = 1
self.dl = instantiate(cfg.data.val.loader)
self.cache_dir = cfg.output_dir
self.precompute_edits()
self.is_first = True
def precompute_edits(self):
self.precomputed_edits = set()
for edit in self.precomputed_edits:
get_and_cache_direction(self.cache_dir, self.dl, self.generator, edit)
if self.cache_dir.joinpath("stylemc_cache").is_dir():
for path in self.cache_dir.joinpath("stylemc_cache").iterdir():
text_prompt = path.stem.replace("_", " ")
self.precomputed_edits.add(text_prompt)
print(text_prompt)
self.edits = defaultdict(defaultdict)
def anonymize(self, img, show_boxes: bool, current_box_idx: int, current_styles, current_boxes, update_identity, edits, cache_id=None):
if not isinstance(img, torch.Tensor):
img, cache_id = pil2torch(img)
img = tops.to_cuda(img)
current_box_idx = current_box_idx % len(current_boxes)
edited_styles = [s.clone() for s in current_styles]
for face_idx, face_edits in edits.items():
for prompt, strength in face_edits.items():
direction = get_and_cache_direction(self.cache_dir, self.dl, self.generator, prompt)
edited_styles[int(face_idx)] += direction * strength
update_identity[int(face_idx)] = True
assert img.dtype == torch.uint8
img = self.anonymizer(
img, truncation_value=0,
multi_modal_truncation=True, amp=True,
cache_id=cache_id,
all_styles=iter(edited_styles),
update_identity=update_identity)
update_identity = [True for i in range(len(update_identity))]
img = utils.im2numpy(img)
if show_boxes:
x0, y0, x1, y1 = [int(_) for _ in current_boxes[int(current_box_idx)]]
img = cv2.rectangle(img, (x0, y0), (x1, y1), (255, 0, 0), 1)
return img, update_identity
def update_image(self, img, show_boxes):
img, cache_id = pil2torch(img)
img = tops.to_cuda(img)
det = self.anonymizer.detector.forward_and_cache(img, cache_id, load_cache=True)[0]
current_styles = []
for i in range(len(det)):
# Need to do forward pass to register all affine modules.
batch = det.get_crop(i, img)
batch["condition"] = batch["img"].float()
if self.multi_modal_truncation:
w = self.generator.style_net.multi_modal_truncate(0, n=1)
else:
w = self.generator.style_net.get_truncated(1, n=1)
if self.is_first:
init_affine_modules(self.generator, batch)
self.is_first = False
s = get_stylesW(w)
current_styles.append(s)
update_identity = [True for i in range(len(det))]
current_boxes = np.array(det.boxes)
edits = defaultdict(defaultdict)
cur_face_idx = -1 % len(current_boxes)
img, update_identity = self.anonymize(img, show_boxes, cur_face_idx, current_styles, current_boxes, update_identity, edits, cache_id=cache_id)
return img, current_styles, current_boxes, update_identity, edits, cur_face_idx
def change_face(self, change, cur_face_idx, current_boxes, input_image, show_boxes, current_styles, update_identity, edits):
cur_face_idx = (cur_face_idx+change) % len(current_boxes)
img, update_identity = self.anonymize(input_image, show_boxes, cur_face_idx, current_styles, current_boxes, update_identity, edits)
return img, update_identity, cur_face_idx
def add_style(self, face_idx: int, prompt: str, strength: float, input_image, show_boxes, current_styles, current_boxes, update_identity, edits):
face_idx = face_idx % len(current_boxes)
edits[face_idx][prompt] = strength
img, update_identity = self.anonymize(input_image, show_boxes, face_idx, current_styles, current_boxes, update_identity, edits)
return img, update_identity, edits
def switch_mmt(self, value):
self.multi_modal_truncation = value
def setup_interface(self):
current_styles = gradio.State()
current_boxes = gradio.State(None)
update_identity = gradio.State([])
edits = gradio.State([])
with gradio.Row():
input_image = gradio.Image(
type="pil", label="Upload your image or try the example below!", source="webcam")
output_image = gradio.Image(type="numpy", label="Output")
with gradio.Row():
update_btn = gradio.Button("Update Anonymization").style(full_width=True)
mmt_btn = gradio.Checkbox(label="Multi Modal anonymization", value=True)
with gradio.Row():
show_boxes = gradio.Checkbox(value=True, label="Show Selected")
cur_face_idx = gradio.Number(value=-1,label="Current", interactive=False)
previous = gradio.Button("Previous Person")
next_ = gradio.Button("Next Person")
with gradio.Row():
text_prompt = gradio.Textbox(
placeholder=" | ".join(list(self.precomputed_edits)),
label="Text Prompt for Edit")
edit_strength = gradio.Slider(0, 5, step=.01)
add_btn = gradio.Button("Add Edit")
add_btn.click(self.add_style, inputs=[cur_face_idx, text_prompt, edit_strength, input_image, show_boxes, current_styles, current_boxes, update_identity, edits], outputs=[output_image, update_identity, edits])
mmt_btn.change(self.switch_mmt, inputs=[mmt_btn], outputs=[])
self.multi_modal_truncation = mmt_btn.value
update_btn.click(self.update_image, inputs=[input_image, show_boxes], outputs=[output_image, current_styles, current_boxes, update_identity, edits, cur_face_idx])
input_image.change(self.update_image, inputs=[input_image, show_boxes], outputs=[output_image, current_styles, current_boxes, update_identity, edits, cur_face_idx])
previous.click(self.change_face, inputs=[gradio.State(-1), cur_face_idx, current_boxes, input_image, show_boxes, current_styles, update_identity, edits], outputs=[output_image, update_identity, cur_face_idx])
next_.click(self.change_face, inputs=[gradio.State(1), cur_face_idx, current_boxes, input_image, show_boxes, current_styles, update_identity, edits], outputs=[output_image, update_identity, cur_face_idx])
show_boxes.change(self.anonymize, inputs=[input_image, show_boxes, cur_face_idx, current_styles, current_boxes, update_identity, edits], outputs=[output_image, update_identity])
def pil2torch(img: Image.Image):
img = img.convert("RGB")
img = np.array(img)
img = np.rollaxis(img, 2)
return torch.from_numpy(img), None
@click.command()
@click.argument("config_path")
def main(config_path):
cfg_face = utils.load_config(config_path)
anonymizer_face = instantiate(cfg_face.anonymizer, load_cache=False)
anonymizer_face.initialize_tracker(fps=1)
with gradio.Blocks() as demo:
gradio.Markdown("# <center> DeepPrivacy2 - Realistic Image Anonymization </center>")
gradio.Markdown("### <center> Håkon Hukkelås, Rudolf Mester, Frank Lindseth </center>")
with gradio.Tab("Text-Guided Anonymization"):
GuidedDemo(anonymizer_face, cfg_face).setup_interface()
demo.launch()
main()
@@ -0,0 +1,28 @@
from dp2.anonymizer import Anonymizer
from dp2.detection.person_detector import CSEPersonDetector
from ..defaults import common
from tops.config import LazyCall as L
from dp2.generator.dummy_generators import MaskOutGenerator
maskout_G = L(MaskOutGenerator)(noise="constant")
detector = L(CSEPersonDetector)(
mask_rcnn_cfg=dict(),
cse_cfg=dict(),
cse_post_process_cfg=dict(
target_imsize=(288, 160),
exp_bbox_cfg=dict(percentage_background=0.3, axis_minimum_expansion=.1),
exp_bbox_filter=dict(minimum_area=32*32, min_bbox_ratio_inside=0, aspect_ratio_range=[0, 99999]),
iou_combine_threshold=0.4,
dilation_percentage=0.02,
normalize_embedding=False
),
score_threshold=0.3,
cache_directory=common.output_dir.joinpath("cse_person_detection_cache")
)
anonymizer = L(Anonymizer)(
detector="${detector}",
cse_person_G_cfg="configs/fdh/styleganL.py",
)
@@ -0,0 +1,29 @@
from dp2.anonymizer import Anonymizer
from dp2.detection.person_detector import CSEPersonDetector
from ..defaults import common
from tops.config import LazyCall as L
from dp2.generator.dummy_generators import MaskOutGenerator
maskout_G = L(MaskOutGenerator)(noise="constant")
detector = L(CSEPersonDetector)(
mask_rcnn_cfg=dict(),
cse_cfg=dict(),
cse_post_process_cfg=dict(
target_imsize=(288, 160),
exp_bbox_cfg=dict(percentage_background=0.3, axis_minimum_expansion=.1),
exp_bbox_filter=dict(minimum_area=32*32, min_bbox_ratio_inside=0, aspect_ratio_range=[0, 99999]),
iou_combine_threshold=0.4,
dilation_percentage=0.02,
normalize_embedding=False
),
score_threshold=0.3,
cache_directory=common.output_dir.joinpath("cse_person_detection_cache")
)
anonymizer = L(Anonymizer)(
detector="${detector}",
person_G_cfg="configs/fdh/styleganL_nocse.py",
cse_person_G_cfg="configs/fdh/styleganL.py",
)
@@ -0,0 +1,29 @@
from dp2.anonymizer import Anonymizer
from dp2.detection.cse_mask_face_detector import CSeMaskFaceDetector
from ..defaults import common
from tops.config import LazyCall as L
detector = L(CSeMaskFaceDetector)(
mask_rcnn_cfg=dict(),
face_detector_cfg=dict(),
face_post_process_cfg=dict(target_imsize=(256, 256), fdf128_expand=False),
cse_cfg=dict(),
cse_post_process_cfg=dict(
target_imsize=(288, 160),
exp_bbox_cfg=dict(percentage_background=0.3, axis_minimum_expansion=.1),
exp_bbox_filter=dict(minimum_area=32*32, min_bbox_ratio_inside=0, aspect_ratio_range=[0, 99999]),
iou_combine_threshold=0.4,
dilation_percentage=0.02,
normalize_embedding=False
),
score_threshold=0.3,
cache_directory=common.output_dir.joinpath("cse_mask_face_detection_cache")
)
anonymizer = L(Anonymizer)(
detector="${detector}",
face_G_cfg="configs/fdf/stylegan.py",
person_G_cfg="configs/fdh/styleganL_nocse.py",
cse_person_G_cfg="configs/fdh/styleganL.py",
car_G_cfg="configs/generators/dummy/pixelation8.py"
)
@@ -0,0 +1,26 @@
from dp2.anonymizer import Anonymizer
from dp2.detection.models.vit_pose_maskrcnn import MaskRCNNVitPose
from ..defaults import common
from tops.config import LazyCall as L
detector = L(MaskRCNNVitPose)(
mask_rcnn_cfg=dict(),
post_process_cfg=dict(
target_imsize=(288, 160),
exp_bbox_cfg=dict(percentage_background=0.3, axis_minimum_expansion=0.1),
exp_bbox_filter=dict(
minimum_area=32 * 32, min_bbox_ratio_inside=0, aspect_ratio_range=[0, 99999]
),
dilation_percentage=0.02,
kp_vis_thr=0.05,
insert_joint_map=True,
),
score_threshold=0.3,
cache_directory=common.output_dir.joinpath("maskrcnn_vitpose_cache"),
)
anonymizer = L(Anonymizer)(
detector="${detector}",
person_G_cfg="configs/fdh/triagan/L_im288.py",
)
@@ -0,0 +1,15 @@
from .face_fdf128 import anonymizer, common, detector
from dp2.detection.deep_privacy1_detector import DeepPrivacy1Detector
from tops.config import LazyCall as L
anonymizer.update(
face_G_cfg="configs/fdf/deep_privacy1.py",
)
anonymizer.detector = L(DeepPrivacy1Detector)(
face_detector_cfg=dict(name="DSFDDetector", clip_boxes=True),
face_post_process_cfg=dict(target_imsize=(128, 128), fdf128_expand=True),
score_threshold=0.3,
keypoint_threshold=0.3,
cache_directory=common.output_dir.joinpath("deep_privacy1_cache")
)
@@ -0,0 +1,17 @@
from dp2.anonymizer import Anonymizer
from dp2.detection.face_detector import FaceDetector
from ..defaults import common
from tops.config import LazyCall as L
detector = L(FaceDetector)(
face_detector_cfg=dict(name="DSFDDetector", clip_boxes=True),
face_post_process_cfg=dict(target_imsize=(256, 256), fdf128_expand=False),
score_threshold=0.3,
cache_directory=common.output_dir.joinpath("face_detection_cache"),
)
anonymizer = L(Anonymizer)(
detector="${detector}",
face_G_cfg="configs/fdf/stylegan.py",
)
@@ -0,0 +1,18 @@
from dp2.anonymizer import Anonymizer
from dp2.detection.face_detector import FaceDetector
from ..defaults import common
from tops.config import LazyCall as L
detector = L(FaceDetector)(
face_detector_cfg=dict(name="DSFDDetector", clip_boxes=True),
face_post_process_cfg=dict(target_imsize=(128, 128), fdf128_expand=True),
score_threshold=0.3,
cache_directory=common.output_dir.joinpath("face_detection_cache")
)
anonymizer = L(Anonymizer)(
detector="${detector}",
face_G_cfg="configs/fdf/stylegan_fdf128.py",
)
@@ -0,0 +1,8 @@
from ..FB_cse_mask_face import anonymizer, detector, common
detector.score_threshold = .1
detector.face_detector_cfg.confidence_threshold = .5
detector.cse_cfg.score_thres = 0.3
anonymizer.face_G_cfg = None
anonymizer.person_G_cfg = "configs/generators/dummy/maskout.py"
anonymizer.cse_person_G_cfg = "configs/generators/dummy/maskout.py"
@@ -0,0 +1,6 @@
from ..FB_cse_mask_face import anonymizer, detector, common
detector.score_threshold = .1
detector.face_detector_cfg.confidence_threshold = .5
detector.cse_cfg.score_thres = 0.3
anonymizer.face_G_cfg = None
@@ -0,0 +1,8 @@
from ..FB_cse_mask_face import anonymizer, detector, common
detector.score_threshold = .1
detector.face_detector_cfg.confidence_threshold = .5
detector.cse_cfg.score_thres = 0.3
anonymizer.face_G_cfg = None
anonymizer.person_G_cfg = "configs/generators/dummy/pixelation16.py"
anonymizer.cse_person_G_cfg = "configs/generators/dummy/pixelation16.py"
@@ -0,0 +1,8 @@
from ..FB_cse_mask_face import anonymizer, detector, common
detector.score_threshold = .1
detector.face_detector_cfg.confidence_threshold = .5
detector.cse_cfg.score_thres = 0.3
anonymizer.face_G_cfg = None
anonymizer.person_G_cfg = "configs/generators/dummy/pixelation8.py"
anonymizer.cse_person_G_cfg = "configs/generators/dummy/pixelation8.py"
@@ -0,0 +1,3 @@
from ...FB_triagan import detector, anonymizer, common
anonymizer.person_G_cfg = "configs/generators/dummy/gaussian.py"
@@ -0,0 +1,3 @@
from ...FB_triagan import detector, anonymizer, common
anonymizer.person_G_cfg = "configs/generators/dummy/maskout.py"
@@ -0,0 +1,4 @@
from ...face import detector, anonymizer, common
anonymizer.face_G_cfg = "configs/generators/dummy/gaussian.py"
@@ -0,0 +1,4 @@
from ...face import detector, anonymizer, common
anonymizer.face_G_cfg = "configs/generators/dummy/maskout.py"
@@ -0,0 +1,69 @@
import os
from pathlib import Path
from tops.config import LazyCall as L
import torch
import functools
from dp2.data.datasets.coco_cse import CocoCSE
from dp2.data.build import get_dataloader
from dp2.data.transforms.transforms import CreateEmbedding, Normalize, Resize, ToFloat, CreateCondition, RandomHorizontalFlip
from dp2.data.transforms.stylegan2_transform import StyleGANAugmentPipe
from dp2.metrics.torch_metrics import compute_metrics_iteratively
from .utils import final_eval_fn
dataset_base_dir = os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
metrics_cache = os.environ["FBA_METRICS_CACHE"] if "FBA_METRICS_CACHE" in os.environ else ".cache"
data_dir = Path(dataset_base_dir, "coco_cse")
data = dict(
imsize=(288, 160),
im_channels=3,
semantic_nc=26,
cse_nc=16,
train=dict(
dataset=L(CocoCSE)(data_dir.joinpath("train"), transform=None, normalize_E=False),
loader=L(get_dataloader)(
shuffle=True, num_workers=6, drop_last=True, prefetch_factor=2,
batch_size="${train.batch_size}",
dataset="${..dataset}",
infinite=True,
gpu_transform=L(torch.nn.Sequential)(*[
L(ToFloat)(),
L(StyleGANAugmentPipe)(
rotate=0.5, rotate_max=.05,
xint=.5, xint_max=0.05,
scale=.5, scale_std=.05,
aniso=0.5, aniso_std=.05,
xfrac=.5, xfrac_std=.05,
brightness=.5, brightness_std=.05,
contrast=.5, contrast_std=.1,
hue=.5, hue_max=.05,
saturation=.5, saturation_std=.5,
imgfilter=.5, imgfilter_std=.1),
L(RandomHorizontalFlip)(p=0.5),
L(CreateEmbedding)(),
L(Resize)(size="${data.imsize}"),
L(Normalize)(mean=[.5, .5, .5], std=[.5, .5, .5], inplace=True),
L(CreateCondition)(),
])
)
),
val=dict(
dataset=L(CocoCSE)(data_dir.joinpath("val"), transform=None, normalize_E=False),
loader=L(get_dataloader)(
shuffle=False, num_workers=6, drop_last=True, prefetch_factor=2,
batch_size="${train.batch_size}",
dataset="${..dataset}",
infinite=False,
gpu_transform=L(torch.nn.Sequential)(*[
L(ToFloat)(),
L(CreateEmbedding)(),
L(Resize)(size="${data.imsize}"),
L(Normalize)(mean=[.5, .5, .5], std=[.5, .5, .5], inplace=True),
L(CreateCondition)(),
])
)
),
# Training evaluation might do optimizations to reduce compute overhead. E.g. compute with AMP.
train_evaluation_fn=functools.partial(compute_metrics_iteratively, cache_directory=Path(metrics_cache, "coco_cse_val"), include_two_fake=False),
evaluation_fn=functools.partial(final_eval_fn, cache_directory=Path(metrics_cache, "coco_cse_val_final"), include_two_fake=True)
)
@@ -0,0 +1,24 @@
from pathlib import Path
from functools import partial
from dp2.data.datasets.fdf import FDFDataset
from .fdf256 import data, dataset_base_dir, metrics_cache, final_eval_fn, train_eval_fn
data_dir = Path(dataset_base_dir, "fdf")
data.train.dataset.dirpath = data_dir.joinpath("train")
data.val.dataset.dirpath = data_dir.joinpath("val")
data.imsize = (128, 128)
data.train_evaluation_fn = partial(
train_eval_fn, cache_directory=Path(metrics_cache, "fdf128_val_train"))
data.evaluation_fn = partial(
final_eval_fn, cache_directory=Path(metrics_cache, "fdf128_val_final"))
data.train.dataset.update(
_target_ = FDFDataset,
imsize="${data.imsize}"
)
data.val.dataset.update(
_target_ = FDFDataset,
imsize="${data.imsize}"
)
@@ -0,0 +1,82 @@
import os
from pathlib import Path
from tops.config import LazyCall as L
import torch
import functools
from dp2.data.datasets.fdf128_wds import get_dataloader_fdf_wds
from dp2.data.utils import get_fdf_flipmap
from dp2.data.transforms.transforms import (
Normalize,
ToFloat,
CreateCondition,
RandomHorizontalFlip,
)
from ..utils import train_eval_fn
from dp2.metrics.torch_metrics import compute_metrics_iteratively
from dp2.metrics.fid_clip import compute_fid_clip
from dp2.metrics.ppl import calculate_ppl
def final_eval_fn(*args, **kwargs):
result = compute_metrics_iteratively(*args, **kwargs)
result2 = calculate_ppl(*args, **kwargs, upsample_size=(128, 128))
result3 = compute_fid_clip(*args, **kwargs)
assert all(key not in result for key in result2)
result.update(result2)
result.update(result3)
return result
def get_cache_directory(imsize, subset):
return Path(metrics_cache, f"{subset}{imsize[0]}")
dataset_base_dir = (
os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
)
metrics_cache = (
os.environ["FBA_METRICS_CACHE"] if "FBA_METRICS_CACHE" in os.environ else ".cache"
)
data_dir = Path(dataset_base_dir, "fdf_resampled")
data = dict(
imsize=(128, 128),
im_channels=3,
cse_nc=0,
n_keypoints=7,
train=dict(
loader=L(get_dataloader_fdf_wds)(
path=data_dir.joinpath("train", "128", "out-{000000..000473}.tar"),
batch_size="${train.batch_size}",
num_workers=4,
transform=L(torch.nn.Sequential)(
L(RandomHorizontalFlip)(p=0.5, flip_map=get_fdf_flipmap()),
),
gpu_transform=L(torch.nn.Sequential)(
L(ToFloat)(norm=False, keys=["img", "mask"]),
L(Normalize)(mean=[0.5*255, 0.5*255, 0.5*255], std=[0.5*255, 0.5*255, 0.5*255], inplace=True),
L(CreateCondition)(),
),
infinite=True,
shuffle=True,
partial_batches=False,
)
),
val=dict(
loader=L(get_dataloader_fdf_wds)(
path=data_dir.joinpath("val", "128", "out-{000000..000016}.tar"),
batch_size="${train.batch_size}",
num_workers=2,
transform=None,
gpu_transform="${data.train.loader.gpu_transform}",
infinite=False,
shuffle=False,
partial_batches=True,
)
),
# Training evaluation might do optimizations to reduce compute overhead. E.g. compute with AMP.
train_evaluation_fn=L(functools.partial)(
train_eval_fn, cache_directory=L(get_cache_directory)(imsize="${data.imsize}", subset="fdf"),
data_len=50_000),
evaluation_fn=L(functools.partial)(
final_eval_fn, cache_directory=L(get_cache_directory)(imsize="${data.imsize}", subset="fdf_eval"),
data_len=50_000)
)
@@ -0,0 +1,9 @@
from .fdf128 import data, data_dir
data.imsize = (16, 16)
data.val.loader.update(
path=data_dir.joinpath("val", "16", "out-{000000..000016}.tar"),
)
data.train.loader.update(
path=data_dir.joinpath("train", "16", "out-{000000..000473}.tar"),
)
@@ -0,0 +1,9 @@
from .fdf128 import data, data_dir
data.imsize = (32, 32)
data.val.loader.update(
path=data_dir.joinpath("val", "32", "out-{000000..000016}.tar"),
)
data.train.loader.update(
path=data_dir.joinpath("train", "32", "out-{000000..000473}.tar"),
)
@@ -0,0 +1,9 @@
from .fdf128 import data, data_dir
data.imsize = (64, 64)
data.val.loader.update(
path=data_dir.joinpath("val", "64", "out-{000000..000016}.tar"),
)
data.train.loader.update(
path=data_dir.joinpath("train", "64", "out-{000000..000473}.tar"),
)
@@ -0,0 +1,55 @@
import os
from pathlib import Path
from tops.config import LazyCall as L
import torch
import functools
from dp2.data.datasets.fdf import FDF256Dataset
from dp2.data.build import get_dataloader
from dp2.data.transforms.transforms import Normalize, Resize, ToFloat, CreateCondition, RandomHorizontalFlip
from .utils import final_eval_fn, train_eval_fn
dataset_base_dir = os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
metrics_cache = os.environ["FBA_METRICS_CACHE"] if "FBA_METRICS_CACHE" in os.environ else ".cache"
data_dir = Path(dataset_base_dir, "fdf256")
data = dict(
imsize=(256, 256),
im_channels=3,
semantic_nc=None,
cse_nc=None,
n_keypoints=None,
train=dict(
dataset=L(FDF256Dataset)(dirpath=data_dir.joinpath("train"), transform=None, load_keypoints=False),
loader=L(get_dataloader)(
shuffle=True, num_workers=3, drop_last=True, prefetch_factor=2,
batch_size="${train.batch_size}",
dataset="${..dataset}",
infinite=True,
gpu_transform=L(torch.nn.Sequential)(*[
L(ToFloat)(),
L(RandomHorizontalFlip)(p=0.5),
L(Resize)(size="${data.imsize}"),
L(Normalize)(mean=[.5, .5, .5], std=[.5, .5, .5], inplace=True),
L(CreateCondition)(),
])
)
),
val=dict(
dataset=L(FDF256Dataset)(dirpath=data_dir.joinpath("val"), transform=None, load_keypoints=False),
loader=L(get_dataloader)(
shuffle=False, num_workers=3, drop_last=False, prefetch_factor=2,
batch_size="${train.batch_size}",
dataset="${..dataset}",
infinite=False,
gpu_transform=L(torch.nn.Sequential)(*[
L(ToFloat)(),
L(Resize)(size="${data.imsize}"),
L(Normalize)(mean=[.5, .5, .5], std=[.5, .5, .5], inplace=True),
L(CreateCondition)(),
])
)
),
# Training evaluation might do optimizations to reduce compute overhead. E.g. compute with AMP.
train_evaluation_fn=functools.partial(train_eval_fn, cache_directory=Path(metrics_cache, "fdf_val_train")),
evaluation_fn=functools.partial(final_eval_fn, cache_directory=Path(metrics_cache, "fdf_val"))
)
@@ -0,0 +1,90 @@
import os
from pathlib import Path
from tops.config import LazyCall as L
import torch
import functools
from dp2.data.datasets.fdh import get_dataloader_fdh_wds
from dp2.data.utils import get_coco_flipmap
from dp2.data.transforms.transforms import (
Normalize,
ToFloat,
CreateCondition,
RandomHorizontalFlip,
CreateEmbedding,
)
from dp2.metrics.torch_metrics import compute_metrics_iteratively
from dp2.metrics.fid_clip import compute_fid_clip
from dp2.metrics.ppl import calculate_ppl
from .utils import train_eval_fn
def final_eval_fn(*args, **kwargs):
result = compute_metrics_iteratively(*args, **kwargs)
result2 = calculate_ppl(*args, **kwargs, upsample_size=(288, 160))
result3 = compute_fid_clip(*args, **kwargs)
assert all(key not in result for key in result2)
result.update(result2)
result.update(result3)
return result
def get_cache_directory(imsize, subset):
return Path(metrics_cache, f"{subset}{imsize[0]}")
dataset_base_dir = (
os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
)
metrics_cache = (
os.environ["FBA_METRICS_CACHE"] if "FBA_METRICS_CACHE" in os.environ else ".cache"
)
data_dir = Path(dataset_base_dir, "fdh")
data = dict(
imsize=(288, 160),
im_channels=3,
cse_nc=16,
n_keypoints=17,
train=dict(
loader=L(get_dataloader_fdh_wds)(
path=data_dir.joinpath("train", "out-{000000..001423}.tar"),
batch_size="${train.batch_size}",
num_workers=6,
transform=L(torch.nn.Sequential)(
L(RandomHorizontalFlip)(p=0.5, flip_map=get_coco_flipmap()),
),
gpu_transform=L(torch.nn.Sequential)(
L(ToFloat)(norm=False, keys=["img", "mask", "E_mask", "maskrcnn_mask"]),
L(CreateEmbedding)(embed_path=data_dir.joinpath("embed_map.torch")),
L(Normalize)(mean=[0.5*255, 0.5*255, 0.5*255], std=[0.5*255, 0.5*255, 0.5*255], inplace=True),
L(CreateCondition)(),
),
infinite=True,
shuffle=True,
partial_batches=False,
load_embedding=True,
keypoints_split="train",
load_new_keypoints=False
)
),
val=dict(
loader=L(get_dataloader_fdh_wds)(
path=data_dir.joinpath("val", "out-{000000..000023}.tar"),
batch_size="${train.batch_size}",
num_workers=6,
transform=None,
gpu_transform="${data.train.loader.gpu_transform}",
infinite=False,
shuffle=False,
partial_batches=True,
load_embedding=True,
keypoints_split="val",
load_new_keypoints="${data.train.loader.load_new_keypoints}"
)
),
# Training evaluation might do optimizations to reduce compute overhead. E.g. compute with AMP.
train_evaluation_fn=L(functools.partial)(
train_eval_fn, cache_directory=L(get_cache_directory)(imsize="${data.imsize}", subset="fdh"),
data_len=30_000),
evaluation_fn=L(functools.partial)(
final_eval_fn, cache_directory=L(get_cache_directory)(imsize="${data.imsize}", subset="fdh_eval"),
data_len=30_000)
)
@@ -0,0 +1,35 @@
from dp2.data.transforms.transforms import ToFloat, Normalize, CreateCondition, InsertJointMap, RandomHorizontalFlip
from tops.config import LazyCall as L
from dp2.data.utils import get_coco_flipmap
from tops.config import LazyCall as L
import torch
from pathlib import Path
from .fdh import data, dataset_base_dir
data.imsize = (288, 160)
data_dir = Path(dataset_base_dir, "fdh_no_embeddings")
data.train.loader.update(
path=data_dir.joinpath("train", "out-{000000..000612}.tar"),
read_condition=False,
gpu_transform=L(torch.nn.Sequential)(
L(ToFloat)(keys=["img", "mask", "maskrcnn_mask"], norm=False),
L(Normalize)(mean=[0.5*255, 0.5*255, 0.5*255], std=[0.5*255, 0.5*255, 0.5*255], inplace=True),
L(CreateCondition)(),
),
transform=L(torch.nn.Sequential)(
L(RandomHorizontalFlip)(p=0.5, flip_map=get_coco_flipmap()),
L(InsertJointMap)(imsize="${data.imsize}"),
),
load_embedding=False,
load_new_keypoints=True,
num_workers=4,
)
data.val.loader.update(
path=data_dir.joinpath("val", "out-{000000..000010}.tar"),
num_workers=2,
read_condition=False,
load_embedding=False,
transform=L(torch.nn.Sequential)(
L(InsertJointMap)(imsize="${data.imsize}"),
)
)
@@ -0,0 +1,8 @@
from .fdh18 import data, data_dir
data.imsize = (144, 80)
data.val.loader.update(
path=data_dir.joinpath("val", "144", "out-{000000..000009}.tar"),
)
data.train.loader.update(
path=data_dir.joinpath("train", "144", "out-{000000..000609}.tar"),
)
@@ -0,0 +1,20 @@
from pathlib import Path
import torch
from tops.config import LazyCall as L
from dp2.data.transforms.transforms import Normalize, ToFloat
from ..fdh_no_embeddings import data, dataset_base_dir
data_dir = Path(dataset_base_dir, "fdh_no_embeddings_resampled/")
data.imsize = (18, 10)
data.val.loader.update(
read_condition=True,
path=data_dir.joinpath("val", "18", "out-{000000..000009}.tar"),
)
data.train.loader.update(
path=data_dir.joinpath("train", "18", "out-{000000..000609}.tar"),
read_condition=True,
gpu_transform=L(torch.nn.Sequential)(
L(ToFloat)(keys=["img", "mask", "maskrcnn_mask", "condition"], norm=False),
L(Normalize)(mean=[0.5*255, 0.5*255, 0.5*255], std=[0.5*255, 0.5*255, 0.5*255], inplace=True, keys=["img", "condition"]),
)
)
@@ -0,0 +1,8 @@
from .fdh18 import data, data_dir
data.imsize = (36, 20)
data.val.loader.update(
path=data_dir.joinpath("val", "36", "out-{000000..000009}.tar"),
)
data.train.loader.update(
path=data_dir.joinpath("train", "36", "out-{000000..000609}.tar"),
)
@@ -0,0 +1,8 @@
from .fdh18 import data, data_dir
data.imsize = (72, 40)
data.val.loader.update(
path=data_dir.joinpath("val", "72", "out-{000000..000009}.tar"),
)
data.train.loader.update(
path=data_dir.joinpath("train", "72", "out-{000000..000609}.tar"),
)
@@ -0,0 +1,21 @@
from dp2.metrics.ppl import calculate_ppl
from dp2.metrics.torch_metrics import compute_metrics_iteratively
from dp2.metrics.fid_clip import compute_fid_clip
def final_eval_fn(*args, **kwargs):
result = compute_metrics_iteratively(*args, **kwargs)
result2 = calculate_ppl(*args, **kwargs,)
result3 = compute_fid_clip(*args, **kwargs)
assert all(key not in result for key in result2)
result.update(result2)
result.update(result3)
return result
def train_eval_fn(*args, **kwargs):
result = compute_metrics_iteratively(*args, **kwargs)
result2 = compute_fid_clip(*args, **kwargs)
assert all(key not in result for key in result2)
result.update(result2)
return result
@@ -0,0 +1,53 @@
import pathlib
import os
import torch
from tops.config import LazyCall as L
if "PRETRAINED_CHECKPOINTS_PATH" in os.environ:
PRETRAINED_CHECKPOINTS_PATH = pathlib.Path(os.environ["PRETRAINED_CHECKPOINTS_PATH"])
else:
PRETRAINED_CHECKPOINTS_PATH = pathlib.Path("pretrained_checkpoints")
if "BASE_OUTPUT_DIR" in os.environ:
BASE_OUTPUT_DIR = pathlib.Path(os.environ["BASE_OUTPUT_DIR"])
else:
BASE_OUTPUT_DIR = pathlib.Path("outputs")
common = dict(
logger_backend=["wandb", "stdout", "json", "image_dumper"],
wandb_project="deep_privacy2",
output_dir=BASE_OUTPUT_DIR,
experiment_name=None, # Optional experiment name to show on wandb
)
train = dict(
batch_size=32,
seed=0,
ims_per_log=1024,
ims_per_val=int(200e3),
max_images_to_train=int(12e6),
amp=dict(
enabled=True,
scaler_D=L(torch.cuda.amp.GradScaler)(init_scale=2**16, growth_factor=4, growth_interval=100, enabled="${..enabled}"),
scaler_G=L(torch.cuda.amp.GradScaler)(init_scale=2**16, growth_factor=4, growth_interval=100, enabled="${..enabled}"),
),
fp16_ddp_accumulate=False, # All gather gradients in fp16?
broadcast_buffers=False,
bias_act_plugin_enabled=True,
grid_sample_gradfix_enabled=True,
conv2d_gradfix_enabled=False,
channels_last=False,
compile_G=dict(
enabled=False,
mode="default" # default, reduce-overhead or max-autotune
),
compile_D=dict(
enabled=False,
mode="default" # default, reduce-overhead or max-autotune
)
)
# exponential moving average
EMA = dict(rampup=0.05)
@@ -0,0 +1,161 @@
from functools import partial
import torch
from dp2.discriminator.projected_gan import ProjectedDiscriminator
from dp2.discriminator.projected_gan.feature_nets import (
_make_efficientnet,
_make_resnet50_clip,
_make_resnet50_cse,
_make_resnet50,
)
from dp2.discriminator.projected_gan.vit import _make_vit_timm
from dp2.discriminator.projected_gan.vit_openclip import OpenCLIPViT
from dp2.loss.projected_gan_loss import ProjectedGANLoss, blur
from tops.config import LazyCall as L
imagenet_norm = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
inception_norm = dict(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
clip_norm = dict(
mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]
)
VIT_PATCH_MAE = dict(
backbone_cfg=L(_make_vit_timm)(
model_name="vit_base_patch16_224",
weight_path="https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_base.pth",
),
interp_size=None,
input_BGR=False,
jit_script=False,
**imagenet_norm
)
VIT_PATCH_MAE_LARGE = dict(
backbone_cfg=L(_make_vit_timm)(
model_name="vit_large_patch16_224",
weight_path="https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_large.pth",
),
interp_size=None,
input_BGR=False,
jit_script=False,
**imagenet_norm
)
VIT_PATCH_MAE_HUGE = dict(
backbone_cfg=L(_make_vit_timm)(
model_name="vit_huge_patch14_224",
weight_path="https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_huge.pth",
),
interp_size=None,
input_BGR=False,
jit_script=False,
**imagenet_norm
)
VIT_DINO_S = dict(
backbone_cfg=L(_make_vit_timm)(
model_name="vit_small_patch16_224",
weight_path="https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth"
),
interp_size=(224, 224),
input_BGR=False,
jit_script=False,
**imagenet_norm
)
VIT_DINO_B = dict(
backbone_cfg=L(_make_vit_timm)(
model_name="vit_base_patch16_224",
weight_path="https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth"
),
interp_size=(224, 224),
input_BGR=False,
jit_script=False,
**imagenet_norm
)
tf_efficientnet_lite0 = dict(
backbone_cfg=L(_make_efficientnet)(model_type="tf_efficientnet_lite0"),
interp_size=None,
input_BGR=False,
jit_script=True,
**inception_norm
)
RN50_CSE = dict(
backbone_cfg=L(_make_resnet50_cse)(
cfg_url="https://raw.githubusercontent.com/facebookresearch/detectron2/main/projects/DensePose/configs/cse/densepose_rcnn_R_50_FPN_s1x.yaml"
),
interp_size=None,
mean=[0.485, 0.456, 0.406],
std=[1 / 255, 1 / 255, 1 / 255],
input_BGR=True,
jit_script=False
)
RN50_CLIP = dict(
backbone_cfg=L(_make_resnet50_clip)(),
interp_size=None,
input_BGR=False,
jit_script=False,
**clip_norm
)
RN50_IN = dict(
backbone_cfg=L(_make_resnet50)(),
interp_size=None,
input_BGR=False,
jit_script=False,
**imagenet_norm
)
deit_base_distilled_patch16_224 = dict(
backbone_cfg=L(_make_vit_timm)(
model_name="deit_base_distilled_patch16_224", weight_path=None
),
interp_size=(224, 224),
input_BGR=False,
jit_script=False,
**imagenet_norm
)
openclip_vit_b_32 = dict(
backbone_cfg=L(OpenCLIPViT)(
model_name="ViT-B-32",
pretrained_dataset="laion2b_s34b_b79k",
),
input_BGR=False,
jit_script=False,
interp_size=(224, 224),
**clip_norm # Not sure if norm is correct for L-14 / B-32
)
openclip_vit_b_16 = dict(
backbone_cfg=L(OpenCLIPViT)(
model_name="ViT-B-16",
pretrained_dataset="openai",
),
input_BGR=False,
jit_script=False,
interp_size=(224, 224),
**clip_norm
)
openclip_vit_l_14 = dict(
backbone_cfg=L(OpenCLIPViT)(
model_name="ViT-L-14",
pretrained_dataset="laion2b_s32b_b82k",
),
input_BGR=False,
jit_script=False,
interp_size=(224, 224),
**clip_norm # Not sure if norm is correct for L-14 / B-32
)
discriminator = L(ProjectedDiscriminator)(
num_discs=4,
patch=True,
diffaug_policy=["color", "cutout"],
backbones=[VIT_PATCH_MAE],
last_ksize=3,
)
loss_fnc = L(ProjectedGANLoss)(
aug_fade_kimg=int(400e3),
blur_init_sigma=4,
)
D_optim = L(torch.optim.Adam)(lr=0.002, betas=(0.0, 0.99))
G_optim = L(torch.optim.Adam)(lr=0.002, betas=(0.0, 0.99))
@@ -0,0 +1,43 @@
from tops.config import LazyCall as L
from dp2.discriminator import SG2Discriminator
import torch
from dp2.loss import StyleGAN2Loss
discriminator = L(SG2Discriminator)(
imsize="${data.imsize}",
im_channels="${data.im_channels}",
min_fmap_resolution=4,
max_cnum_mul=8,
cnum=80,
input_condition=True,
conv_clamp=256,
input_cse=False,
cse_nc="${data.cse_nc}",
fix_residual=False,
)
loss_fnc = L(StyleGAN2Loss)(
lazy_regularization=True,
lazy_reg_interval=16,
r1_opts=dict(lambd=5, mask_out=False, mask_out_scale=False),
EP_lambd=0.001,
pl_reg_opts=dict(weight=0, batch_shrink=2,start_nimg=int(1e6), pl_decay=0.01)
)
def build_D_optim(type, lr, betas, lazy_regularization, lazy_reg_interval, **kwargs):
if lazy_regularization:
# From Analyzing and improving the image quality of stylegan, CVPR 2020
c = lazy_reg_interval / (lazy_reg_interval + 1)
betas = [beta ** c for beta in betas]
lr *= c
print(f"Lazy regularization on. Setting lr to: {lr}, betas to: {betas}")
return type(lr=lr, betas=betas, **kwargs)
D_optim = L(build_D_optim)(
type=torch.optim.Adam, lr=0.001, betas=(0.0, 0.99),
lazy_regularization="${loss_fnc.lazy_regularization}",
lazy_reg_interval="${loss_fnc.lazy_reg_interval}")
G_optim = L(torch.optim.Adam)(lr=0.001, betas=(0.0, 0.99))
@@ -0,0 +1,9 @@
from tops.config import LazyCall as L
from dp2.generator.deep_privacy1 import MSGGenerator
from ..datasets.fdf128 import data
from ..defaults import common, train
generator = L(MSGGenerator)()
common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/0940803d-1a2c-4b54-9c1d-0d3aeb80c5a8970f7dd4-bde6-4120-9d3e-5fad937eef2b7b0544e2-8c00-43c2-9193-f56679740872"
common.model_md5sum = "6cc8b285bdc1fcdfc64f5db7c521d0a6"
@@ -0,0 +1,14 @@
from ..generators.stylegan_unet import generator
from ..datasets.fdf256 import data
from ..discriminators.sg2_discriminator import discriminator, G_optim, D_optim, loss_fnc
from ..defaults import train, common, EMA
train.max_images_to_train = int(35e6)
G_optim.lr = 0.002
D_optim.lr = 0.002
generator.input_cse = False
loss_fnc.r1_opts.lambd = 1
train.ims_per_val = int(2e6)
common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/89660f04-5c11-4dbf-adac-cbe2f11b0aeea25cbf78-7558-475a-b3c7-03f5c10b7934646b0720-ca0a-4d53-aded-daddbfa45c9e"
common.model_md5sum = "e8e32190528af2ed75f0cb792b7f2b07"
@@ -0,0 +1,17 @@
from ..discriminators.sg2_discriminator import discriminator, G_optim, D_optim, loss_fnc
from ..datasets.fdf128 import data
from ..generators.stylegan_unet import generator
from ..defaults import train, common, EMA
from tops.config import LazyCall as L
G_optim.lr = 0.002
D_optim.lr = 0.002
generator.update(cnum=128, max_cnum_mul=4, input_cse=False)
loss_fnc.r1_opts.lambd = 0.1
train.update(ims_per_val=int(2e6), batch_size=64, max_images_to_train=int(35e6))
common.update(
model_url="https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/66d803c0-55ce-44c0-9d53-815c2c0e6ba4eb458409-9e91-45d1-bce0-95c8a47a57218b102fdf-bea3-44dc-aac4-0fb1d370ef1c",
model_md5sum="bccd4403e7c9bca682566ff3319e8176"
)
@@ -0,0 +1,42 @@
from ..discriminators.projected_discriminator import (
G_optim,
D_optim,
loss_fnc,
discriminator,
VIT_PATCH_MAE_LARGE,
RN50_CLIP
)
from ..defaults import common, EMA, train
from ..datasets.fdf128_wds.fdf128 import data
from ..generators.triagan import generator, ckpt_mapper
train.update(
batch_size=128,
ims_per_log=1024 * 20,
ims_per_val=int(2.4e6),
max_images_to_train=int(77e6),
broadcast_buffers=True,
fp16_ddp_accumulate=True,
)
loss_fnc.aug_fade_kimg = int(4e6)
generator.update(
dim_mults=[1, 2, 2, 2, 2],
dim=256,
imsize="${data.imsize}",
use_maskrcnn_mask=False,
input_keypoint_indices=list(range(3)),
input_keypoints=True,
use_noise=True,
layer_scale=False,
input_joint=False,
num_resnet_blocks=2
)
VIT_PATCH_MAE_LARGE.interp_size = (224, 224)
RN50_CLIP.interp_size = (224, 224)
discriminator.update(
backbones=[RN50_CLIP, VIT_PATCH_MAE_LARGE],
)
common.model_md5sum = "7b94366d9d2e1e9a6491e065491fda87"
common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/88e98c73-e890-489d-a3eb-cf6fbf1728f531b0047f-ddf3-4188-8028-2b55c580ac6da54d9760-e395-4f2a-8890-743f3562e1b3"
@@ -0,0 +1,16 @@
from tops.config import LazyCall as L
from ..generators.stylegan_unet import generator
from ..datasets.fdh import data
from ..discriminators.sg2_discriminator import discriminator, G_optim, D_optim, loss_fnc
from ..defaults import train, common, EMA
train.max_images_to_train = int(50e6)
train.batch_size = 64
G_optim.lr = 0.002
D_optim.lr = 0.002
data.train.loader.num_workers = 4
train.ims_per_val = int(1e6)
loss_fnc.r1_opts.lambd = .1
common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/21841da7-2546-4ce3-8460-909b3a63c58b13aac1a1-c778-4c8d-9b69-3e5ed2cde9de1524e76e-7aa6-4dd8-b643-52abc9f0792c"
common.model_md5sum = "3411478b5ec600a4219cccf4499732bd"
@@ -0,0 +1,14 @@
from tops.config import LazyCall as L
from ..generators.stylegan_unet import generator
from ..datasets.fdh import data
from ..discriminators.sg2_discriminator import discriminator, G_optim, D_optim, loss_fnc
from ..defaults import train, common, EMA
train.max_images_to_train = int(50e6)
G_optim.lr = 0.002
D_optim.lr = 0.002
generator.input_cse = False
data.load_embeddings = False
common.model_url = "https://folk.ntnu.no/haakohu/checkpoints/deep_privacy2/fdh_styleganL_nocse.ckpt"
common.model_md5sum = "fda0d809741bc67487abada793975c37"
generator.fix_errors = False
@@ -0,0 +1,15 @@
from .L_im72 import (
G_optim, D_optim, loss_fnc, common, EMA, train,
generator, discriminator, ckpt_mapper
)
from ...datasets.fdh_resampled_wds.fdh144 import data
generator.update(
dim=256,
dim_mults=[1, 2, 2, 2,2],
)
train.update(
generator_init_cfg="configs/fdh/triagan/L_im72.py",
)
train.max_images_to_train = int(110e6)
train.batch_size = 512
@@ -0,0 +1,35 @@
from ...discriminators.projected_discriminator import (
G_optim,
D_optim,
loss_fnc,
discriminator,
VIT_PATCH_MAE_LARGE,
RN50_CLIP
)
from ...defaults import common, EMA, train
from dp2.data.utils import get_coco_keypoints
from ...generators.triagan import generator, ckpt_mapper
from ...datasets.fdh_resampled_wds.fdh18 import data
train.update(
batch_size=1024,
ims_per_log=1024 * 20,
ims_per_val=int(10e6),
max_images_to_train=int(300e6),
broadcast_buffers=True,
fp16_ddp_accumulate=True,
)
loss_fnc.aug_fade_kimg = int(4e6)
generator.update(
input_keypoint_indices=list(range(len(get_coco_keypoints()))),
input_keypoints=True,
num_resnet_blocks=2,
)
loss_fnc.loss_type = "masked-hinge"
VIT_PATCH_MAE_LARGE.interp_size = (224, 224)
RN50_CLIP.interp_size = (288, 160)
discriminator.update(
backbones=[VIT_PATCH_MAE_LARGE, RN50_CLIP],
)
@@ -0,0 +1,27 @@
from .L_im144 import (
G_optim, D_optim, loss_fnc, common, EMA, train,
generator, discriminator, ckpt_mapper
)
from ...datasets.fdh_no_embeddings import data
from ...discriminators.projected_discriminator import (
VIT_PATCH_MAE_LARGE,
RN50_CLIP
)
from functools import partial
from tops.config import LazyCall as L
generator.update(
dim=128,
dim_mults=[1, 2, 4, 4, 4, 4],
)
train.update(
generator_init_cfg="configs/fdh/triagan/L_im144.py",
)
train.max_images_to_train = int(70e6)
train.batch_size = 128
VIT_PATCH_MAE_LARGE.interp_size = (224, 224)
RN50_CLIP.interp_size = None
discriminator.update(
backbones=[VIT_PATCH_MAE_LARGE, RN50_CLIP],
)
common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/e62a306a-5295-47dd-8a0e-4f7c05b9ecd44c9fbc76-5ce2-4dd0-9454-04776bef2745659fbec7-fa0a-485b-8501-c94a2439b601"
common.model_md5sum = "b649410e831b45f7800a89c738b411ce"
@@ -0,0 +1,13 @@
from .L_im18 import (
G_optim, D_optim, loss_fnc, common, EMA, train,
generator, discriminator, ckpt_mapper
)
from ...datasets.fdh_resampled_wds.fdh36 import data
generator.update(
dim_mults=[1, 1, 1],
)
train.update(
generator_init_cfg="configs/fdh/triagan/L_im18.py",
)
train.max_images_to_train = int(200e6)
@@ -0,0 +1,16 @@
from .L_im36 import (
G_optim, D_optim, loss_fnc, common, EMA, train,
generator, discriminator, ckpt_mapper
)
from ...datasets.fdh_resampled_wds.fdh72 import data
generator.update(
dim_mults=[1, 1, 1, 1],
)
train.update(
generator_init_cfg="configs/fdh/triagan/L_im36.py",
)
train.max_images_to_train = int(160e6)
common.model_md5sum = "291b9374a8f004fb9a2cfce59249be58"
common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/57f4101a-e1b7-414d-b616-ce4d71586fc7379379b4-c16e-41ba-aa3f-cd0f5af1ae94ecbce694-137f-4c80-8f7c-0b7ed6ace39f"
@@ -0,0 +1,8 @@
from ..base import generator, discriminator, D_optim, G_optim, common, EMA, train, loss_fnc
from .....datasets.fdh_resampled_wds.fdh18 import data
generator.update(
dim_mults=[1, 1],
layer_scale=True,
)
train.max_images_to_train = int(76e6)
@@ -0,0 +1,14 @@
from .im18 import (
G_optim, D_optim, loss_fnc, common, EMA, train,
generator, discriminator
)
from .....datasets.fdh_resampled_wds.fdh36 import data
generator.update(
dim_mults=[1, 1, 1],
)
train.update(
generator_init_cfg="configs/fdh/triagan/ablations/PG/im18.py",
)
train.max_images_to_train = int(61e6)
@@ -0,0 +1,14 @@
from .im18 import (
G_optim, D_optim, loss_fnc, common, EMA, train,
generator, discriminator
)
from .....datasets.fdh_resampled_wds.fdh72 import data
generator.update(
dim_mults=[1, 1, 1, 1],
)
train.update(
generator_init_cfg="configs/fdh/triagan/ablations/PG/im36.py",
)
train.max_images_to_train = int(50e6)
@@ -0,0 +1,27 @@
from ..L_im18 import (
generator,
discriminator,
D_optim,
G_optim,
common,
EMA,
train,
loss_fnc,
ckpt_mapper,
)
from ....datasets.fdh_resampled_wds.fdh72 import data
train.update(
batch_size=512,
max_images_to_train=int(50e6),
)
generator.update(
dim_mults=[1, 1, 1, 1],
dim=512,
num_resnet_blocks=1,
layer_scale=False,
use_noise=False,
)
loss_fnc.loss_type = "hinge"
@@ -0,0 +1,20 @@
from ..base import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
from .....discriminators.projected_discriminator import (
RN50_CLIP,
)
RN50_CLIP.interp_size = (288, 160)
discriminator.update(
backbones=[RN50_CLIP],
)
@@ -0,0 +1,14 @@
from .im72_CLIP import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
loss_fnc.loss_type = "masked-hinge"
@@ -0,0 +1,18 @@
from ..base import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
from .....discriminators.projected_discriminator import VIT_PATCH_MAE
VIT_PATCH_MAE.interp_size = (224, 224)
discriminator.update(
backbones=[VIT_PATCH_MAE],
)
@@ -0,0 +1,18 @@
from ..base import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
from .....discriminators.projected_discriminator import VIT_PATCH_MAE_LARGE
VIT_PATCH_MAE_LARGE.interp_size = (224, 224)
discriminator.update(
backbones=[VIT_PATCH_MAE_LARGE],
)
@@ -0,0 +1,14 @@
from .im72_MAEL import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
loss_fnc.loss_type = "masked-hinge"
@@ -0,0 +1,12 @@
from ..base import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
@@ -0,0 +1,14 @@
from .im72_MAEL_clip import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
loss_fnc.loss_type = "masked-hinge"
@@ -0,0 +1,14 @@
from .im72_MAE import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
loss_fnc.loss_type = "masked-hinge"
@@ -0,0 +1,19 @@
from ..base import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
from .....discriminators.projected_discriminator import VIT_PATCH_MAE_LARGE, RN50_CLIP
VIT_PATCH_MAE_LARGE.interp_size = (224, 224)
RN50_CLIP.interp_size = (288, 160)
discriminator.update(
backbones=[VIT_PATCH_MAE_LARGE, RN50_CLIP],
)
@@ -0,0 +1,14 @@
from .im72_MAE_clip import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
loss_fnc.loss_type = "masked-hinge"
@@ -0,0 +1,18 @@
from ..base import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
from .....discriminators.projected_discriminator import openclip_vit_b_16
openclip_vit_b_16.interp_size = (224, 224)
discriminator.update(
backbones=[openclip_vit_b_16],
)
@@ -0,0 +1,14 @@
from .im72_VIT_CLIP import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
loss_fnc.loss_type = "masked-hinge"
@@ -0,0 +1,18 @@
from ..base import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
from .....discriminators.projected_discriminator import deit_base_distilled_patch16_224
deit_base_distilled_patch16_224.interp_size = (224, 224)
discriminator.update(
backbones=[deit_base_distilled_patch16_224],
)
@@ -0,0 +1,14 @@
from .im72_VIT_IN import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
loss_fnc.loss_type = "masked-hinge"
@@ -0,0 +1,20 @@
from ..base import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
from .....discriminators.projected_discriminator import (
tf_efficientnet_lite0,
)
tf_efficientnet_lite0.interp_size = (288, 160)
discriminator.update(
backbones=[tf_efficientnet_lite0],
)
@@ -0,0 +1,14 @@
from .im72_effnet import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
loss_fnc.loss_type = "masked-hinge"
@@ -0,0 +1,18 @@
from ..base import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
from .....discriminators.projected_discriminator import RN50_CSE
RN50_CSE.interp_size = (288, 160)
discriminator.update(
backbones=[RN50_CSE],
)
@@ -0,0 +1,14 @@
from .im72_rn50_CSE import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
loss_fnc.loss_type = "masked-hinge"
@@ -0,0 +1,18 @@
from ..base import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
from .....discriminators.projected_discriminator import RN50_IN
RN50_IN.interp_size = (288, 160)
discriminator.update(
backbones=[RN50_IN],
)
@@ -0,0 +1,14 @@
from .im72_rn50_IN import (
G_optim,
D_optim,
loss_fnc,
common,
EMA,
train,
data,
generator,
discriminator,
ckpt_mapper,
)
loss_fnc.loss_type = "masked-hinge"
@@ -0,0 +1,5 @@
from dp2.generator.dummy_generators import GaussianBlurGenerator
from tops.config import LazyCall as L
from ...defaults import common
generator = L(GaussianBlurGenerator)()
@@ -0,0 +1,5 @@
from dp2.generator.dummy_generators import MaskOutGenerator
from tops.config import LazyCall as L
from ...defaults import common
generator = L(MaskOutGenerator)(noise="constant")
@@ -0,0 +1,4 @@
from dp2.generator.dummy_generators import PixelationGenerator
from tops.config import LazyCall as L
generator = L(PixelationGenerator)(pixelation_size=16)
@@ -0,0 +1,5 @@
from dp2.generator.dummy_generators import PixelationGenerator
from tops.config import LazyCall as L
from ...defaults import common
generator = L(PixelationGenerator)(pixelation_size=8)
@@ -0,0 +1,22 @@
from dp2.generator.stylegan_unet import StyleGANUnet
from tops.config import LazyCall as L
generator = L(StyleGANUnet)(
imsize="${data.imsize}",
im_channels="${data.im_channels}",
min_fmap_resolution=8,
cnum=64,
max_cnum_mul=8,
n_middle_blocks=0,
z_channels=512,
mask_output=True,
conv_clamp=256,
input_cse=True,
scale_grad=True,
cse_nc="${data.cse_nc}",
w_dim=512,
n_keypoints="${data.n_keypoints}",
input_keypoints=False,
input_keypoint_indices=[],
fix_errors=True
)
@@ -0,0 +1,43 @@
from dp2.generator.triagan import TriaGAN
from functools import partial
from tops.config import LazyCall as L
from dp2.generator.base import SG2StyleNet
generator = L(TriaGAN)(
im_channels="${data.im_channels}",
imsize="${data.imsize}",
dim=512,
dim_mults=[1, 1],
num_resnet_blocks=1,
n_middle_blocks=2,
z_channels=64,
w_dim=512,
norm_enc=True,
use_maskrcnn_mask=True,
input_keypoints=False,
input_keypoint_indices=[],
input_joint=True,
n_keypoints="${data.n_keypoints}",
norm_dec=True,
layer_scale=True,
use_noise=True,
style_net=L(SG2StyleNet)(
z_dim="${generator.z_channels}", w_dim="${generator.w_dim}"
),
)
def ckpt_map_G(state: dict):
new_state = dict()
for key, item in state.items():
new_key = key
for i in range(6):
if key == f"decoder.to_rgb.{i}.weight":
new_key = "decoder.to_rgb.weight"
elif key == f"decoder.to_rgb.{i}.bias":
new_key = "decoder.to_rgb.bias"
new_state[new_key] = item
return new_state
ckpt_mapper = L(partial)(ckpt_map_G)
@@ -0,0 +1,42 @@
# Getting Started
## Requirements
- Linux and MacOS (CPU only) are supported, but we recommend linux. The code is not tested on Windows, and it might be difficult to install detectron2 for windows (see [here](https://github.com/hukkelas/deep_privacy2/issues/10) for issue).
- GPU is not required for inference.
- 1-8 server-grade NVIDIA GPUs with at least 32GB of memory for training.
- Python >= 3.8.
## Install with Anaconda
We recommend to setup and install pytorch with [anaconda](https://www.anaconda.com/) following the [pytorch installation instructions](https://pytorch.org/get-started/locally/).
1. Clone repository: `git clone https://github.com/hukkelas/deep_privacy2/`.
2. Install using `setup.py`:
```
pip install -e .
```
or:
```
pip install git+https://github.com/hukkelas/deep_privacy2/
```
## Install with Docker
1. Install [nvidia-docker](https://github.com/NVIDIA/nvidia-docker) to support GPU acceleration.
2. Build the docker image using the [Dockerfile](Dockerfile).
```bash
# If you're not planning to train the network (or not use wandb logging), you can remove the WANDB_API_KEY argument.
docker build -t deep_privacy2 --build-arg WANDB_API_KEY=YOUR_WANDB_KEY --build-arg UID=$(id -u) --build-arg UNAME=$(id -un) .
```
3. Run the docker image with selected command:
```
docker run --runtime=nvidia --gpus '"device=0"' --name deep_privacy2 --ipc=host -u $(id -u) -v $PWD:/home/$(id -un) --rm deep_privacy2 python3 anonymize.py configs/anonymizers/deep_privacy1.py -i media/regjeringen.jpg -o output.png
```
## Environment variables
DeepPrivacy2 uses the following environment variables:
- `BASE_DATASET_DIR`: The directory where datasets are located. Defaults to `./data` if not set
- `BASE_OUTPUT_DIR`: The directory where outputs will be saved. Defaults to `./outputs`.
- `FBA_METRICS_CACHE`: The directory where intermediate calculations from metric calculation is saved. For example, FID statistics for real images.
- `TORCH_HOME`: The directory where checkpoints downloaded from URL are saved.
@@ -0,0 +1,6 @@
- [Getting started](QUICKSTART.md)
- [Anonymization](anonymization.md)
- [Development and Dataset Setup](training_and_development.md)
- [Gradio Demos](gradio_demos.md)
- [Building the Docs](building.md)
- [Anonymizing datasets](anonymizing_datasets.md)
@@ -0,0 +1,120 @@
# Anonymization
## Available Models
DeepPrivacy2 provides various anonymization models. Each model has a training config and an anonymization config.
- Training Config details the training setup for the generative model.
- Anonymization config details the inference setup for anonymization. The anonymization config can link to several training configs when multi-modal anonymization is used. See [here](anonymization.md#multi-modal-anonymization) for more info about multi-modal anonymization.
### Face Anonymization Models
| Dataset (Resolution) | Detection Type | Anonymization Config | Training Config | Comment |
|----------------------|-------------------------|--------------------------------------|--------------------------------| |
|FDF128 (128x128) | Face Bbox + 7 Keypoints | [configs/anonymizers/deep_privacy1.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/deep_privacy1.py) | *[configs/fdf/deep_privacy1.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdf/deep_privacy1.py) | Not recommended unless you have large head rotations.|
| FDF128 (128x128) | Face Bbox | [configs/anonymizers/face_fdf128.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/face_fdf128.py) | [configs/fdf/stylegan_fdf128.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdf/stylegan_fdf128.py) | Recommended model if all faces have a resolution < 128x128.|
| FDF256 (256x256) | Face Bbox | [configs/anonymizers/face.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/face.py) | [configs/fdf/stylegan.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdf/stylegan.py) | Recommended model if any face has a resolution > 128x128.|
\*Note that the weights for [configs/fdf/deep_privacy1.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdf/deep_privacy1.py) are not available to retrain, as these weights are ported from the original [DeepPrivacy repository](s://github.com/hukkelas/DeepPrivacy).
The **face bbox** is the bounding box detected by [DSFD](http://github.com/hukkelas/DSFD-Pytorch-Inference).
The **7 keypoints** are the first 7 keypoints detected by a Keypoint R-CNN model trained on COCO, indicating nose, eyes, ears, and shoulders.
### Full-body Anonymization Models
| Detection Type | Anonymization Config | Training Config | Comment |
|---|---|---| |
| Segmentation Mask | [configs/anonymizers/FB_nocse.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/FB_nocse.py) | [configs/fdh/styleganL_nocse.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/configs/fdh/styleganL_nocse.py) | Generally produces poor quality human figures except for masks that explicitly encodes the pose of the person. |
| CSE + Segmentation Mask | [configs/anonymizers/FB_cse.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/FB_cse.py) | [configs/fdh/styleganL.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/configs/fdh/styleganL.py) | Recommended model. |
The FDH dataset with a resolution of 288x160 is used to train all full-body anonymization models.
The **CSE** refers to surface maps from a Continuous Surface Embedding model. **Segementation mask** refers to a instance segmentation mask, where we use the output of a Mask R-CNN model trained on COCO.
The **17 keypoints** are keypoints following the COCO format.
## Using anonymize.py
[anonymize.py](anonymize.py) is the main script for anonymization.
The typical usage is
```
python3 anonymize.py configs/anonymizers/FB_cse.py -i path_to_image.png
```
where the first argument is the chosen anonymizer (see above for the different models) and the second a path to an image/folder/video.
There are several optional arguments, see `python3 anonymize.py --help` for more info.
```
python3 anonymize.py --help
Usage: anonymize.py [OPTIONS] CONFIG_PATH
config_path: Specify the path to the anonymization model to use.
Options:
-i, --input_path TEXT Input path. Accepted inputs: images, videos,
directories.
-o, --output_path PATH Output path to save. Can be directory or
file.
-v, --visualize Visualize the result
--max-res INTEGER Maximum resolution of height/wideo
--start-time, --st INTEGER Start time (second) for vide anonymization
--end-time, --et INTEGER End time (second) for vide anonymization
--fps INTEGER FPS for anonymization
--detection-score-threshold, --dst FLOAT RANGE
Detection threshold, threshold applied for
all detection models. [0<=x<=1]
--visualize-detection, --vd Visualize only detections without running
anonymization.
--multi-modal-truncation, --mt Enable multi-modal truncation proposed by:
https://arxiv.org/pdf/2202.12211.pdf
--cache Enable detection caching. Will save and load
detections from cache.
--amp Use automatic mixed precision for generator
forward pass
-t, --truncation_value FLOAT RANGE
Latent interpolation truncation value.
[0<=x<=1]
--track Track detections over frames. Will use the
same latent variable (z) for tracked
identities.
--seed INTEGER Set random seed for generating images.
--person-generator PATH Config path to unconditional person
generator
--cse-person-generator PATH Config path to CSE-guided person generator
--webcam Read image from webcam feed.
--help Show this message and exit.
```
### Singe image anonymization
```
python3 anonymize.py configs/anonymizers/FB_cse.py -i path_to_image.png --output_path output.png
```
### Folder anonymization
If a folder is given as the input, all image and video files in the given folder will be anonymized and placed under --output_path. The script will duplicate the directory structure/filenames in the given folder for the output.
```
python3 anonymize.py configs/anonymizers/FB_cse.py -i path/to/input/folder --output_path output_folder
```
### Video anonymization
```
python3 anonymize.py configs/anonymizers/FB_cse.py -i path_to_video.mp4 --output_path output.mp4
```
### Webcam anonymization
```
python3 anonymize.py configs/anonymizers/FB_cse.py --webcam
```
## Multi-modal anonymization
DeepPrivacy2 supports anonymizing individuals detected by different modalities (e.g. faces and bodies).
![](media/header.png)
The following multi-modal anonymization models are provided:
| Config File | Detection Modalities | Synthesis Configs | Modalities |
| --- |---| ---| --- |
| [configs/anonymizers/FB_cse_mask_face.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/FB_cse_mask_face.py) | CSE+Segmentation Masks, Segmentation Masks, Face bbox | [configs/fdh/styleganL.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdh/styleganL.py), [configs/fdh/styleganL_nocse.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdh/styleganL_nocse.py), [configs/fdf/stylegan.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdf/stylegan.py) | Bodies (detected w/CSE), bodies (not detected w/CSE), Faces|
| [configs/anonymizers/FB_cse_mask.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/FB_cse_mask.py) | CSE+Segmentation Masks, Segmentation Masks | [configs/fdh/styleganL.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdh/styleganL.py), [configs/fdh/styleganL_nocse.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdh/styleganL_nocse.py), | Bodies (detected w/CSE), bodies (not detected w/CSE)|
Note that combining different synthesis networks listed [previously](anonymization.md#available-models) is straightforward, see for eaxmple [configs/anonymizers/FB_cse_mask_face.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/FB_cse_mask_face.py).
@@ -0,0 +1,107 @@
# Anonymizing datasets
This document contains information to reproduce the experiments from the paper "Does Image Anonymization Impact Computer Vision Training?" published at CVPR Workshop on Autonomous Driving 2023.
## Dataset setup
The paper evaluates on BDD100k, Cityscapes, and COCO. Download the datasets following the instructions from each, and keep the original datafile structure as documented for each dataset. The code expects the following folder structre for the different datasets:
### BDD100k
```
bdd100k-directory/
annotated_keypoints_train.json # Can be downloaded from https://drive.google.com/file/d/1apTK26BuERnruEDqWJ2LdLQ9xoM-aRRw/view?usp=sharing
face_boxes_train.json # Can be downloaded from https://drive.google.com/file/d/1D2p1g8mC-0qu9AqHCIsTmvqcxBz9Ug-t/view?usp=sharing
images/
jsons/
labels/
```
### COCO
```
coco-directory/
boxes_train2017.json # Can be downloaded from https://drive.google.com/file/d/1FS9ZOymm7XMmZd_ocH-ikYioJlH6J63c/view?usp=sharing
boxes_val2017.json # Can be downloaded from https://drive.google.com/file/d/12B5a_apfUOr8UJK8ED2g1EX6kU1IxWsw/view?usp=sharing
annotations/
person_keypoints_train2017.json
captions_val2017.json
instances_val2017.json
captions_train2017.json
person_keypoints_val2017.json
instances_train2017.json
train2017/
...
val2017/
...
```
### Cityscapes
```
cityscapes-directory/
annotated_keypoints_train.json # Can be downloaded from https://drive.google.com/file/d/1Acv7A1hONHUH1MvaXwCHQ95-f5LUEl7c/view?usp=sharing
annotated_keypoints_val.json # Can be downloaded from https://drive.google.com/file/d/1WkfIhuKlcie9DjMt5IgL10FzIwUFrtkX/view?usp=sharing
face_boxes_train.json # Can be downloaded from https://drive.google.com/file/d/1O56H4xbx_DgIkiF1E8JTZUjYmuHgO0Bs/view?usp=sharing
camera/
gtFine/
leftImg8bit/
```
## Anonymizing
All scripts for full-body anonymization accepts the following three config files: [configs/anonymizers/FB_triagan.py](configs/anonymizers/FB_triagan.py), [configs/anonymizers/traditional/body/gaussian.py](configs/anonymizers/traditional/body/gaussian.py), and [configs/anonymizers/traditional/body/maskout.py](configs/anonymizers/traditional/body/maskout.py).
All scripts for face anonymization accepts the following three config files: [configs/anonymizers/face_fdf128.py](configs/anonymizers/face_fdf128.py), [configs/anonymizers/traditional/face/gaussian.py](configs/anonymizers/traditional/face/gaussian.py), and [configs/anonymizers/traditional/face/maskout.py](configs/anonymizers/traditional/face/maskout.py).
All scripts accepts the following config files:
Some of the scripts have additional arguments:
- `--match-histogram`: Enables naive histogram matching
- `--sampler`: Select the sampling approach of the latent variable
- `--n-sampling-steps`: Setting this to > 1 enables histogram matching via latent optimization. Default is set to 100 for experiments in paper.
- `--min_size`: Set the minimum resolution of bboxes to anonymize.
**Note**: The path to the dataset and directory to save the anonymized dataset is hard-coded in the code. Change these yourself, all dataset sources and targets are saved under the path `/mnt/work2/haakohu/datasets` for my setup.
### Anonymizing COCO
**Face Anonymization:**
```
python3 -m tools.anonymization.coco.anonymize_faces configs/anonymizers/face_fdf128.py
```
We experimented with higher-resolution face anonymization for the COCO dataset. To refine the face anonymization, run:
```
python3 -m tools.anonymization.coco.refine_faces
```
Note that this has to be run **after** the low-resolution face anonymizer.
**Full-body Anonymization:**
```
python3 -m tools.anonymization.coco.anonymize_body configs/anonymizers/FB_triagan.py
```
### Anonymizing BDD100k
**Face Anonymization:**
```
python3 -m tools.anonymization.bdd100k.anonymize_face configs/anonymizers/face_fdf128.py
```
**Full-body Anonymization:**
```
python3 -m tools.anonymization.bdd100k.anonymize_body configs/anonymizers/FB_triagan.py
```
### Anonymizing Cityscapes
**Face Anonymization:**
```
python3 -m tools.anonymization.cityscapes.anonymize_faces configs/anonymizers/face_fdf128.py
```
**Full-body Anonymization:**
```
python3 -m tools.anonymization.cityscapes.anonymize_body configs/anonymizers/FB_triagan.py
```
## Training the models on anonymized datasets
See the paper to reproduce our experiments to train and validate on the anonymized datasets.
@@ -0,0 +1,10 @@
# Building the Docs
First, install [docsify](https://docsify.js.org/#/quickstart).
Then:
```
docsify serve docs/
```
from the root folder.
@@ -0,0 +1,35 @@
# Gradio Demos
## Face Anonymization
Test it on [Hugginface](https://huggingface.co/spaces/haakohu/deep_privacy2_face), or run it on your local computer:
```
python3 -m gradio_demos.face
```
## Full-body anonymization
Test it on [Hugginface](https://huggingface.co/spaces/haakohu/deep_privacy2), or run it on your local computer:
```
python3 -m gradio_demos.body_cse
```
## Attribute guided anonymization
DeepPrivacy2 allows for controllable anonymization through text prompts by adapting [StyleMC](https://github.com/catlab-team/stylemc).
StyleMC finds global semantically meaningful directions in the GAN latent space by manipulating images towards a given text prompt with a [CLIP](https://github.com/openai/CLIP)-based loss.
<center>
<img src="https://raw.githubusercontent.com/hukkelas/deep_privacy2/master/media/stylemc_example.jpg" alt= “” width="50%">
</center>
The repository includes a [gradio](https://gradio.app/) demo for interactive text-guided anonymization.
To use the demo, first:
1. Download the FDF256 dataset (see [here](training_and_development.md#dataset-setup)). Only the validation set is required.
2. Run the following:
```
python3 attribute_guided_demo.py
```
The script will spin up a local webserver.
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="description" content="Description">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/docsify@4/lib/themes/vue.css">
</head>
<body>
<div id="app"></div>
<script>
window.$docsify = {
name: 'DeepPrivacy2 Docs',
repo: 'https://github.com/hukkelas/deep_privacy2',
loadSidebar: true,
homepage: 'QUICKSTART.md',
subMaxLevel: 3
}
</script>
<!-- Docsify v4 -->
<script src="//cdn.jsdelivr.net/npm/docsify@4"></script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

@@ -0,0 +1,43 @@
# Reproducing results from: "Synthesizing Anyone, Anywhere, in Any Pose"
The dataset for FDH has to be set up for the triagan paper. See [training_and_development](here) for more info.
See the supplementary material for the paper for more information.
### Table 1 results:
#### Training
```
# Model A
python3 train.py configs/fdh/triagan/ablations/fnets/im72_effnet.py
# B
python3 train.py configs/fdh/triagan/ablations/fnets/im72_effnet_MAD.py
# C
python3 train.py configs/fdh/triagan/ablations/fnets/im72_MAEL_clip_MAD.py
# D - requires progressive growing
python3 train.py configs/fdh/triagan/ablations/PG/im18.py
python3 train.py configs/fdh/triagan/ablations/PG/im36.py
python3 train.py configs/fdh/triagan/ablations/PG/im72.py
# E - required progrssive growing
python3 train.py configs/fdh/triagan/L_im18.py
python3 train.py configs/fdh/triagan/L_im36.py
python3 train.py configs/fdh/triagan/L_im72.py
python3 train.py configs/fdh/triagan/L_im144.py
python3 train.py configs/fdh/triagan/L_im288.py
```
#### Validation
For each config path, you can run:
```
python3 -m tools.triagan.validate_triaGAN
```
All table 1 results are computed from the model with resolution (72x40)
### Figure 3
All models in figure 3 is included in `configs/fdh/triagan/ablations/fnets`
### Table 2 results
```
python3 -m tools.triagan.validate_triaGAN configs/fdh/styleganL.py
python3 -m tools.triagan.validate_triaGAN configs/fdh/triagan/L_im288.py
```
@@ -0,0 +1,57 @@
# Training, development and Dataset Setup
## Training
First, download dataset for training (see below).
To start training, type the following:
```
python3 train.py configs/fdh/styleganL.py
```
The training automatically logs to [wandb](https://wandb.ai/).
## Model development utility scripts
**Dataset inspection:** To inspect the training dataset, you can use:
```
python3 -m tools.inspect_dataset configs/fdh/styleganL.py
```
**Sanity check:**
```
python3 -m tools.dryrun configs/fdh/styleganL.py
```
**Output visualization:** To visualize output of trained models:
```
python3 -m tools.show_examples configs/fdh/styleganL.py
```
## Calculating metrics
```
python3 validate.py configs/fdh/styleganL.py
```
**NOTE:** The metrics calculated with validate.py will slightly differ from training metrics, as validate.py disables automatic mixed precision.
## Dataset Setup
**Setting Data directory:**
The default dataset directory is ./data. If you want to change the dataset directory, set the environment variable `BASE_DATASET_DIR`. For example, `export BASE_DATASET_DIR=/work/data/`.
### FDF256
Follow the instructions [here](https://github.com/hukkelas/FDF/blob/master/FDF256.md) to download the FDF256 dataset. The dataset should be placed in the directory: `data/fdf256`.
### FDH
Follow the instructions [here](https://www.github.com/hukkelas/FDH) to download the FDH dataset. The dataset should be placed in the directory: `data/fdh`.
#### FDH for TriA-GAN paper
TriA-GAN requires the FDH dataset to be prepared for progressive growing training. This can be done by first downloading the dataset to 'data/fdh'.
Then, run:
```
python3 -m tools.dataset.copy_fdh_remove_embedding
```
Followed by
```
python3 -m tools.dataset.create_webdataset_progressive
```
@@ -0,0 +1 @@
from .anonymizer import Anonymizer
@@ -0,0 +1,240 @@
from pathlib import Path
from typing import Union, Optional
import numpy as np
import torch
import tops
import torchvision.transforms.functional as F
from motpy import Detection, MultiObjectTracker
from dp2.utils import load_config
from dp2.infer import build_trained_generator
from dp2.detection.structures import (
CSEPersonDetection,
FaceDetection,
PersonDetection,
VehicleDetection,
)
from tops import logger
from stylemc import get_and_cache_direction, get_stylesW, init_affine_modules
class Anonymizer:
def __init__(
self,
detector,
load_cache: bool = False,
person_G_cfg: Optional[Union[str, Path]] = None,
cse_person_G_cfg: Optional[Union[str, Path]] = None,
face_G_cfg: Optional[Union[str, Path]] = None,
car_G_cfg: Optional[Union[str, Path]] = None,
) -> None:
self.detector = detector
self.generators = {
k: None
for k in [
CSEPersonDetection,
PersonDetection,
FaceDetection,
VehicleDetection,
]
}
self.load_cache = load_cache
self.generator_cfgs = dict()
if cse_person_G_cfg is not None:
self.generator_cfgs[CSEPersonDetection] = load_config(cse_person_G_cfg)
self.generators[CSEPersonDetection] = build_trained_generator(
self.generator_cfgs[CSEPersonDetection]
)
tops.logger.log(f"Loaded generator from: {cse_person_G_cfg}")
if person_G_cfg is not None:
self.generator_cfgs[PersonDetection] = load_config(person_G_cfg)
self.generators[PersonDetection] = build_trained_generator(
self.generator_cfgs[PersonDetection]
)
tops.logger.log(f"Loaded generator from: {cse_person_G_cfg}")
if face_G_cfg is not None:
self.generator_cfgs[FaceDetection] = load_config(face_G_cfg)
self.generators[FaceDetection] = build_trained_generator(
self.generator_cfgs[FaceDetection]
)
tops.logger.log(f"Loaded generator from: {face_G_cfg}")
if car_G_cfg is not None:
self.generator_cfgs[VehicleDetection] = load_config(car_G_cfg)
self.generators[VehicleDetection] = build_trained_generator(
self.generator_cfgs[VehicleDetection]
)
tops.logger.log(f"Loaded generator from: {face_G_cfg}")
self.dl = None
def initialize_tracker(self, fps: float):
self.tracker = MultiObjectTracker(dt=1 / fps)
self.track_to_z_idx = dict()
def reset_tracker(self):
self.track_to_z_idx = dict()
def forward_G(
self,
G,
batch,
multi_modal_truncation: bool,
amp: bool,
z_idx: Optional[int],
truncation_value: float,
detection_type,
all_styles=None,
text_prompt=None,
text_prompt_strength: Optional[float] = None,
):
batch["img"] = F.normalize(
batch["img"].float(),
[0.5 * 255, 0.5 * 255, 0.5 * 255],
[0.5 * 255, 0.5 * 255, 0.5 * 255],
)
batch["condition"] = batch["mask"].float() * batch["img"]
cfg = self.generator_cfgs[detection_type]
if text_prompt is not None and self.dl is None:
cfg.train.batch_size = 1
self.dl = tops.config.instantiate(cfg.data.val.loader)
init_affine_modules(G, batch)
if z_idx is None:
z_idx = np.random.randint(0, 2**32)
state = np.random.RandomState(seed=z_idx)
z = state.normal(size=(1, G.z_channels)).astype(np.float32)
z = tops.to_cuda(torch.from_numpy(z))
if not hasattr(G, "style_net"):
if multi_modal_truncation:
logger.warn("The current generator does not support multi-modal truncation.")
w = None
z = G.get_z(z=z, truncation_value=truncation_value)
elif multi_modal_truncation:
w = G.style_net.multi_modal_truncate(
truncation_value,
w_indices=[z_idx % len(G.style_net.w_centers)],
z=z,
)
else:
w = G.style_net.get_truncated(truncation_value, z=z)
if text_prompt is not None:
direction = get_and_cache_direction(cfg.output_dir, self.dl, G, text_prompt)
all_styles = get_stylesW(w)
all_styles = all_styles + direction * text_prompt_strength
all_styles = all_styles
elif all_styles is not None:
all_styles = next(all_styles)
with torch.cuda.amp.autocast(amp):
if all_styles is not None:
anonymized_im = G(**batch, s=iter(all_styles))["img"]
else:
anonymized_im = G(**batch, w=w)["img"]
anonymized_im = (anonymized_im + 1).div(2).clamp(0, 1).mul(255)
return anonymized_im
@torch.no_grad()
def anonymize_detections(
self, im, detection, update_identity=None, z_idx=None, **synthesis_kwargs
):
G = self.generators[type(detection)]
if G is None:
return im
C, H, W = im.shape
if update_identity is None:
update_identity = [True for i in range(len(detection))]
for idx in range(len(detection)):
if not update_identity[idx]:
continue
batch = detection.get_crop(idx, im)
x0, y0, x1, y1 = batch.pop("boxes")[0]
batch = {k: tops.to_cuda(v) for k, v in batch.items()}
anonymized_im = self.forward_G(
G,
batch,
**synthesis_kwargs,
z_idx=None if z_idx is None else z_idx[idx],
detection_type=type(detection),
)
gim = F.resize(
anonymized_im[0],
(y1 - y0, x1 - x0),
interpolation=F.InterpolationMode.BICUBIC,
antialias=True,
)
mask = F.resize(
batch["mask"][0],
(y1 - y0, x1 - x0),
interpolation=F.InterpolationMode.NEAREST,
).squeeze(0)
# Remove padding
pad = [max(-x0, 0), max(-y0, 0)]
pad = [*pad, max(x1 - W, 0), max(y1 - H, 0)]
def remove_pad(x):
return x[
..., pad[1] : x.shape[-2] - pad[3], pad[0] : x.shape[-1] - pad[2]
]
gim = remove_pad(gim)
mask = remove_pad(mask) > 0.5
x0, y0 = max(x0, 0), max(y0, 0)
x1, y1 = min(x1, W), min(y1, H)
mask = mask.logical_not()[None].repeat(3, 1, 1)
im[:, y0:y1, x0:x1][mask] = gim[mask].round().clamp(0, 255).byte()
return im
def visualize_detection(
self, im: torch.Tensor, cache_id: str = None
) -> torch.Tensor:
im = tops.to_cuda(im)
all_detections = self.detector.forward_and_cache(
im, cache_id, load_cache=self.load_cache
)
im = im.cpu()
for det in all_detections:
im = det.visualize(im)
return im
@torch.no_grad()
def forward(
self,
im: torch.Tensor,
cache_id: str = None,
track=True,
detections=None,
**synthesis_kwargs,
) -> torch.Tensor:
assert im.dtype == torch.uint8
im = tops.to_cuda(im)
all_detections = detections
if detections is None:
if self.load_cache:
all_detections = self.detector.forward_and_cache(im, cache_id, load_cache=True)
else:
all_detections = self.detector(im)
if hasattr(self, "tracker") and track:
[_.pre_process() for _ in all_detections]
boxes = np.concatenate([_.boxes for _ in all_detections])
boxes = [Detection(box) for box in boxes]
self.tracker.step(boxes)
track_ids = self.tracker.detections_matched_ids
z_idx = []
for track_id in track_ids:
if track_id not in self.track_to_z_idx:
self.track_to_z_idx[track_id] = np.random.randint(0, 2**32 - 1)
z_idx.append(self.track_to_z_idx[track_id])
z_idx = np.array(z_idx)
idx_offset = 0
for detection in all_detections:
zs = None
if hasattr(self, "tracker") and track:
zs = z_idx[idx_offset : idx_offset + len(detection)]
idx_offset += len(detection)
im = self.anonymize_detections(im, detection, z_idx=zs, **synthesis_kwargs)
return im.cpu()
def __call__(self, *args, **kwargs):
return self.forward(*args, **kwargs)
@@ -0,0 +1,87 @@
import torch
import tops
import numpy as np
from kornia.color import rgb_to_hsv
from dp2 import utils
from kornia.enhance import histogram
from .anonymizer import Anonymizer
import torchvision.transforms.functional as F
from skimage.exposure import match_histograms
from kornia.filters import gaussian_blur2d
class LatentHistogramMatchAnonymizer(Anonymizer):
def forward_G(
self,
G,
batch,
multi_modal_truncation: bool,
amp: bool,
z_idx: int,
truncation_value: float,
idx: int,
n_sampling_steps: int = 1,
all_styles=None,
):
batch["img"] = F.normalize(batch["img"].float(), [0.5*255, 0.5*255, 0.5*255], [0.5*255, 0.5*255, 0.5*255])
batch["condition"] = batch["mask"].float() * batch["img"]
assert z_idx is None and all_styles is None, "Arguments not supported with n_sampling_steps > 1."
real_hls = rgb_to_hsv(utils.denormalize_img(batch["img"]))
real_hls[:, 0] /= 2 * torch.pi
indices = [1, 2]
hist_kwargs = dict(
bins=torch.linspace(0, 1, 256, dtype=torch.float32, device=tops.get_device()),
bandwidth=torch.tensor(1., device=tops.get_device()))
real_hist = [histogram(real_hls[:, i].flatten(start_dim=1), **hist_kwargs) for i in indices]
if multi_modal_truncation:
w = G.style_net.multi_modal_truncate(
truncation_value=truncation_value, n=batch["condition"].shape[0]).detach()
else:
w = G.style_net.get_truncated(truncation_value, n=batch["condition"].shape[0]).detach()
assert z_idx is None and all_styles is None, "Arguments not supported with n_sampling_steps > 1."
w.requires_grad = True
optim = torch.optim.Adam([w])
for j in range(n_sampling_steps):
with torch.set_grad_enabled(True):
with torch.cuda.amp.autocast(amp):
anonymized_im = G(**batch, truncation_value=None, w=w)["img"]
fake_hls = rgb_to_hsv(anonymized_im*0.5 + 0.5)
fake_hls[:, 0] /= 2 * torch.pi
fake_hist = [histogram(fake_hls[:, i].flatten(start_dim=1), **hist_kwargs) for i in indices]
dist = sum([utils.torch_wasserstein_loss(r, f) for r, f in zip(real_hist, fake_hist)])
dist.backward()
if w.grad.sum() == 0:
break
assert w.grad.sum() != 0
optim.step()
optim.zero_grad()
if dist < 0.02:
break
anonymized_im = (anonymized_im+1).div(2).clamp(0, 1).mul(255)
return anonymized_im
class HistogramMatchAnonymizer(Anonymizer):
def forward_G(self, G, batch, *args, **kwargs):
rimg = batch["img"]
anonymized_im = super().forward_G(G, batch, *args, **kwargs)
equalized_gim = match_histograms(tops.im2numpy(anonymized_im.round().clamp(0, 255).byte()), tops.im2numpy(rimg))
if equalized_gim.dtype != np.uint8:
equalized_gim = equalized_gim.astype(np.float32)
assert equalized_gim.dtype == np.float32, equalized_gim.dtype
equalized_gim = tops.im2torch(equalized_gim, to_float=False)[0]
else:
equalized_gim = tops.im2torch(equalized_gim, to_float=False).float()[0]
equalized_gim = equalized_gim.to(device=rimg.device)
assert equalized_gim.dtype == torch.float32
gaussian_mask = 1 - (batch["maskrcnn_mask"][0].repeat(3, 1, 1) > 0.5).float()
gaussian_mask = gaussian_blur2d(gaussian_mask[None], kernel_size=[19, 19], sigma=[10, 10])[0]
gaussian_mask = gaussian_mask / gaussian_mask.max()
anonymized_im = gaussian_mask * equalized_gim + (1-gaussian_mask) * anonymized_im
return anonymized_im
@@ -0,0 +1,40 @@
import torch
import tops
from .utils import collate_fn
def get_dataloader(
dataset, gpu_transform: torch.nn.Module,
num_workers,
batch_size,
infinite: bool,
drop_last: bool,
prefetch_factor: int,
shuffle,
channels_last=False
):
sampler = None
dl_kwargs = dict(
pin_memory=True,
)
if infinite:
sampler = tops.InfiniteSampler(
dataset, rank=tops.rank(),
num_replicas=tops.world_size(),
shuffle=shuffle
)
elif tops.world_size() > 1:
sampler = torch.utils.data.DistributedSampler(
dataset, shuffle=shuffle, num_replicas=tops.world_size(), rank=tops.rank())
dl_kwargs["drop_last"] = drop_last
else:
dl_kwargs["shuffle"] = shuffle
dl_kwargs["drop_last"] = drop_last
dataloader = torch.utils.data.DataLoader(
dataset, sampler=sampler, collate_fn=collate_fn,
batch_size=batch_size,
num_workers=num_workers, prefetch_factor=prefetch_factor,
**dl_kwargs
)
dataloader = tops.DataPrefetcher(dataloader, gpu_transform, channels_last=channels_last)
return dataloader

Some files were not shown because too many files have changed in this diff Show More