File size: 17,643 Bytes
748425c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4ccc11
 
 
748425c
 
 
 
 
e4ccc11
748425c
79b337b
748425c
 
 
 
 
 
 
 
e4ccc11
 
d8cda25
 
 
 
748425c
 
 
 
e4ccc11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748425c
e4ccc11
 
 
79b337b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4ccc11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748425c
79b337b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748425c
d63f692
748425c
e4ccc11
748425c
e4ccc11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748425c
e4ccc11
d8cda25
e4ccc11
 
748425c
e4ccc11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748425c
 
 
79b337b
748425c
 
d63f692
748425c
 
 
 
 
 
 
 
e608228
748425c
e608228
 
 
 
 
748425c
e608228
 
 
748425c
 
 
 
 
 
d63f692
e4ccc11
748425c
e4ccc11
 
 
 
 
d63f692
e4ccc11
 
748425c
 
 
 
697792b
e608228
697792b
748425c
e4ccc11
 
 
 
e608228
 
748425c
e4ccc11
e608228
 
 
 
 
697792b
e608228
 
 
 
 
 
 
 
 
 
748425c
e4ccc11
e608228
e4ccc11
e608228
 
 
 
 
 
 
 
 
 
 
 
 
 
748425c
 
 
 
 
 
 
 
79b337b
748425c
 
d63f692
748425c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d63f692
748425c
e4ccc11
748425c
e4ccc11
748425c
e4ccc11
748425c
e4ccc11
d63f692
e608228
e4ccc11
697792b
748425c
 
697792b
 
 
 
748425c
e4ccc11
 
 
 
 
 
697792b
 
 
748425c
e4ccc11
748425c
 
 
 
 
 
 
 
 
 
 
 
79b337b
748425c
 
d63f692
748425c
d63f692
 
 
 
 
748425c
d63f692
 
 
 
 
748425c
 
 
 
 
 
 
 
 
 
 
 
79b337b
748425c
 
d63f692
748425c
9c43fab
748425c
8b98658
d63f692
79b337b
748425c
d63f692
 
 
e4ccc11
 
 
 
79b337b
748425c
e4ccc11
79b337b
748425c
e4ccc11
d63f692
748425c
 
 
e4ccc11
 
9c43fab
e4ccc11
 
 
748425c
e4ccc11
 
 
 
 
 
 
 
 
 
 
 
 
 
748425c
 
 
 
d8cda25
 
 
 
 
 
 
 
 
e4ccc11
 
d8cda25
 
 
 
 
e4ccc11
d8cda25
 
 
 
 
 
 
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
import os
from io import BytesIO

import cv2
import modal
import numpy as np
from PIL import Image

app = modal.App("ImageAlfred")

PYTHON_VERSION = "3.12"
CUDA_VERSION = "12.4.0"
FLAVOR = "devel"
OPERATING_SYS = "ubuntu22.04"
tag = f"{CUDA_VERSION}-{FLAVOR}-{OPERATING_SYS}"
volume = modal.Volume.from_name("image-alfred-volume", create_if_missing=True)
volume_path = "/vol"

MODEL_CACHE_DIR = f"{volume_path}/models/cache"
TORCH_HOME = f"{volume_path}/torch/home"
HF_HOME = f"{volume_path}/huggingface"

image = (
    modal.Image.from_registry(f"nvidia/cuda:{tag}", add_python=PYTHON_VERSION)
    .env(
        {
            "HF_HUB_ENABLE_HF_TRANSFER": "1",  # faster downloads
            "HF_HUB_CACHE": HF_HOME,
            "TORCH_HOME": TORCH_HOME,
        }
    )
    .apt_install(
        "git",
    )
    .pip_install(
        "huggingface-hub",
        "hf_transfer",
        "Pillow",
        "numpy",
        "transformers",
        "opencv-contrib-python-headless",
        "scipy",
        gpu="A10G",
    )
    .pip_install(
        "torch==2.4.1",
        "torchvision==0.19.1",
        index_url="https://download.pytorch.org/whl/cu124",
        gpu="A10G",
    )
    .pip_install("git+https://github.com/openai/CLIP.git", gpu="A10G")
    .pip_install("git+https://github.com/facebookresearch/sam2.git", gpu="A10G")
    .pip_install(
        "git+https://github.com/PramaLLC/BEN2.git#egg=ben2",
        gpu="A10G",
    )
)


