Spaces:
Sleeping

File size: 3,435 Bytes
5a5e72e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from __future__ import annotations

import torch
from torch import nn

from .decoder_native_wflw98 import (
    ALIGNED_IMAGE_SIZE,
    NORMALIZED_COORDINATE_LIMIT,
    NativeWFLW98Error,
    warp_image_wflw98,
)
from .decoder_geometry_policy import LANDMARK_COUNT
from .decoder_heads import DECODER_FEATURE_DIM, _make_decoder_heads


def _landmarks(value: torch.Tensor, *, label: str) -> None:
    if not torch.is_tensor(value) or value.dtype != torch.float32:
        raise NativeWFLW98Error(f"{label} must be float32")
    if value.ndim != 3 or value.shape[1:] != (LANDMARK_COUNT, 2) or value.shape[0] < 1:
        raise NativeWFLW98Error(f"{label} must have nonempty shape (B,98,2)")
    if not torch.isfinite(value.detach()).all():
        raise NativeWFLW98Error(f"{label} contains non-finite coordinates")
    if (value.detach().abs() > NORMALIZED_COORDINATE_LIMIT).any():
        raise NativeWFLW98Error(f"{label} exceeds inclusive range [-2,2]")


class NativeWFLW98FaceWarp(nn.Module):
    def __init__(
        self,
        mean_landmarks: torch.Tensor,
    ) -> None:
        super().__init__()
        mean = torch.as_tensor(mean_landmarks)
        if mean.shape != (LANDMARK_COUNT, 2):
            raise NativeWFLW98Error("mean landmarks must have shape (98,2)")
        _landmarks(mean[None], label="mean landmarks")
        self.register_buffer("mean_landmarks", mean.detach().clone())

    def forward(
        self,
        texture: torch.Tensor,
        landmarks: torch.Tensor,
    ) -> tuple[torch.Tensor, tuple[dict[str, float], ...]]:
        _landmarks(landmarks, label="predicted landmarks")
        source = self.mean_landmarks[None].expand(landmarks.shape[0], -1, -1)
        return warp_image_wflw98(texture, source, landmarks)


class NativeWFLW98FaceDecoder(nn.Module):
    def __init__(
        self,
        mean_landmarks: torch.Tensor,
    ) -> None:
        super().__init__()
        (self.fc3, self.geometry_head, self.texture_fc, self.texture_decoder) = (
            _make_decoder_heads(landmark_count=LANDMARK_COUNT, bounded_geometry=False)
        )
        self.warp = NativeWFLW98FaceWarp(mean_landmarks)

    def forward(
        self,
        feature: torch.Tensor,
    ) -> dict[str, torch.Tensor | tuple[dict[str, float], ...]]:
        if (
            not torch.is_tensor(feature)
            or feature.dtype != torch.float32
            or feature.ndim != 2
            or feature.shape[1] != DECODER_FEATURE_DIM
            or feature.shape[0] < 1
        ):
            raise ValueError("feature must have nonempty float32 shape (B,4096)")
        if not torch.isfinite(feature.detach()).all():
            raise ValueError("feature contains non-finite values")
        shared = torch.relu(self.fc3(feature))
        landmarks = self.geometry_head(shared).reshape(-1, LANDMARK_COUNT, 2)
        _landmarks(landmarks, label="predicted landmarks")
        seed = torch.relu(self.texture_fc(shared)).reshape(-1, 256, 14, 14)
        texture = self.texture_decoder(seed)
        if texture.shape[1:] != (3, ALIGNED_IMAGE_SIZE, ALIGNED_IMAGE_SIZE):
            raise ValueError("texture decoder changed the registered RGB224 canvas")
        rendered, diagnostics = self.warp(texture, landmarks)
        return {
            "landmarks": landmarks,
            "registered_texture": texture,
            "rendered_face": rendered,
            "warp_diagnostics": diagnostics,
        }