File size: 11,523 Bytes
c4a514c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""
Module 4 – Facial Simulation via Landmark-Guided Gaussian RBF Warping.

Applies procedure-specific morphological transformations directly to the
target anatomical region of the uploaded photograph using a dense inverse
displacement field and bicubic `cv2.remap`, preserving crisp skin texture
and leaving non-target regions untouched.
"""

import os
import cv2
import numpy as np

from mfaf_net.module1_feature_extraction import REGION_INDICES

# ---------------------------------------------------------------------------
# Procedure-specific landmark displacement rules
# Each entry: (group_name, axis, factor_rel_to_face, direction)
#   axis      : 'x' or 'y'
#   factor    : fraction of face width/height to displace
#   direction : +1 (down/right), -1 (up/left), or 'inward' (toward face centerline)
# ---------------------------------------------------------------------------
PROCEDURE_RULES = {
    'rhinoplasty': [
        ('nose_bridge_sides', 'x', 0.042, 'inward'),
        ('nose_alar', 'x', 0.055, 'inward'),
        ('nose_tip', 'y', 0.028, -1),
    ],
    'blepharoplasty': [
        ('upper_eyelid', 'y', 0.022, -1),
        ('lower_eyelid', 'y', 0.015, -1),
    ],
    'rhytidectomy': [
        ('jawline', 'y', 0.030, -1),
        ('jawline', 'x', 0.025, 'inward'),
        ('cheeks', 'y', 0.020, -1),
    ],
    'genioplasty': [
        ('chin_tip', 'y', 0.036, +1),
        ('chin_sides', 'x', 0.022, 'inward'),
    ],
    'forehead_surgery': [
        ('forehead', 'y', 0.026, -1),
        ('eyebrows', 'y', 0.012, -1),
    ],
    'brow_lift': [
        ('eyebrows', 'y', 0.032, -1),
    ],
}

LANDMARK_GROUPS = {
    'nose_bridge_sides': [196, 3, 236, 198, 419, 248, 456, 420],
    'nose_alar': [129, 98, 49, 209, 358, 327, 279, 429],
    'nose_tip': [1, 2, 4, 5, 19, 94],
    'upper_eyelid': [159, 160, 158, 157, 161, 223, 224, 386, 385, 387, 388, 384, 443, 444],
    'lower_eyelid': [145, 144, 153, 154, 229, 230, 374, 373, 380, 381, 449, 450],
    'jawline': [172, 136, 150, 149, 176, 58, 132, 397, 365, 379, 378, 400, 288, 361],
    'cheeks': [205, 206, 50, 123, 425, 426, 280, 352],
    'chin_tip': [152, 175, 199, 200],
    'chin_sides': [148, 176, 377, 400],
    'forehead': [10, 109, 67, 103, 54, 338, 297, 332, 284, 151, 9, 8],
    'eyebrows': [70, 63, 105, 66, 107, 46, 53, 52, 65, 55,
                 300, 293, 334, 296, 336, 276, 283, 282, 295, 285],
}

# Anchor landmarks locked near zero displacement so adjacent features remain stable
PROCEDURE_ANCHORS = {
    'rhinoplasty': [133, 362, 33, 263, 0, 61, 291, 152],
    'blepharoplasty': [33, 133, 362, 263, 1, 61, 291, 105, 334],
    'rhytidectomy': [1, 33, 263, 61, 291, 13, 14, 152, 10],
    'genioplasty': [14, 17, 61, 291, 1, 172, 397],
    'forehead_surgery': [159, 386, 33, 263, 1, 152],
    'brow_lift': [159, 386, 33, 263, 1, 10, 152],
}

# RBF influence radius as a fraction of face width (landmarks 234 <-> 454)
PROCEDURE_SIGMA_RATIO = {
    'rhinoplasty': 0.080,
    'blepharoplasty': 0.055,
    'rhytidectomy': 0.115,
    'genioplasty': 0.095,
    'forehead_surgery': 0.120,
    'brow_lift': 0.075,
}

PROCEDURE_PRIMARY_REGION = {
    'rhinoplasty': 'nose',
    'blepharoplasty': 'eyes',
    'rhytidectomy': 'jawline',
    'genioplasty': 'chin',
    'forehead_surgery': 'forehead',
    'brow_lift': 'eyebrows',
}

CENTRE_X_IDX = 1


def _compute_patient_scale(patient_features: np.ndarray = None) -> float:
    """Derive an anatomical elasticity modulation factor from patient metadata."""
    if patient_features is None or len(patient_features) < 10:
        return 1.0
    age_norm = float(patient_features[0])      # [0, 1]
    tx_history = float(patient_features[9])    # 0 or 1
    scale = 1.0 + 0.18 * (0.35 - age_norm) - 0.12 * tx_history
    return float(np.clip(scale, 0.78, 1.25))


def _compute_model_scale(
    trained_model,
    landmarks_array: np.ndarray,
    measurements: dict,
    patient_features: np.ndarray,
    procedure: str,
    h: int,
    w: int,
) -> float:
    """
    Use the trained MFAFNetModel to derive a data-driven regional shift multiplier
    restricted strictly to the procedure's target landmarks (avoiding global drift).
    """
    from mfaf_net.model_arch import predict_landmark_displacements
    dst_pred = predict_landmark_displacements(
        model=trained_model,
        landmarks_array=landmarks_array,
        measurements=measurements,
        patient_features=patient_features,
        procedure=procedure,
        img_h=h,
        img_w=w,
    )
    region_name = PROCEDURE_PRIMARY_REGION.get(procedure, 'nose')
    indices = [i for i in REGION_INDICES.get(region_name, []) if i < len(landmarks_array)]
    if not indices:
        return 1.0
    face_w = max(float(np.linalg.norm(landmarks_array[454] - landmarks_array[234])), 1.0)
    mean_shift = float(np.mean(np.linalg.norm(dst_pred[indices] - landmarks_array[indices], axis=1)))
    # Normalize learned shift relative to face width into a smooth [0.85, 1.35] multiplier
    ratio = mean_shift / (0.04 * face_w)
    return float(np.clip(0.85 + 0.35 * np.tanh(ratio), 0.85, 1.35))


def _apply_displacements(
    landmarks: np.ndarray,
    procedure: str,
    h: int,
    w: int,
    patient_features: np.ndarray = None,
    extra_scale: float = 1.0,
) -> np.ndarray:
    """Return a modified copy of landmarks with procedure-specific displacements applied."""
    dst = landmarks.copy()
    rules = PROCEDURE_RULES.get(procedure, [])
    centre_x = float(landmarks[CENTRE_X_IDX, 0])
    face_w = max(float(np.linalg.norm(landmarks[454] - landmarks[234])), 1.0)
    face_h = max(float(np.linalg.norm(landmarks[152] - landmarks[10])), 1.0)
    scale = _compute_patient_scale(patient_features) * float(extra_scale)

    for group_name, axis, factor, direction in rules:
        indices = LANDMARK_GROUPS.get(group_name, [])
        scaled_factor = factor * scale
        if axis == 'y':
            shift = scaled_factor * face_h * direction
            for idx in indices:
                if idx < len(dst):
                    dst[idx, 1] += shift
        elif axis == 'x':
            magnitude = scaled_factor * face_w
            if direction == 'inward':
                for idx in indices:
                    if idx < len(dst):
                        cx = dst[idx, 0]
                        shift = magnitude if cx > centre_x else -magnitude
                        dst[idx, 0] -= shift
            else:
                shift = magnitude * direction
                for idx in indices:
                    if idx < len(dst):
                        dst[idx, 0] += shift

    dst[:, 0] = np.clip(dst[:, 0], 0, w - 1)
    dst[:, 1] = np.clip(dst[:, 1], 0, h - 1)
    return dst


def _rbf_remap_warp(
    src_img: np.ndarray,
    src_pts: np.ndarray,
    dst_pts: np.ndarray,
    procedure: str,
) -> np.ndarray:
    """
    Smooth, artifact-free image warp using a Gaussian RBF inverse displacement
    field and `cv2.remap(..., cv2.INTER_CUBIC)`. Pixels outside the procedure's
    influence radius stay bit-for-bit identical to `src_img`.
    """
    h, w = src_img.shape[:2]
    deltas = dst_pts - src_pts
    mag = np.linalg.norm(deltas, axis=1)
    active_idx = np.where(mag > 0.25)[0]
    if len(active_idx) == 0:
        return src_img.copy()

    face_w = max(float(np.linalg.norm(src_pts[454] - src_pts[234])), float(min(h, w)) * 0.4)
    sigma = max(PROCEDURE_SIGMA_RATIO.get(procedure, 0.08) * face_w, 8.0)
    inv_2sig2 = 1.0 / (2.0 * sigma * sigma)

    # Coordinate grid
    grid_x, grid_y = np.meshgrid(
        np.arange(w, dtype=np.float32),
        np.arange(h, dtype=np.float32),
    )

    disp_x = np.zeros((h, w), dtype=np.float32)
    disp_y = np.zeros((h, w), dtype=np.float32)
    weight_sum = np.zeros((h, w), dtype=np.float32)

    for idx in active_idx:
        px, py = float(src_pts[idx, 0]), float(src_pts[idx, 1])
        dx, dy = float(deltas[idx, 0]), float(deltas[idx, 1])
        d2 = (grid_x - px) ** 2 + (grid_y - py) ** 2
        w_k = np.exp(-d2 * inv_2sig2)
        disp_x += w_k * dx
        disp_y += w_k * dy
        weight_sum += w_k

    # Normalize overlapping control weights smoothly without boosting far-field noise
    norm_factor = np.maximum(weight_sum, 1.0)
    disp_x /= norm_factor
    disp_y /= norm_factor

    # Anchor suppression so nearby stable landmarks (e.g. eye corners, lips) stay locked
    anchor_sigma = max(0.045 * face_w, 6.0)
    inv_2asig2 = 1.0 / (2.0 * anchor_sigma * anchor_sigma)
    anchor_mask = np.ones((h, w), dtype=np.float32)
    for a_idx in PROCEDURE_ANCHORS.get(procedure, []):
        if a_idx < len(src_pts) and a_idx not in active_idx:
            ax, ay = float(src_pts[a_idx, 0]), float(src_pts[a_idx, 1])
            ad2 = (grid_x - ax) ** 2 + (grid_y - ay) ** 2
            anchor_mask *= (1.0 - 0.92 * np.exp(-ad2 * inv_2asig2))

    disp_x *= anchor_mask
    disp_y *= anchor_mask

    map_x = np.clip(grid_x - disp_x, 0.0, float(w - 1)).astype(np.float32)
    map_y = np.clip(grid_y - disp_y, 0.0, float(h - 1)).astype(np.float32)

    return cv2.remap(
        src_img,
        map_x,
        map_y,
        interpolation=cv2.INTER_CUBIC,
        borderMode=cv2.BORDER_REFLECT_101,
    )


def _piecewise_affine_warp(
    src_img: np.ndarray,
    src_pts: np.ndarray,
    dst_pts: np.ndarray,
    procedure: str = 'rhinoplasty',
) -> np.ndarray:
    """Compatibility wrapper forwarding to the artifact-free RBF remap warp."""
    return _rbf_remap_warp(src_img, src_pts, dst_pts, procedure=procedure)


def simulate_procedure(
    original_path: str,
    landmarks_array: np.ndarray,
    regions: dict,
    procedure: str,
    output_dir: str,
    uid: str,
    patient_features: np.ndarray = None,
    attention_weights: dict = None,
    measurements: dict = None,
) -> dict:
    """
    Apply landmark-guided facial simulation to produce a crisp simulated image.

    Uses the trained PyTorch MFAFNetModel (`models/mfaf_net_best.pt`) when
    available to modulate the procedure-specific anatomical displacement,
    falling back seamlessly to patient-scaled geometric rules if no checkpoint
    is present.
    """
    image = cv2.imread(original_path)
    if image is None:
        raise ValueError(f"Cannot read image: {original_path}")

    h, w = image.shape[:2]
    src_pts = landmarks_array[:468].copy()

    simulation_mode = 'rule_based_geometric'
    model_scale = 1.0
    try:
        from mfaf_net.model_arch import load_trained_model
        trained_model, _ = load_trained_model()
        if trained_model is not None and patient_features is not None and measurements is not None:
            model_scale = _compute_model_scale(
                trained_model=trained_model,
                landmarks_array=src_pts,
                measurements=measurements,
                patient_features=patient_features,
                procedure=procedure,
                h=h,
                w=w,
            )
            simulation_mode = 'trained_mfaf_net'
    except Exception:
        model_scale = 1.0

    dst_pts = _apply_displacements(
        src_pts,
        procedure,
        h,
        w,
        patient_features=patient_features,
        extra_scale=model_scale,
    )

    result = _rbf_remap_warp(image, src_pts, dst_pts, procedure=procedure)

    sim_filename = f'simulated_{uid}.png'
    sim_path = os.path.join(output_dir, sim_filename)
    cv2.imwrite(sim_path, result)

    return {
        'simulated_image_path': sim_path,
        'simulation_mode': simulation_mode,
    }