-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
4414 lines (3995 loc) · 201 KB
/
Copy pathmain.py
File metadata and controls
4414 lines (3995 loc) · 201 KB
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
useknockout — state-of-the-art background removal API.
Powered by BiRefNet (MIT license, commercial-safe), served on Modal GPUs.
Deploy:
modal deploy main.py
Test (multipart file upload):
curl -X POST "$URL/remove" \
-H "Authorization: Bearer $API_TOKEN" \
-F "file=@cat.jpg" \
-o cat-nobg.png
Test (remote URL):
curl -X POST "$URL/remove-url" \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/cat.jpg"}' \
-o cat-nobg.png
"""
import base64
import hashlib
import io
import json
import math
import os
import secrets
import shutil
import subprocess
import tempfile
import time
import uuid
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from typing import List, Optional, Tuple
import modal
def _now_iso() -> str:
"""ISO-8601 UTC timestamp for Postgres timestamptz columns."""
return datetime.now(timezone.utc).isoformat()
APP_NAME = "api"
MODEL_REPO = "ZhengPeng7/BiRefNet"
MODEL_INPUT_SIZE = (1024, 1024)
MAX_IMAGE_BYTES = 25 * 1024 * 1024 # 25 MB
# --- Tier-based endpoint gating -------------------------------------------
# Billable endpoints a signed-up FREE-tier user may call. Anything billable
# NOT in this set requires a paid tier (payg/volume/enterprise); free callers
# get a 402 upsell. /estimate is ungated (no auth) so it is intentionally
# absent. Paid-only set = edits (replace-bg, smart-crop, outline, sticker) +
# AI enhancement (upscale, face-restore, colorize, inpaint) + e-commerce
# presets (studio-shot, headshot) + creative (shadow, silhouette) + batch
# (remove-batch, remove-batch-url).
FREE_TIER_ENDPOINTS = frozenset({
"/remove",
"/remove-url",
"/mask",
"/compare",
"/preview",
})
# The anonymous shared demo key is a throttled taste of the product: it may
# only hit these endpoints, output is downscaled, and there is a global daily
# cap. Everything else 402s with a signup nudge.
DEMO_ENDPOINTS = frozenset({
"/remove",
"/replace-bg",
"/mask",
"/sticker",
"/compare",
})
# Demo output cap. Was 512 after a token-abuse incident, but the public
# playground runs on the demo key — so every visitor's first impression was a
# 512px thumbnail upscaled in the browser, next to competitors showing full-res.
# 1536 still bounds abuse (and the global daily cap is the real guard) while
# looking like the product actually is. Override with DEMO_MAX_DIM env.
DEMO_MAX_DIM = int(os.environ.get("DEMO_MAX_DIM", "") or 1536)
# Signed-up free tier: images/month, no card. Raised 10 -> 30 on 2026-08-13 to
# match withoutbg's "50 free" signup grant — except theirs is a ONE-TIME grant
# that expires in 30 days and ours recurs every month and never expires, so at
# 50 we are strictly more generous than the competitor we were being compared
# against (their 50 is one-time and expires in 30 days; ours recurs).
FREE_MONTHLY_QUOTA = int(os.environ.get("FREE_MONTHLY_QUOTA", "") or 30)
DEMO_DAILY_CAP_DEFAULT = 500 # global anonymous calls/day; DEMO_DAILY_CAP overrides
DEMO_IP_DAILY_CAP_DEFAULT = 10 # per-IP anonymous calls/day; DEMO_IP_DAILY_CAP overrides
DEMO_IP_SALT = os.environ.get("DEMO_IP_SALT", "knockout-demo-ip-v1") # raw IPs never stored
# CascadePSP's fast=False path refines in ~900px tiles at NATIVE resolution and
# fuses them. A tile landing entirely inside a large flat region (the inside of
# an open box, a plain backdrop panel) carries no boundary evidence, so some
# tiles flip to background and the fused alpha comes back with grid-shaped
# holes. Kravento hit this on a 3072px box on 2026-08-25: 8 interior holes,
# 13.6% of the subject destroyed. The SAME image at 1280px is spotless — the
# bug is purely a function of pixel dimensions. Cap what the refiner sees, then
# upscale the alpha back. 1600 still localises edges far better than the 1024
# default-engine mask, which is where the halo win came from in the first place.
# 900 == the refiner's own tile size. Anything larger tiles and can seam; 1600
# was tried first and still left 7.9% of the box interior semi-transparent.
PRODUCT_REFINE_MAX_DIM = int(os.environ.get("PRODUCT_REFINE_MAX_DIM", "") or 900)
# Refinement may legitimately shrink a boundary; it must never punch a hole
# through the middle of the subject. Measured away from the edge, so ordinary
# boundary tightening cannot trip it.
PRODUCT_REFINE_MAX_INTERIOR_LOSS = 0.01
# engine=auto only: product-v1 must not be WORSE than the default mask it is
# replacing. Auto already computes the default first, so it can compare and
# keep the default when escalation backfires. Shape routing cannot see damage;
# this can. 1% of the subject interior going transparent is the limit.
AUTO_MAX_PRODUCT_REGRESSION = 0.01
# ---- /replace-bg-ai (AI-generated backgrounds) ----------------------------
# EXPERIMENT, allowlist-gated. The generative model NEVER sees the product: we
# cut the subject with BiRefNet, generate only the backdrop from a text prompt,
# and composite. So product pixels are provably untouched and output stays at
# source resolution — neither is true of generative image EDITING.
#
# Public model name -> Azure deployment name. Azure deployment names are chosen
# at deploy time and need not match the catalog id, so every entry is
# overridable by env (AI_BG_DEPLOYMENT_<UPPER_SNAKE>) — a wrong guess is a
# secret edit, not a redeploy.
# (deployment_name, route). Azure serves three different image APIs and picking
# the wrong one 404s:
# aoai - Azure OpenAI native models. Deployment in the PATH.
# {res}.openai.azure.com/openai/deployments/{dep}/images/generations
# foundry - "sold directly by Azure" partner models (BFL FLUX). Model in BODY.
# {res}.services.ai.azure.com/openai/v1/images/generations
# mai - Microsoft's own MAI image family, its own namespace. Model in BODY.
# {res}.services.ai.azure.com/mai/v1/images/generations
AI_BG_AZURE_MODELS = {
"flux2-pro": ("FLUX.2-pro", "bfl"),
"flux2-flex": ("FLUX.2-flex", "bfl"),
"flux1-kontext-pro": ("FLUX.1-Kontext-pro", "foundry"),
"gpt-image-2": ("gpt-image-2", "aoai"),
"mai-image-2e": ("MAI-Image-2e", "mai"),
"mai-image-2.5": ("MAI-Image-2.5", "mai"),
"mai-image-2.5-pro": ("MAI-Image-2.5-Pro", "mai"),
"mai-image-2.5-flash": ("MAI-Image-2.5-Flash", "mai"),
}
AI_BG_GOOGLE_MODELS = {
"nano-banana": "gemini-2.5-flash-image",
}
# ASU AIML gateway — OWNER-ONLY, for free model evaluation. The token is Troy's
# university work credential, so customer traffic must never touch it: these
# models 403 for everyone except the internal is_legacy token, allowlist or not.
# (The gateway strips image INPUTS, which is why this feature generates only the
# backdrop from text — image-to-image evaluation there is impossible.)
AI_BG_ASU_MODELS = {
"asu-gpt-image-2": ("openai", "gpt_image2"),
"asu-nano-banana": ("gcp-deepmind", "nano_banana_pro"),
"asu-gemini-flash": ("gcp-deepmind", "geminiflash2_5_image"),
}
AI_BG_ASU_URL = "https://api-main.aiml.asu.edu/query"
AI_BG_DEFAULT_MODEL = os.environ.get("AI_BG_DEFAULT_MODEL", "flux2-pro").strip() or "flux2-pro"
AI_BG_API_VERSION = os.environ.get("AI_BG_API_VERSION", "2025-04-01-preview")
# Empty allowlist = feature OFF for everyone (the default). Comma-separated
# Supabase user_ids enable it. The owner's internal token always passes.
# Read at REQUEST time, not import time: Modal injects secret env vars into the
# container, and module-level globals can evaluate before that lands. Reading
# lazily also means adding a user is a secret edit with no redeploy.
def _ai_bg_allowlist() -> frozenset:
return frozenset(
u.strip() for u in os.environ.get("AI_BG_ALLOWLIST", "").split(",") if u.strip()
)
AI_BG_DAILY_CAP_DEFAULT = 50 # global calls/day; each one spends real provider money
AI_BG_PROMPT_MAX = 500
# ---- /video/remove (async jobs) ----
VIDEO_MAX_SECONDS = 15 # hard cap per clip: 15s ProRes ~305MB stays under the 500MB storage limit; 30s would exceed it
VIDEO_FPS_CAP = 30 # frames processed per second of video, max
VIDEO_MAX_BYTES = 200 * 1024 * 1024
VIDEO_MAX_DIM = 1920 # frames downscaled to this longest side before inference
VIDEO_METER_EVENT = os.environ.get("STRIPE_VIDEO_METER_EVENT", "video.seconds").strip() or "video.seconds"
# Video bills on its OWN Stripe meter (not the image meter): 1 unit = 1 output
# second, priced at $0.10/second. 15s clip = 15 units = $1.50. Set the price to
# $0.10 ($10/unit? no — unit_amount 10 cents) on the video.seconds meter.
VIDEO_BUCKET = "video-jobs"
VIDEO_FORMATS = frozenset({"prores4444", "webm", "mp4"})
VIDEO_INPUT_EXTS = frozenset({"mp4", "mov", "avi", "webm", "mkv"})
# Swin2SR — SwinV2 Transformer super-res (successor to SwinIR). Apache-2.0.
# Better than Real-ESRGAN on real photos: preserves skin/hair texture instead
# of the painted/plastic look Real-ESRGAN produces on faces.
SWIN2SR_X4_REPO = "caidas/swin2SR-realworld-sr-x4-64-bsrgan-psnr"
SWIN2SR_X2_REPO = "caidas/swin2SR-classical-sr-x2-64"
UPSCALE_WEIGHTS_DIR = "/root/weights"
REALESRGAN_URL = (
"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth"
)
GFPGAN_URL = (
"https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth"
)
FACEXLIB_DETECTION_URL = (
"https://github.com/xinntao/facexlib/releases/download/v0.1.0/detection_Resnet50_Final.pth"
)
FACEXLIB_PARSING_URL = (
"https://github.com/xinntao/facexlib/releases/download/v0.2.2/parsing_parsenet.pth"
)
def _download_model() -> None:
"""Bake all model weights into the image at build time so cold starts are fast."""
import os
import urllib.request
from transformers import (
AutoImageProcessor,
AutoModelForImageSegmentation,
Swin2SRForImageSuperResolution,
)
AutoModelForImageSegmentation.from_pretrained(MODEL_REPO, trust_remote_code=True)
# Bake Swin2SR weights into image so cold starts skip the HF download.
for repo in (SWIN2SR_X4_REPO, SWIN2SR_X2_REPO):
Swin2SRForImageSuperResolution.from_pretrained(repo)
AutoImageProcessor.from_pretrained(repo)
os.makedirs(UPSCALE_WEIGHTS_DIR, exist_ok=True)
# Real-ESRGAN + GFPGAN main weights — explicit paths used at load time.
direct_downloads = {
"RealESRGAN_x4plus.pth": REALESRGAN_URL,
"GFPGANv1.4.pth": GFPGAN_URL,
}
for name, url in direct_downloads.items():
dest = os.path.join(UPSCALE_WEIGHTS_DIR, name)
if not os.path.exists(dest):
print(f"Downloading {name}...")
urllib.request.urlretrieve(url, dest)
# facexlib auto-downloads detection + parsing weights into gfpgan/weights/.
# Pre-bake them so the first /face-restore request doesn't pay the network cost.
import gfpgan as _gfpgan_mod
gfpgan_weights_dir = os.path.join(os.path.dirname(_gfpgan_mod.__file__), "weights")
os.makedirs(gfpgan_weights_dir, exist_ok=True)
facexlib_downloads = {
"detection_Resnet50_Final.pth": FACEXLIB_DETECTION_URL,
"parsing_parsenet.pth": FACEXLIB_PARSING_URL,
}
for name, url in facexlib_downloads.items():
dest = os.path.join(gfpgan_weights_dir, name)
if not os.path.exists(dest):
print(f"Downloading {name} -> gfpgan/weights/...")
urllib.request.urlretrieve(url, dest)
# DDColor (Apache-2.0) — colorization. Pre-fetch the modelscope snapshot
# so cold starts skip the ~870 MB download. Network errors here are
# non-fatal: pipeline() will lazy-fetch at request time as a fallback.
try:
from modelscope import snapshot_download
print("Pre-fetching DDColor weights (~870 MB)...")
snapshot_download("damo/cv_ddcolor_image-colorization")
except Exception as e:
print(f"DDColor pre-fetch skipped: {e!r}")
# LaMa weights (~200 MB) — instantiating SimpleLama triggers the one-time
# weight download into the user cache dir. Cold starts then skip the fetch.
try:
from simple_lama_inpainting import SimpleLama
print("Pre-fetching LaMa weights (~200 MB)...")
SimpleLama()
except Exception as e:
print(f"LaMa pre-fetch skipped: {e!r}")
image = (
modal.Image.debian_slim(python_version="3.11")
.apt_install("libgl1", "libglib2.0-0", "ffmpeg") # ffmpeg: /video/remove demux/remux (ProRes 4444, VP9 alpha)
.pip_install(
"torch==2.4.0",
"torchvision==0.19.0",
"transformers==4.44.2",
"pillow==10.4.0",
"timm==1.0.9",
"kornia==0.7.3",
"einops==0.8.0",
"huggingface_hub==0.24.6",
"fastapi[standard]==0.115.0",
"python-multipart==0.0.9",
"requests==2.32.3",
"pydantic==2.9.2",
"numpy==1.26.4",
"pymatting==1.1.12",
"opencv-python-headless==4.10.0.84",
)
.pip_install(
"basicsr==1.4.2",
"facexlib==0.3.0",
"realesrgan==0.3.0",
"gfpgan==1.3.8",
)
# basicsr install bumps numpy to 2.x — pin back to 1.26.4 to keep pymatting + PIL stable.
.pip_install("numpy==1.26.4")
# DDColor (Apache-2.0) for /colorize via ModelScope. ModelScope brings
# its own pipeline registry — keeps DDColor's basicsr fork isolated from
# the basicsr we already use for Real-ESRGAN/GFPGAN.
# ModelScope's pipelines.base unconditionally imports a dependency chain
# that requires datasets, oss2, addict, simplejson, sortedcontainers —
# none of which are auto-installed by `pip install modelscope`. Front-load
# all of them to avoid iterative rebuilds chasing missing modules.
.pip_install(
"modelscope==1.18.1",
"datasets==2.21.0",
"oss2==2.18.5",
"addict==2.4.0",
"simplejson==3.19.2",
"sortedcontainers==2.4.0",
)
# LaMa (Apache-2.0) for /inpaint via simple-lama-inpainting wrapper.
# Resolution-robust Large Mask Inpainting — deterministic, no prompts.
# Weight download (~200 MB) baked into the image below via SimpleLama() warmup.
.pip_install("simple-lama-inpainting==0.1.2")
# psd-tools (MIT) for layered PSD export (format=psd). Needs >=1.11 for
# create_pixel_layer (real transparent layers; frompil flattens to an
# opaque Background). Re-pin numpy AND pillow in the same layer so psd-tools
# can't silently bump them (it pulls pillow 12.x + numpy 2.x otherwise) and
# break pymatting/PIL.
.pip_install("psd-tools>=1.11,<2", "numpy==1.26.4", "pillow==10.4.0")
# PyJWT + cryptography for the web-app portal credential (Path 1.5 in
# _check_auth): verifies Supabase session JWTs (ES256) against the
# project's JWKS endpoint. No shared JWT secret is stored anywhere.
.pip_install("pyjwt==2.9.0", "cryptography==43.0.1")
# basicsr 1.4.2 + facexlib import `torchvision.transforms.functional_tensor`,
# removed in torchvision 0.17+. Patch every file in site-packages that
# references it. Uses grep to find files (no Python import — would crash).
# Then nuke __pycache__ so stale .pyc bytecode doesn't shadow the new .py.
.run_commands(
"grep -rl 'torchvision.transforms.functional_tensor' "
"/usr/local/lib/python3.11/site-packages/ "
"| xargs --no-run-if-empty "
"sed -i 's/torchvision.transforms.functional_tensor/torchvision.transforms.functional/g'",
"find /usr/local/lib/python3.11/site-packages/ -type d -name __pycache__ "
"-exec rm -rf {} + 2>/dev/null; true"
)
.run_function(_download_model)
)
# Module-level imports available inside the container only.
# This lets FastAPI resolve UploadFile/Header/etc. via get_type_hints().
with image.imports():
import numpy as np
import requests
import torch
from basicsr.archs.rrdbnet_arch import RRDBNet
from fastapi import FastAPI, File, Form, Header, HTTPException, Request, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import Response
from gfpgan import GFPGANer
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont, ImageOps, UnidentifiedImageError
from pydantic import BaseModel, HttpUrl
from pymatting import estimate_foreground_cf, estimate_foreground_ml
from realesrgan import RealESRGANer
from torchvision import transforms
from transformers import (
AutoImageProcessor,
AutoModelForImageSegmentation,
Swin2SRForImageSuperResolution,
)
# ModelScope pipeline for DDColor (/colorize endpoint). Imported lazily
# at container-init time — heavy import, so don't pull at module scope.
from modelscope.outputs import OutputKeys
from modelscope.pipelines import pipeline as ms_pipeline
# LaMa (Apache-2.0) — large-mask inpainting for /inpaint.
from simple_lama_inpainting import SimpleLama
app = modal.App(APP_NAME, image=image)
# ---- product-v1 engine (S3OD + CascadePSP), isolated container ------------
#
# Alternate cutout engine for flat product photography (lightbox flat-lays,
# e-commerce sheets). S3OD (okupyn/s3od, MIT) produces the coarse mask;
# CascadePSP (segmentation-refinement, MIT) refines it at native resolution.
# Chosen over BiRefNet for this domain in the 2026-08-17 bakeoff — see
# docs/superpowers/specs/2026-08-17-white-halo-problem.md and
# eval/cases/kravento-film/.
#
# Lives in its OWN image + container: its torch 2.6 stack must not touch the
# main image's torch 2.4 / numpy 1.26 pins (basicsr/pymatting/modelscope all
# depend on those), and isolation keeps cold starts, VRAM and rollbacks of the
# experiment separate from every existing endpoint.
product_image = (
modal.Image.debian_slim(python_version="3.11")
.apt_install("git", "libgl1", "libglib2.0-0")
.pip_install(
"torch==2.6.0",
"torchvision==0.21.0",
"transformers>=4.48",
"timm",
"einops",
"safetensors",
"huggingface_hub",
"pillow",
"numpy",
"opencv-python-headless",
)
.pip_install("segmentation-refinement")
.pip_install("git+https://github.com/KupynOrest/s3od.git")
)
@app.cls(gpu="L4", scaledown_window=300, timeout=600, image=product_image)
class ProductEngine:
@modal.enter()
def load(self):
from s3od import BackgroundRemoval
import segmentation_refinement as refine
self.det = BackgroundRemoval(model_id="okupyn/s3od")
self.refiner = refine.Refiner(device="cuda")
@modal.method()
def cutout(self, image_png: bytes) -> bytes:
"""RGB image bytes in, native-resolution grayscale alpha PNG out."""
import io
import cv2
import numpy as np
from PIL import Image as PILImage
im = PILImage.open(io.BytesIO(image_png)).convert("RGB")
res = self.det.remove_background(im)
arr = np.squeeze(np.asarray(res.predicted_mask))
if arr.max() <= 1.5:
arr = (arr * 255).clip(0, 255).astype("uint8")
else:
arr = arr.astype("uint8")
alpha = PILImage.fromarray(arr)
if alpha.size != im.size:
alpha = alpha.resize(im.size, PILImage.LANCZOS)
# ---- guard 1: never let the refiner tile ------------------------
# See PRODUCT_REFINE_MAX_DIM. Refine small, then scale the alpha back.
longest = max(im.size)
if longest > PRODUCT_REFINE_MAX_DIM:
s = PRODUCT_REFINE_MAX_DIM / float(longest)
small = (max(1, int(round(im.width * s))), max(1, int(round(im.height * s))))
im_r = im.resize(small, PILImage.LANCZOS)
alpha_r = alpha.resize(small, PILImage.LANCZOS)
print(f"product engine: refining at {small} (native {im.size})")
else:
im_r, alpha_r = im, alpha
bgr = cv2.cvtColor(np.asarray(im_r), cv2.COLOR_RGB2BGR)
refined = self.refiner.refine(bgr, np.asarray(alpha_r), fast=False, L=900)
refined_img = PILImage.fromarray(refined)
if refined_img.size != im.size:
refined_img = refined_img.resize(im.size, PILImage.LANCZOS)
# ---- guard 2: refinement must not eat the subject ---------------
# Independent of guard 1 on purpose: if some future image tiles badly
# anyway, we ship the unrefined S3OD mask rather than a holed cutout.
try:
from scipy import ndimage
# Compare CONTINUOUS alpha, not a >128 threshold. The tile seams
# come back at ~50% alpha, which a binary test scores as "kept"
# while the pixel is visibly half gone. That mistake is why a 7.9%
# semi-transparent wash was first reported as fixed.
base = np.asarray(alpha).astype(np.float32) / 255.0
ref = np.asarray(refined_img).astype(np.float32) / 255.0
solid = ndimage.binary_fill_holes(base > 0.5)
# ignore a boundary band; only interior losses count
band = max(4, int(0.004 * max(im.size)))
interior = ndimage.binary_erosion(solid, iterations=band)
if interior.any():
drop = (base - ref)[interior]
lost = float((drop > 0.2).sum()) / float(interior.sum())
if lost > PRODUCT_REFINE_MAX_INTERIOR_LOSS:
print(f"product engine: refinement made {lost:.1%} of the "
f"subject interior transparent - DISCARDED, unrefined mask")
refined_img = alpha
except Exception as e: # a broken guard must never fail the request
print(f"product engine: interior guard skipped ({e!r})")
buf = io.BytesIO()
refined_img.save(buf, format="PNG")
return buf.getvalue()
@app.cls(
gpu="L4",
scaledown_window=300, # keep warm 5 min between requests
timeout=1800, # video jobs run inside the class (30s @ 30fps = 900 frames)
max_containers=10,
secrets=[
modal.Secret.from_name("knockout-secrets"),
# AI-background provider creds. Separate secret so the experiment can be
# deleted in one command without touching production credentials.
modal.Secret.from_name("knockout-ai-bg", required_keys=[]),
],
)
class Knockout:
@modal.enter()
def load(self) -> None:
torch.set_float32_matmul_precision("high")
self.model = AutoModelForImageSegmentation.from_pretrained(
MODEL_REPO, trust_remote_code=True
)
self.model.to("cuda").eval().half()
self.transform = transforms.Compose([
transforms.Resize(MODEL_INPUT_SIZE),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
self.to_pil = transforms.ToPILImage()
# Real-ESRGAN x4 upscaler. Tile inference keeps VRAM bounded for big inputs.
rrdb = RRDBNet(
num_in_ch=3, num_out_ch=3, num_feat=64,
num_block=23, num_grow_ch=32, scale=4,
)
self.upscaler = RealESRGANer(
scale=4,
model_path=f"{UPSCALE_WEIGHTS_DIR}/RealESRGAN_x4plus.pth",
model=rrdb,
tile=512,
tile_pad=10,
pre_pad=0,
half=True,
gpu_id=0,
)
# GFPGAN portrait restorer — two variants:
# face_restorer → original bg preserved (no Real-ESRGAN bg pass)
# avoids skin-tone bleed into bg around face edges
# face_restorer_full → bg also upscaled via Real-ESRGAN (legacy v0.5.0 behavior)
self.face_restorer = GFPGANer(
model_path=f"{UPSCALE_WEIGHTS_DIR}/GFPGANv1.4.pth",
upscale=2,
arch="clean",
channel_multiplier=2,
bg_upsampler=None,
)
self.face_restorer_full = GFPGANer(
model_path=f"{UPSCALE_WEIGHTS_DIR}/GFPGANv1.4.pth",
upscale=2,
arch="clean",
channel_multiplier=2,
bg_upsampler=self.upscaler,
)
# Swin2SR — default upscaler. Better photo quality than Real-ESRGAN
# (which is trained heavily on synthetic/anime and produces a painted
# look on real photos). x4 = real-world BSRGAN-PSNR weights, x2 = classical.
self.swin2sr_x4 = Swin2SRForImageSuperResolution.from_pretrained(
SWIN2SR_X4_REPO
).to("cuda").eval().half()
self.swin2sr_x2 = Swin2SRForImageSuperResolution.from_pretrained(
SWIN2SR_X2_REPO
).to("cuda").eval().half()
self.swin2sr_proc_x4 = AutoImageProcessor.from_pretrained(SWIN2SR_X4_REPO)
self.swin2sr_proc_x2 = AutoImageProcessor.from_pretrained(SWIN2SR_X2_REPO)
# DDColor — diffusion-free colorization (Apache-2.0). ConvNeXt-Large
# backbone predicts ab channels in LAB color space. Single feed-forward
# (no diffusion sampling), ~500ms warm on L4. Inputs can be color or
# B&W; the model treats input as grayscale internally.
self.colorizer = ms_pipeline(
"image-colorization",
model="damo/cv_ddcolor_image-colorization",
)
# LaMa — large-mask inpainting (Apache-2.0). Resolution-robust, deterministic,
# no prompts. Used by /inpaint. Loads cached weights downloaded at build time.
self.inpainter = SimpleLama()
# =========================================================================
# Auth + usage logging
# =========================================================================
# Two paths:
# 1. Legacy / public-beta — token in API_TOKEN env (comma-separated).
# Returns context with user_id=None, tier="free". No DB lookup.
# 2. Per-user kno_live_<32> / kno_test_<32> — SHA-256 hashed and looked
# up in Supabase tokens table. Returns full context (user_id, token_id,
# tier) used by usage logging + meter reporting.
#
# _check_auth now returns the context dict so endpoints can call _log_usage
# afterwards. On failure it raises HTTPException as before.
def _supabase_request(
self,
method: str,
path: str,
params: Optional[dict] = None,
body: Optional[dict] = None,
prefer: Optional[str] = None,
) -> Tuple[int, bytes]:
"""Talk to Supabase REST. Service role bypasses RLS — only run server-side."""
url = os.environ["SUPABASE_URL"].rstrip("/") + path
if params:
url += "?" + urllib.parse.urlencode(params, safe=",.()*=:")
headers = {
"apikey": os.environ["SUPABASE_SERVICE_ROLE_KEY"],
"Authorization": f"Bearer {os.environ['SUPABASE_SERVICE_ROLE_KEY']}",
"Content-Type": "application/json",
}
if prefer:
headers["Prefer"] = prefer
data = json.dumps(body).encode("utf-8") if body is not None else None
req = urllib.request.Request(url, method=method, headers=headers, data=data)
try:
with urllib.request.urlopen(req, timeout=5) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
except Exception:
return 0, b""
# ---- Supabase Storage (video jobs) --------------------------------------
def _storage_request(self, method: str, path: str, data: Optional[bytes] = None,
content_type: str = "application/octet-stream",
timeout: int = 120) -> Tuple[int, bytes]:
"""Raw call against Supabase Storage. Service role only, server-side."""
url = os.environ["SUPABASE_URL"].rstrip("/") + "/storage/v1" + path
headers = {
"apikey": os.environ["SUPABASE_SERVICE_ROLE_KEY"],
"Authorization": f"Bearer {os.environ['SUPABASE_SERVICE_ROLE_KEY']}",
"Content-Type": content_type,
}
req = urllib.request.Request(url, method=method, headers=headers, data=data)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def _storage_upload(self, path: str, data: bytes, content_type: str) -> None:
status, body = self._storage_request(
"POST", f"/object/{VIDEO_BUCKET}/{path}", data=data, content_type=content_type)
if status not in (200, 201):
raise RuntimeError(f"storage upload failed ({status}): {body[:200]!r}")
def _storage_download(self, path: str) -> bytes:
status, body = self._storage_request("GET", f"/object/{VIDEO_BUCKET}/{path}")
if status != 200:
raise RuntimeError(f"storage download failed ({status}): {body[:200]!r}")
return body
def _storage_signed_url(self, path: str, expires_s: int = 3600) -> str:
status, body = self._storage_request(
"POST", f"/object/sign/{VIDEO_BUCKET}/{path}",
data=json.dumps({"expiresIn": expires_s}).encode(),
content_type="application/json")
if status != 200:
raise RuntimeError(f"sign failed ({status}): {body[:200]!r}")
signed = json.loads(body).get("signedURL", "")
return os.environ["SUPABASE_URL"].rstrip("/") + "/storage/v1" + signed
def _job_update(self, job_id: str, **fields) -> None:
"""Patch a video_jobs row. Best-effort — worker keeps going on failure."""
fields["updated_at"] = datetime.now(timezone.utc).isoformat()
try:
self._supabase_request(
"PATCH", "/rest/v1/video_jobs",
params={"id": f"eq.{job_id}"}, body=fields, prefer="return=minimal")
except Exception:
pass
def _job_get(self, job_id: str) -> Optional[dict]:
status, body = self._supabase_request(
"GET", "/rest/v1/video_jobs", params={"id": f"eq.{job_id}", "select": "*"})
if status != 200:
return None
rows = json.loads(body)
return rows[0] if rows else None
def _check_auth(self, authorization: Optional[str]) -> dict:
"""Returns a TokenContext dict. Raises HTTPException on auth failure."""
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Missing bearer token")
presented = authorization.split(" ", 1)[1].strip()
if not presented:
raise HTTPException(status_code=401, detail="Empty bearer token")
# Hard-retired tokens — recognized only so we can return a helpful 402
# upsell instead of a generic auth error. No access. Env-driven so a
# leaked key can be killed without a redeploy.
retired = set()
retired_env = os.environ.get("API_TOKEN_RETIRED", "").strip()
if retired_env:
retired |= {t.strip() for t in retired_env.split(",") if t.strip()}
if presented in retired:
raise HTTPException(
status_code=402,
detail=(
"This key has been retired. Create a free account at "
"useknockout.com/signin — 30 images/month free, no card, "
"then pay-as-you-go at $0.05/image (4x cheaper than remove.bg)."
),
)
# Anonymous shared demo key(s) — a throttled taste of the product. The
# old public-beta key now lands here instead of being killed: it stays
# the frictionless "try it in 3 seconds" hook, but downstream gating
# restricts it to /remove only, downscales output, and enforces a
# global daily cap (see _check_endpoint_access / _enforce_demo_limit).
# is_legacy keeps it out of the per-user usage table + monthly quota.
demo_keys = {"kno_public_beta_4d7e9f1a3c5b2e8d6a9f7c1b3e5d8a2f"}
demo_env = os.environ.get("API_TOKEN_DEMO", "").strip()
if demo_env:
demo_keys |= {t.strip() for t in demo_env.split(",") if t.strip()}
if presented in demo_keys:
return {
"user_id": None,
"token_id": None,
"tier": "free",
"is_legacy": True,
"is_demo": True,
}
# Path 1: legacy / public-beta token via API_TOKEN env.
legacy_raw = os.environ.get("API_TOKEN", "").strip()
legacy_set = {t.strip() for t in legacy_raw.split(",") if t.strip()}
if presented in legacy_set:
return {"user_id": None, "token_id": None, "tier": "free", "is_legacy": True}
# Path 1.5: portal session credential from the web app.
# Format: knoportal.<token_row_uuid>.<supabase access JWT (ES256)>
# The browser never holds a plaintext kno_* key; it proves identity with
# the user's Supabase session JWT, and the token row id names WHICH of
# their keys to act as. Ownership is enforced in the lookup query.
if presented.startswith("knoportal."):
return self._check_portal_auth(presented[len("knoportal."):])
# Path 2: per-user kno_* token. SHA-256 hashed lookup.
if not presented.startswith("kno_"):
raise HTTPException(status_code=401, detail="Invalid token format")
hashed = hashlib.sha256(presented.encode("utf-8")).hexdigest()
status, body = self._supabase_request(
"GET",
"/rest/v1/tokens",
params={
"select": "id,user_id,scopes,revoked_at",
"hashed_token": f"eq.{hashed}",
"revoked_at": "is.null",
"limit": "1",
},
)
if status != 200:
raise HTTPException(status_code=503, detail="Auth service unavailable")
try:
rows = json.loads(body) if body else []
except json.JSONDecodeError:
rows = []
if not rows:
raise HTTPException(status_code=401, detail="Invalid or revoked token")
return self._ctx_from_token_row(rows[0])
_jwks_client = None # class-level PyJWKClient cache (fetches Supabase JWKS once per container)
def _check_portal_auth(self, rest: str) -> dict:
"""Verify a knoportal.<key_id>.<jwt> credential. See Path 1.5 above.
JWT verification is asymmetric (ES256 via the project's JWKS endpoint,
confirmed live 2026-08-23) — no shared secret enters this codebase.
"""
key_id, _, jwt_token = rest.partition(".")
if not key_id or not jwt_token or "." not in jwt_token:
raise HTTPException(status_code=401, detail="Invalid portal credential format")
try:
import jwt as pyjwt
from jwt import PyJWKClient
if Knockout._jwks_client is None:
jwks_url = os.environ["SUPABASE_URL"].rstrip("/") + "/auth/v1/.well-known/jwks.json"
Knockout._jwks_client = PyJWKClient(jwks_url, cache_keys=True)
signing_key = Knockout._jwks_client.get_signing_key_from_jwt(jwt_token)
payload = pyjwt.decode(
jwt_token, signing_key.key,
algorithms=["ES256"], audience="authenticated",
)
except HTTPException:
raise
except Exception as e:
print(f"portal auth: JWT verification failed: {type(e).__name__}")
raise HTTPException(status_code=401, detail="Invalid or expired portal session")
sub = payload.get("sub")
if not sub:
raise HTTPException(status_code=401, detail="Invalid portal session")
# Ownership enforced in the query: the key row must belong to the JWT's user.
status, body = self._supabase_request(
"GET",
"/rest/v1/tokens",
params={
"select": "id,user_id,scopes,revoked_at",
"id": f"eq.{key_id}",
"user_id": f"eq.{sub}",
"revoked_at": "is.null",
"limit": "1",
},
)
if status != 200:
raise HTTPException(status_code=503, detail="Auth service unavailable")
try:
rows = json.loads(body) if body else []
except json.JSONDecodeError:
rows = []
if not rows:
raise HTTPException(status_code=401, detail="Portal key not found or revoked")
return self._ctx_from_token_row(rows[0])
def _ctx_from_token_row(self, row: dict) -> dict:
"""Token row → TokenContext. Shared by the raw-key and portal paths so
tier resolution can never diverge between them."""
token_id = row["id"]
user_id = row["user_id"]
scopes = row.get("scopes") or []
# Look up tier on the user.
ustatus, ubody = self._supabase_request(
"GET",
"/rest/v1/users",
params={
"select": "tier,stripe_customer_id",
"id": f"eq.{user_id}",
"limit": "1",
},
)
tier = "free"
stripe_customer_id = None
if ustatus == 200:
try:
urows = json.loads(ubody) if ubody else []
if urows:
tier = urows[0].get("tier") or "free"
stripe_customer_id = urows[0].get("stripe_customer_id")
except json.JSONDecodeError:
pass
# Bump last_used_at (best-effort, fire-and-forget).
try:
self._supabase_request(
"PATCH",
"/rest/v1/tokens",
params={"id": f"eq.{token_id}"},
body={"last_used_at": _now_iso()},
)
except Exception:
pass
return {
"user_id": user_id,
"token_id": token_id,
"tier": tier,
"scopes": scopes,
"stripe_customer_id": stripe_customer_id,
"is_legacy": False,
}
def _check_endpoint_access(self, ctx: dict, endpoint: str) -> None:
"""Tier-based endpoint gate.
- Demo key: /remove only (DEMO_ENDPOINTS).
- Signed-up free tier: blocked from paid endpoints (anything not in
FREE_TIER_ENDPOINTS).
- Internal full-access API_TOKEN (is_legacy, not demo): ungated.
- Paid tiers: ungated.
"""
if ctx.get("is_demo"):
if endpoint not in DEMO_ENDPOINTS:
allowed = ", ".join(sorted(DEMO_ENDPOINTS))
raise HTTPException(
status_code=402,
detail=(
f"The shared demo key only supports {allowed} (low-res). "
"Create a free account at useknockout.com/signin for your "
"own key — 30 full-quality images/month free across the "
"core endpoints, no card."
),
)
return
# Internal legacy full-access token (API_TOKEN env) — not tier-gated.
if ctx.get("is_legacy"):
return
if ctx.get("tier") == "free" and endpoint not in FREE_TIER_ENDPOINTS:
raise HTTPException(
status_code=402,
detail=(
f"{endpoint} is a paid endpoint. Your free tier covers the "
f"{len(FREE_TIER_ENDPOINTS)} core endpoints (background "
"removal + helpers). Upgrade for edits, AI enhancement, "
"e-commerce presets & batch at useknockout.com/pricing — "
"pay-as-you-go $0.05/image, no minimum."
),
)
def _enforce_demo_limit(self, ctx: dict) -> None:
"""Global daily cap on the anonymous shared demo key. No-op otherwise.
Soft cap: read-modify-write on a date-keyed counter in the existing
knockout-stats modal.Dict (no DB change). Minor overshoot under
concurrency is fine — this is a cost guard, not a billing meter.
"""
if not ctx.get("is_demo"):
return
try:
cap = int(os.environ.get("DEMO_DAILY_CAP", "") or DEMO_DAILY_CAP_DEFAULT)
except ValueError:
cap = DEMO_DAILY_CAP_DEFAULT
day = datetime.now(timezone.utc).strftime("%Y-%m-%d")
key = f"demo-{day}"
try:
d = modal.Dict.from_name("knockout-stats", create_if_missing=True)
used = int(d.get(key, 0))
if used >= cap:
raise HTTPException(
status_code=402,
detail=(
"The shared demo key has hit today's global free limit. "
"Create a free account at useknockout.com/signin for your "
"own key — 30 images/month free, no card, available now."
),
)
d[key] = used + 1
# Per-IP daily cap, on top of the global one. Requested by the
# web-app session (2026-08-23): the demo key is public and CORS is
# open, so browser-side throttles are decoration — only this
# server-side counter is real. IPs are salted-hashed, never stored.
ip = (ctx.get("client_ip") or "").strip()
if ip:
try:
ip_cap = int(os.environ.get("DEMO_IP_DAILY_CAP", "")
or DEMO_IP_DAILY_CAP_DEFAULT)
except ValueError:
ip_cap = DEMO_IP_DAILY_CAP_DEFAULT
iph = hashlib.sha256((DEMO_IP_SALT + ip).encode("utf-8")).hexdigest()[:16]
ip_key = f"demo-ip:{day}:{iph}"
ip_used = int(d.get(ip_key, 0))
if ip_used >= ip_cap:
raise HTTPException(
status_code=429,
detail=(
"Daily free limit reached for this connection. "
"Sign in at useknockout.com/signin for your own key — "
"30 images/month free, no card."
),
)
d[ip_key] = ip_used + 1
except HTTPException:
raise
except Exception:
# Never fail a real call because the counter store hiccuped.
pass
def _check_scope(self, ctx: dict, endpoint: str) -> None:
"""If a token has scopes, deny calls to endpoints not in the list."""
scopes = ctx.get("scopes") or []
if not scopes:
return # full-access token
if endpoint not in scopes:
raise HTTPException(
status_code=403,
detail=f"Token not authorized for {endpoint}",
)
def _is_pro(self, ctx: dict) -> bool:
"""True for Knockout Plus ('pro') and enterprise ('volume') tiers."""
return ctx.get("tier") in {"pro", "volume"}
def _require_pro(self, ctx: dict, feature: str = "This feature") -> None:
"""Gate premium features behind Knockout Plus. 402 for everyone else.
Internal full-access (is_legacy) bypasses, so the owner's own key still
works for testing. Premium = despill, watermarks, saved presets.
"""
if ctx.get("is_legacy") or self._is_pro(ctx):
return
raise HTTPException(
status_code=402,
detail=(
f"{feature} requires Knockout Plus. Upgrade at "
"useknockout.com/pricing to unlock edge despill, saved presets, "
"custom watermarks, and PSD-included exports for $10/month."
),
)
def _enforce_quota(self, ctx: dict) -> None:
"""Free tier: FREE_MONTHLY_QUOTA images/month. Paid tiers: no cap."""
if ctx.get("is_legacy"):
return
if ctx.get("tier") != "free":