@app.function(
    image=image,
    gpu="A10G",
    volumes={volume_path: volume},
    timeout=60 * 3,
)
def prompt_segment(
    image_pil: Image.Image,
    prompts: list[str],
) -> list[dict]:
    clip_results = clip.remote(image_pil, prompts)

    if not clip_results:
        print("No boxes returned from CLIP.")
        return None

    boxes = np.array(clip_results["boxes"])

    sam_result_masks, sam_result_scores = sam2.remote(image_pil=image_pil, boxes=boxes)

    print(f"sam_result_mask {sam_result_masks}")

    if not sam_result_masks.any():
        print("No masks or scores returned from SAM2.")
        return None

    if sam_result_masks.ndim == 3:
        # If the masks are in 3D, we need to convert them to 4D
        sam_result_masks = [sam_result_masks]

    results = {
        "labels": clip_results["labels"],
        "boxes": boxes,
        "clip_scores": clip_results["scores"],
        "sam_masking_scores": sam_result_scores,
        "masks": sam_result_masks,
    }
    return results


@app.function(
    image=image,
    gpu="A10G",
    volumes={volume_path: volume},
    timeout=60 * 3,
)
def privacy_prompt_segment(
    image_pil: Image.Image,
    prompts: list[str],
    threshold: float,
) -> list[dict]:
    owlv2_results = owlv2.remote(image_pil, prompts, threshold=threshold)

    if not owlv2_results:
        print("No boxes returned from OWLV2.")
        return None

    boxes = np.array(owlv2_results["boxes"])

    sam_result_masks, sam_result_scores = sam2.remote(image_pil=image_pil, boxes=boxes)

    print(f"sam_result_mask {sam_result_masks}")

    if not sam_result_masks.any():
        print("No masks or scores returned from SAM2.")
        return None

    if sam_result_masks.ndim == 3:
        # If the masks are in 3D, we need to convert them to 4D
        sam_result_masks = [sam_result_masks]

    results = {
        "labels": owlv2_results["labels"],
        "boxes": boxes,
        "owlv2_scores": owlv2_results["scores"],
        "sam_masking_scores": sam_result_scores,
        "masks": sam_result_masks,
    }
    return results


@app.function(
    image=image,
    gpu="A100",
    volumes={volume_path: volume},
    timeout=60 * 3,
)
def sam2(image_pil: Image.Image, boxes: list[np.ndarray]) -> list[dict]:
    import torch
    from sam2.sam2_image_predictor import SAM2ImagePredictor

    predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2-hiera-large")

    with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
        predictor.set_image(image_pil)
        masks, scores, _ = predictor.predict(
            point_coords=None,
            point_labels=None,
            box=boxes,
            multimask_output=False,
        )
    return masks, scores


@app.function(
    image=image,
    gpu="A100",
    volumes={volume_path: volume},
)
def owlv2(
    image_pil: Image.Image,
    labels: list[str],
    threshold: float,
) -> list[dict]:
    """
    Perform zero-shot segmentation on an image using specified labels.
    Args:
        image_pil (Image.Image): The input image as a PIL Image.
        labels (list[str]): List of labels for zero-shot segmentation.

    Returns:
        list[dict]: List of dictionaries containing label and bounding box information.
    """
    from transformers import pipeline

    checkpoint = "google/owlv2-large-patch14-ensemble"
    detector = pipeline(
        model=checkpoint,
        task="zero-shot-object-detection",
        device="cuda",
        use_fast=True,
    )
    # Load the image
    predictions = detector(
        image_pil,
        candidate_labels=labels,
    )
    labels = []
    scores = []
    boxes = []
    for prediction in predictions:
        if prediction["score"] < threshold:
            continue
        labels.append(prediction["label"])
        scores.append(prediction["score"])
        boxes.append(np.array(list(prediction["box"].values())))
    if labels == []:
        print("No predictions found with score above threshold.")
        return None
    predictions = {"labels": labels, "scores": scores, "boxes": boxes}
    return predictions


@app.function(
    image=image,
    gpu="A100",
    volumes={volume_path: volume},
    timeout=60 * 3,
)
def clip(
    image_pil: Image.Image,
    prompts: list[str],
) -> list[dict]:
    """
    returns:
        dict with keys each are lists:
            - labels: str, the prompt used for the prediction
            - scores: float, confidence score of the prediction
            - boxes: np.array representing bounding box coordinates
    """

    from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
    import torch

    processor = CLIPSegProcessor.from_pretrained(
        "CIDAS/clipseg-rd64-refined",
        use_fast=True,
    )
    model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined")

    # Get original image dimensions
    orig_width, orig_height = image_pil.size

    inputs = processor(
        text=prompts,
        images=[image_pil] * len(prompts),
        padding="max_length",
        return_tensors="pt",
    )
    # predict
    with torch.no_grad():
        outputs = model(**inputs)
    preds = outputs.logits.unsqueeze(1)

    # Get the dimensions of the prediction output
    pred_height, pred_width = preds.shape[-2:]

    # Calculate scaling factors
    width_scale = orig_width / pred_width
    height_scale = orig_height / pred_height

    labels = []
    scores = []
    boxes = []

    # Process each prediction to find bounding boxes in high probability regions
    for i, prompt in enumerate(prompts):
        # Apply sigmoid to get probability map
        pred_tensor = torch.sigmoid(preds[i][0])
        # Convert tensor to numpy array
        pred_np = pred_tensor.cpu().numpy()

        # Convert to uint8 for OpenCV processing
        heatmap = (pred_np * 255).astype(np.uint8)

        # Apply threshold to find high probability regions
        _, binary = cv2.threshold(heatmap, 127, 255, cv2.THRESH_BINARY)

        # Find contours in thresholded image
        contours, _ = cv2.findContours(
            binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
        )

        # Process each contour to get bounding boxes
        for contour in contours:
            # Skip very small contours that might be noise
            if cv2.contourArea(contour) < 100:  # Minimum area threshold
                continue

            # Get bounding box coordinates in prediction space
            x, y, w, h = cv2.boundingRect(contour)

            # Scale coordinates to original image dimensions
            x_orig = int(x * width_scale)
            y_orig = int(y * height_scale)
            w_orig = int(w * width_scale)
            h_orig = int(h * height_scale)

            # Calculate confidence score based on average probability in the region
            mask = np.zeros_like(pred_np)
            cv2.drawContours(mask, [contour], 0, 1, -1)
            confidence = float(np.mean(pred_np[mask == 1]))

            labels.append(prompt)
            scores.append(confidence)
            boxes.append(
                np.array(
                    [
                        x_orig,
                        y_orig,
                        x_orig + w_orig,
                        y_orig + h_orig,
                    ]
                )
            )

    if labels == []:
        return None

    results = {
        "labels": labels,
        "scores": scores,
        "boxes": boxes,
    }
    return results


@app.function(
    gpu="A10G",
    image=image,
    volumes={volume_path: volume},
    timeout=60 * 3,
)
def change_image_objects_hsv(
    image_pil: Image.Image,
    targets_config: list[list[str | int | float]],
) -> Image.Image:
    if not isinstance(targets_config, list) or not all(
        (
            isinstance(target, list)
            and len(target) == 4
            and isinstance(target[0], str)
            and isinstance(target[1], (int))
            and isinstance(target[2], (int))
            and isinstance(target[3], (int))
            and target[1] >= 0
            and target[1] <= 255
            and target[2] >= 0
            and target[2] <= 255
            and target[3] >= 0
            and target[3] <= 255
        )
        for target in targets_config
    ):
        raise ValueError(
            "targets_config must be a list of lists, each containing [target_name, hue, saturation_scale]."  # noqa: E501
        )
    print("Change image objects hsv targets config:", targets_config)
    prompts = [target[0].strip() for target in targets_config]

    prompt_segment_results = prompt_segment.remote(
        image_pil=image_pil,
        prompts=prompts,
    )
    if not prompt_segment_results:
        return image_pil

    output_labels = prompt_segment_results["labels"]

    img_array = np.array(image_pil)
    img_hsv = cv2.cvtColor(img_array, cv2.COLOR_RGB2HSV).astype(np.float32)

    for idx, label in enumerate(output_labels):
        if not label or label == "":
            print("Skipping empty label.")
            continue
        if label not in prompts:
            print(f"Label '{label}' not found in prompts. Skipping.")
            continue
        input_label_idx = prompts.index(label)
        target_rgb = targets_config[input_label_idx][1:]
        target_hsv = cv2.cvtColor(np.uint8([[target_rgb]]), cv2.COLOR_RGB2HSV)[0][0]

        mask = prompt_segment_results["masks"][idx][0].astype(bool)
        h, s, v = cv2.split(img_hsv)
        # Convert all channels to float32 for consistent processing
        h = h.astype(np.float32)
        s = s.astype(np.float32)
        v = v.astype(np.float32)

        # Compute original S and V means inside the mask
        mean_s = np.mean(s[mask])
        mean_v = np.mean(v[mask])

        # Target S and V
        target_hue, target_s, target_v = target_hsv

        # Compute scaling factors (avoid div by zero)
        scale_s = target_s / mean_s if mean_s > 0 else 1.0
        scale_v = target_v / mean_v if mean_v > 0 else 1.0

        scale_s = np.clip(scale_s, 0.8, 1.2)
        scale_v = np.clip(scale_v, 0.8, 1.2)

        # Apply changes only in mask
        h[mask] = target_hue
        s = s.astype(np.float32)
        v = v.astype(np.float32)
        s[mask] = np.clip(s[mask] * scale_s, 0, 255)
        v[mask] = np.clip(v[mask] * scale_v, 0, 255)

        # Merge and convert back
        img_hsv = cv2.merge(
            [
                h.astype(np.uint8),
                s.astype(np.uint8),
                v.astype(np.uint8),
            ]
        )

    output_img = cv2.cvtColor(img_hsv.astype(np.uint8), cv2.COLOR_HSV2RGB)
    output_img_pil = Image.fromarray(output_img)
    return output_img_pil


@app.function(
    gpu="A10G",
    image=image,
    volumes={volume_path: volume},
    timeout=60 * 3,
)
def change_image_objects_lab(
    image_pil: Image.Image,
    targets_config: list[list[str | int | float]],
) -> Image.Image:
    """Changes the color of specified objects in an image.
    This function uses LangSAM to segment objects in the image based on provided prompts,
    and then modifies the color of those objects in the LAB color space.
    """  # noqa: E501
    if not isinstance(targets_config, list) or not all(
        (
            isinstance(target, list)
            and len(target) == 3
            and isinstance(target[0], str)
            and isinstance(target[1], int)
            and isinstance(target[2], int)
            and 0 <= target[1] <= 255
            and 0 <= target[2] <= 255
        )
        for target in targets_config
    ):
        raise ValueError(
            "targets_config must be a list of lists, each containing [target_name, new_a, new_b]."  # noqa: E501
        )

    print("change image objects lab targets config:", targets_config)

    prompts = [target[0].strip() for target in targets_config]

    prompt_segment_results = prompt_segment.remote(
        image_pil=image_pil,
        prompts=prompts,
    )
    if not prompt_segment_results:
        return image_pil

    output_labels = prompt_segment_results["labels"]

    img_array = np.array(image_pil)
    img_lab = cv2.cvtColor(img_array, cv2.COLOR_RGB2Lab).astype(np.float32)

    for idx, label in enumerate(output_labels):
        if not label or label == "":
            print("Skipping empty label.")
            continue

        if label not in prompts:
            print(f"Label '{label}' not found in prompts. Skipping.")
            continue

        input_label_idx = prompts.index(label)

        new_a = targets_config[input_label_idx][1]
        new_b = targets_config[input_label_idx][2]

        mask = prompt_segment_results["masks"][idx][0]
        mask_bool = mask.astype(bool)

        img_lab[mask_bool, 1] = new_a
        img_lab[mask_bool, 2] = new_b

    output_img = cv2.cvtColor(img_lab.astype(np.uint8), cv2.COLOR_Lab2RGB)
    output_img_pil = Image.fromarray(output_img)

    return output_img_pil


@app.function(
    gpu="A10G",
    image=image,
    volumes={volume_path: volume},
    timeout=60 * 3,
)
def apply_mosaic_with_bool_mask(
    image: np.ndarray,
    mask: np.ndarray,
    privacy_strength: int,
) -> np.ndarray:
    h, w = image.shape[:2]
    image_size_factor = min(h, w) / 1000
    block_size = int(max(1, (privacy_strength * image_size_factor)))

    # Ensure block_size is at least 1 and doesn't exceed half of image dimensions
    block_size = max(1, min(block_size, min(h, w) // 2))

    small = cv2.resize(
        image, (w // block_size, h // block_size), interpolation=cv2.INTER_LINEAR
    )
    mosaic = cv2.resize(small, (w, h), interpolation=cv2.INTER_NEAREST)

    result = image.copy()
    result[mask] = mosaic[mask]
    return result


@app.function(
    gpu="A10G",
    image=image,
    volumes={volume_path: volume},
    timeout=60 * 3,
)
def preserve_privacy(
    image_pil: Image.Image,
    prompts: list[str],
    privacy_strength: int = 15,
    threshold: float = 0.2,
) -> Image.Image:
    """
    Preserves privacy in an image by applying a mosaic effect to specified objects.
    """
    print(f"Preserving privacy for prompt: {prompts} with strength {privacy_strength}")
    if isinstance(prompts, str):
        prompts = [prompt.strip() for prompt in prompts.split(".")]
        print(f"Parsed prompts: {prompts}")
    prompt_segment_results = privacy_prompt_segment.remote(
        image_pil=image_pil,
        prompts=prompts,
        threshold=threshold,
    )
    if not prompt_segment_results:
        return image_pil

    img_array = np.array(image_pil)

    for i, mask in enumerate(prompt_segment_results["masks"]):
        mask_bool = mask[0].astype(bool)

        # Create kernel for morphological operations
        kernel_size = 100
        kernel = np.ones((kernel_size, kernel_size), np.uint8)

        # Convert bool mask to uint8 for OpenCV operations
        mask_uint8 = mask_bool.astype(np.uint8) * 255

        # Apply dilation to slightly expand the mask area
        mask_uint8 = cv2.dilate(mask_uint8, kernel, iterations=2)
        # Optional: Apply erosion again to refine the mask
        mask_uint8 = cv2.erode(mask_uint8, kernel, iterations=2)

        # Convert back to boolean mask
        mask_bool = mask_uint8 > 127

        img_array = apply_mosaic_with_bool_mask.remote(
            img_array, mask_bool, privacy_strength
        )

    output_image_pil = Image.fromarray(img_array)

    return output_image_pil


@app.function(
    gpu="A10G",
    image=image,
    volumes={volume_path: volume},
    timeout=60 * 2,
)
def remove_background(image_pil: Image.Image) -> Image.Image:
    import torch  # type: ignore
    from ben2 import BEN_Base  # type: ignore

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    print(f"Using device: {device}")
    print("type of image_pil:", type(image_pil))
    model = BEN_Base.from_pretrained("PramaLLC/BEN2")
    model.to(device).eval()  # todo check if this should be outside the function

    output_image = model.inference(
        image_pil,
        refine_foreground=True,
    )
    print(f"output type: {type(output_image)}")
    return output_image