andevs commited on
Commit
ef47fd3
·
verified ·
1 Parent(s): 8994082

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +209 -63
app.py CHANGED
@@ -1,19 +1,23 @@
1
  #!/usr/bin/env python3
2
- # app.py - Background Remover v32.9.5
3
  #
4
- # ===== CHANGES vs v32.9.2 =====
5
- # 1. isnet-general-use is the WORKHORSE: preloaded, native 1024px, routes
6
- # human / vehicle / product / medium / complex. birefnet-general-lite is
7
- # LAZY and only used for genuinely very_hard inputs when RSS allows.
8
- # 2. MODEL_RES_CAPS matched to each model's native resolution.
9
- # 3. Memory: pixel-count guard before decode, JPEG draft() reduced-scale
10
- # decode, MALLOC_TRIM/MMAP_THRESHOLD env, explicit del of large buffers,
11
- # accurate 'anon' cgroup reporting.
12
- # 4. Router: isnet workhorse lanes + birefnet specialist upgrade path.
13
- # 5. Fallback chain never lazy-loads birefnet on AUTO path. Explicit
14
- # ?model=birefnet-lite DOES lazy-load it.
15
- # 6. _birefnet_viable() math fixed (was comparing % + MB).
16
- # 7. /api/debug/reset endpoint to reclaim memory without a Space restart.
 
 
 
 
17
 
18
  import starlette.formparsers as _sfp
19
  _orig_spooled = _sfp.SpooledTemporaryFile
@@ -62,7 +66,7 @@ try:
62
  if 'sess_options' not in kwargs and 'so' not in kwargs:
63
  try:
64
  so = _ort.SessionOptions()
65
- so.intra_op_num_threads = 1
66
  so.inter_op_num_threads = 1
67
  so.enable_cpu_mem_arena = False
68
  so.enable_mem_pattern = False
@@ -73,7 +77,7 @@ try:
73
  return _orig_session_init(self, *args, **kwargs)
74
 
75
  _ort.InferenceSession.__init__ = _patched_session_init
76
- print("ONNX Runtime patched: arena=OFF, mem_pattern=OFF, threads=1/1")
77
  except Exception as e:
78
  print(f"Could not patch ONNX Runtime: {e}")
79
 
@@ -513,7 +517,7 @@ class ContentClassifier:
513
 
514
 
515
  os.environ["U2NET_HOME"] = "/tmp/u2net_models"
516
- os.environ["OMP_NUM_THREADS"] = "1"
517
  os.environ["CUDA_VISIBLE_DEVICES"] = ""
518
  os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
519
  os.environ["PYTHONUNBUFFERED"] = "1"
@@ -532,7 +536,7 @@ SERIALIZE_INFERENCE = os.environ.get('SERIALIZE_INFERENCE', '1') == '1'
532
  _image_semaphore = threading.Semaphore(1)
533
  _birefnet_semaphore = threading.Semaphore(1)
534
  BIREFNET_RSS_GATE_PERCENT = 88.0
535
- BIREFNET_INFERENCE_RSS_MB = 60
536
 
537
  ALPHA_SMOOTH_WEIGHT = 0.35
538
  ALPHA_CACHE_MAX_SESSIONS = 8
@@ -800,12 +804,26 @@ def _cap_output_size(size: tuple, max_size: int) -> tuple:
800
  return (max(1, int(w * scale)), max(1, int(h * scale)))
801
 
802
 
803
- def _safe_open_image(data: bytes, draft_target: int = 2048) -> Image.Image:
 
 
 
 
 
 
 
 
 
 
 
 
 
804
  try:
805
  img = Image.open(io.BytesIO(data))
806
  except Exception as e:
807
  raise HTTPException(400, f"Cannot decode image: {str(e)[:100]}")
808
- w, h = img.size
 
809
  if w * h > MAX_IMAGE_PIXELS:
810
  raise HTTPException(
811
  413,
@@ -820,7 +838,7 @@ def _safe_open_image(data: bytes, draft_target: int = 2048) -> Image.Image:
820
  if img.mode != 'RGBA':
821
  img = img.convert('RGBA')
822
  img.load()
823
- return img
824
 
825
 
826
  def process_with_neural(image, session, model_name,
@@ -1039,14 +1057,15 @@ def _prewarm_models():
1039
 
1040
 
1041
  logger.info("=" * 60)
1042
- logger.info("Background Remover v32.9.5")
1043
  logger.info(f"Preload: {[n for n, _ in PRELOAD_MODELS]}")
1044
  logger.info(f"Lazy active: {sorted(LAZY_ACTIVE_MODELS)}")
1045
  logger.info(f"Dormant: {sorted(DORMANT_MODELS.keys())}")
1046
  logger.info(f"MODEL_RES_CAPS: {MODEL_RES_CAPS}")
1047
- logger.info(f"BIREFNET_RSS_GATE_PERCENT: {BIREFNET_RSS_GATE_PERCENT}")
 
1048
  logger.info(f"SERIALIZE_INFERENCE: {SERIALIZE_INFERENCE}")
1049
- logger.info("Router: isnet workhorse; birefnet very_hard or explicit")
1050
  logger.info("=" * 60)
1051
 
1052
  preload_all_models()
@@ -1054,6 +1073,64 @@ initialize_models()
1054
  _prewarm_models()
1055
  _start_housekeeping()
1056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1057
  _log_rss("boot complete")
1058
  logger.info("=" * 60)
1059
 
@@ -1090,7 +1167,8 @@ def _birefnet_viable() -> bool:
1090
  total_mb = mem['total_mb']
1091
  if total_mb <= 0:
1092
  return True
1093
- projected_mb = mem['current_rss_mb'] + BIREFNET_INFERENCE_RSS_MB
 
1094
  projected_percent = (projected_mb / total_mb) * 100
1095
  return projected_percent <= BIREFNET_RSS_GATE_PERCENT
1096
 
@@ -1172,6 +1250,12 @@ def analyze_image_complexity(image):
1172
  has_u2net_human = 'u2net_human_seg' in loaded
1173
  rss_pct = round(get_container_memory()['current_rss_percent'], 1)
1174
 
 
 
 
 
 
 
1175
  tier_map = {
1176
  'vehicle': 'VEHICLE', 'simple_graphic': 'GRAPHIC',
1177
  'very_hard': 'VERY_HARD', 'human_hair': 'HUMAN_HAIR',
@@ -1189,6 +1273,8 @@ def analyze_image_complexity(image):
1189
  'is_human': is_human, 'is_graphic': is_graphic,
1190
  'hair_complexity': hc,
1191
  'cc_category': cc_cat, 'cc_confidence': 0.7,
 
 
1192
  'available': {
1193
  'isnet': has_isnet,
1194
  'birefnet_viable': has_birefnet_viable,
@@ -1206,18 +1292,25 @@ def analyze_image_complexity(image):
1206
  return _route('flood_fill', 'simple_graphic', 'classical',
1207
  'simple graphic')
1208
 
1209
- if (is_human
1210
- and hc['route'] in ('wispy_hair', 'complex_hair')
1211
- and complexity > 45):
 
 
 
 
 
 
1212
  if has_birefnet_viable:
1213
  return _route('birefnet-general-lite', 'human_hair', 'neural',
1214
- f'human+{hc["route"]}+cx{complexity:.0f} -> birefnet')
1215
  if has_isnet:
1216
  return _route('isnet-general-use', 'human_hair', 'neural',
1217
- f'human+{hc["route"]}+cx{complexity:.0f} -> isnet '
1218
- f'(birefnet not viable at {rss_pct}% RSS)')
 
1219
  return _route('silueta', 'human_hair', 'neural',
1220
- f'human+{hc["route"]} -> silueta')
1221
 
1222
  is_very_hard = (
1223
  max(image.size) > 2400
@@ -1317,8 +1410,22 @@ def process_image_sync(image_data, model_name=None, transparent=True,
1317
  logger.info(f"[REQ {req}] acquired")
1318
 
1319
  try:
1320
- image = _safe_open_image(image_data, draft_target=max(1024, max_size * 2))
1321
- original_size = image.size
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1322
 
1323
  if _has_meaningful_alpha(image) and model_name is None:
1324
  target = _cap_output_size(image.size, max_size)
@@ -1347,7 +1454,8 @@ def process_image_sync(image_data, model_name=None, transparent=True,
1347
  'router_category': 'alpha_passthrough',
1348
  'router_confidence': 1.0,
1349
  'mask_confidence': 1.0, 'mask_issues': [], 'hair_route': '',
1350
- 'hair_refined': False, 'diagnostics': [],
 
1351
  'dormant_rerouted': None, 'birefnet_swapped': None}
1352
 
1353
  if model_name:
@@ -1370,17 +1478,18 @@ def process_image_sync(image_data, model_name=None, transparent=True,
1370
  )
1371
 
1372
  birefnet_swapped = None
1373
- if selected == 'birefnet-general-lite' and model_name is None:
1374
  mem = get_container_memory()
1375
  total_mb = mem['total_mb'] or 1
1376
- projected_mb = mem['current_rss_mb'] + BIREFNET_INFERENCE_RSS_MB
 
1377
  projected_percent = (projected_mb / total_mb) * 100
1378
  if projected_percent > BIREFNET_RSS_GATE_PERCENT:
1379
  fallback = ('isnet-general-use'
1380
  if 'isnet-general-use' in model_manager.models
1381
  else 'silueta')
1382
  logger.warning(
1383
- f"Birefnet would push RSS to {projected_percent:.1f}% "
1384
  f"({projected_mb:.0f}MB, gate {BIREFNET_RSS_GATE_PERCENT}%) "
1385
  f"-> {fallback}"
1386
  )
@@ -1415,8 +1524,7 @@ def process_image_sync(image_data, model_name=None, transparent=True,
1415
  tried.add(candidate)
1416
 
1417
  if (candidate == 'birefnet-general-lite'
1418
- and candidate not in model_manager.models
1419
- and model_name is None):
1420
  continue
1421
 
1422
  cand_session = get_session_for_model(candidate)
@@ -1448,7 +1556,10 @@ def process_image_sync(image_data, model_name=None, transparent=True,
1448
  f"All models failed. First: {json.dumps(diagnostics[:2])[:400]}"
1449
  )
1450
 
 
 
1451
  hair_refined = False
 
1452
  mask_quality = {'confidence': 1.0, 'issues': [], 'passed': True}
1453
  if (result.mode == 'RGBA'
1454
  and preserve_hair
@@ -1457,15 +1568,36 @@ def process_image_sync(image_data, model_name=None, transparent=True,
1457
  alpha = np.array(result)[:, :, 3]
1458
  q = mask_checker.check(alpha)
1459
  mask_quality = q
1460
- if not q['passed']:
1461
- refined = hair_refiner.refine(alpha)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1462
  arr = np.array(result.convert('RGBA'))
1463
- arr[:, :, 3] = refined
1464
  result = Image.fromarray(arr, 'RGBA')
1465
- hair_refined = True
1466
- mask_quality = mask_checker.check(np.array(result)[:, :, 3])
1467
- except Exception:
1468
- pass
 
 
1469
 
1470
  if selected in ('u2netp', 'silueta'):
1471
  frag = {'fragment_ratio': 0.0, 'quality_score': 100.0,
@@ -1512,7 +1644,9 @@ def process_image_sync(image_data, model_name=None, transparent=True,
1512
  'mask_confidence': mask_quality.get('confidence', 0),
1513
  'mask_issues': mask_quality.get('issues', []),
1514
  'hair_route': (route_analysis.get('hair_complexity', {}) or {}).get('route', '') if route_analysis else '',
1515
- 'hair_refined': hair_refined, 'diagnostics': diagnostics,
 
 
1516
  'dormant_rerouted': None, 'birefnet_swapped': birefnet_swapped}
1517
  except HTTPException:
1518
  raise
@@ -1626,7 +1760,7 @@ def _process_frames_sync(raw_frames, resolved_model, transparent,
1626
  return results
1627
 
1628
 
1629
- app = FastAPI(title="Background Remover", version="32.9.5")
1630
  app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True,
1631
  allow_methods=["*"], allow_headers=["*"])
1632
 
@@ -1695,7 +1829,8 @@ async def process_image_api(
1695
  raise HTTPException(400, "Not an image")
1696
  contents = await file.read()
1697
  if not contents: raise HTTPException(400, "Empty")
1698
- if len(contents) > 30 * 1024 * 1024: raise HTTPException(400, "Too large")
 
1699
  if not AI_AVAILABLE: raise HTTPException(503, "AI unavailable")
1700
 
1701
  user_model = None
@@ -1730,6 +1865,7 @@ async def process_image_api(
1730
  'X-Router-Tier': _header_safe(result_data.get('router_tier', '')),
1731
  'X-Router-Score': f"{result_data.get('router_score', 0):.1f}",
1732
  'X-Router-Reason': _header_safe(result_data.get('router_reason', '')),
 
1733
  'Content-Disposition': _content_disposition(
1734
  f"processed_{fn}.{ext}", fallback=f"processed.{ext}"
1735
  ),
@@ -1938,6 +2074,8 @@ async def debug_memory():
1938
  'dormant_models': sorted(DORMANT_MODELS.keys()),
1939
  'alpha_cache': _alpha_cache_stats(),
1940
  'serialize_inference': SERIALIZE_INFERENCE,
 
 
1941
  'malloc_env': {
1942
  'MALLOC_ARENA_MAX': os.environ.get('MALLOC_ARENA_MAX'),
1943
  'MALLOC_TRIM_THRESHOLD_': os.environ.get('MALLOC_TRIM_THRESHOLD_'),
@@ -1950,7 +2088,7 @@ async def debug_memory():
1950
  async def debug_route(file: UploadFile = File(...)):
1951
  try:
1952
  contents = await file.read()
1953
- image = _safe_open_image(contents, draft_target=1024)
1954
  if image.mode not in ('RGB', 'L'):
1955
  image = image.convert('RGB')
1956
  analysis = analyze_image_complexity(image)
@@ -1964,6 +2102,8 @@ async def debug_route(file: UploadFile = File(...)):
1964
  'complexity': analysis.get('score'),
1965
  'is_graphic': analysis.get('is_graphic'),
1966
  'is_human': analysis.get('is_human'),
 
 
1967
  'available': analysis.get('available'),
1968
  },
1969
  'memory': {
@@ -1972,7 +2112,7 @@ async def debug_route(file: UploadFile = File(...)):
1972
  'birefnet_loaded': 'birefnet-general-lite' in model_manager.models,
1973
  'birefnet_viable': _birefnet_viable(),
1974
  },
1975
- 'image': {'size': list(image.size)},
1976
  }
1977
  except HTTPException:
1978
  raise
@@ -2031,10 +2171,13 @@ async def debug_env():
2031
  'video_max_batch': VIDEO_MAX_BATCH,
2032
  'birefnet_res_cap': MODEL_RES_CAPS.get('birefnet-general-lite'),
2033
  'birefnet_rss_gate': BIREFNET_RSS_GATE_PERCENT,
 
 
 
2034
  'preload_models': [n for n, _ in PRELOAD_MODELS],
2035
  'torch_loaded': 'torch' in sys.modules,
2036
- 'onnx_threads': 1,
2037
- 'version': '32.9.5',
2038
  'serialize_inference': SERIALIZE_INFERENCE,
2039
  }
2040
 
@@ -2046,7 +2189,7 @@ async def home():
2046
  warmed = sum(1 for w in stats['warmed'].values() if w)
2047
  return HTMLResponse(f"""
2048
  <!DOCTYPE html><html><head><meta charset="UTF-8">
2049
- <title>Background Remover v32.9.5</title>
2050
  <style>body{{font-family:system-ui;background:#0A0A0A;color:#fff;
2051
  min-height:100vh;display:flex;align-items:center;justify-content:center;
2052
  margin:0;padding:20px}}.c{{max-width:900px;background:#111;
@@ -2054,13 +2197,13 @@ async def home():
2054
  .s{{padding:15px;border-radius:12px;margin:20px 0;background:#1a1a1a}}
2055
  a{{color:#7ED957}}</style>
2056
  </head><body><div class="c">
2057
- <h1>Background Remover v32.9.5</h1>
2058
  <div class="s">AI online. {len(stats['loaded_models'])} models loaded ({warmed} warmed).<br>
2059
  RSS {mem['current_rss_percent']:.1f}% ({mem['current_rss_mb']}MB) ·
2060
  anon {mem['anon_percent']:.1f}% ({mem['anon_mb']}MB) ·
2061
  Peak {mem['peak_rss_percent']:.0f}%</div>
2062
  <p>Preload: u2netp · silueta · isnet (workhorse)</p>
2063
- <p>Lazy: birefnet-lite · isnet-anime · u2net-human-seg</p>
2064
  <p><a href="/docs">API Docs</a> ·
2065
  <a href="/api/models">Models</a> ·
2066
  <a href="/api/debug/memory">Memory</a> ·
@@ -2117,6 +2260,7 @@ async def health_check():
2117
  'silueta_ready': silueta_ready,
2118
  'isnet_ready': isnet_ready,
2119
  'birefnet_loaded': 'birefnet-general-lite' in stats['loaded_models'],
 
2120
  'preloaded_models': preload_names,
2121
  'lazy_active_models': sorted(LAZY_ACTIVE_MODELS),
2122
  'dormant_models': sorted(DORMANT_MODELS.keys()),
@@ -2133,9 +2277,10 @@ async def health_check():
2133
  'video_force_model': VIDEO_FORCE_MODEL,
2134
  'birefnet_res_cap': MODEL_RES_CAPS.get('birefnet-general-lite'),
2135
  'birefnet_rss_gate': BIREFNET_RSS_GATE_PERCENT,
2136
- 'version': '32.9.5',
 
2137
  'alpha_smoothing': _alpha_cache_stats(),
2138
- 'onnx_threads': 1,
2139
  'torch_loaded': 'torch' in sys.modules,
2140
  'serialize_inference': SERIALIZE_INFERENCE,
2141
  }
@@ -2157,17 +2302,18 @@ async def gen_exc(request, exc):
2157
  @app.on_event("startup")
2158
  async def startup():
2159
  logger.info("=" * 60)
2160
- logger.info("v32.9.5 ready")
2161
  logger.info(f"Preload: {[n for n, _ in PRELOAD_MODELS]}")
2162
  logger.info(f"Lazy active: {sorted(LAZY_ACTIVE_MODELS)}")
2163
  logger.info(f"Dormant: {sorted(DORMANT_MODELS.keys())}")
2164
  logger.info(f"SERIALIZE_INFERENCE: {SERIALIZE_INFERENCE}")
 
2165
  logger.info(f"MALLOC env: ARENA_MAX={os.environ.get('MALLOC_ARENA_MAX')}, "
2166
  f"TRIM={os.environ.get('MALLOC_TRIM_THRESHOLD_')}, "
2167
  f"MMAP={os.environ.get('MALLOC_MMAP_THRESHOLD_')}")
2168
- logger.info("Router: isnet workhorse; birefnet very_hard or explicit")
2169
- logger.info("Output cap: result <= max_size")
2170
- logger.info("Image timeout: 32s")
2171
  logger.info("=" * 60)
2172
  _log_rss("startup")
2173
 
 
1
  #!/usr/bin/env python3
2
+ # app.py - Background Remover v32.9.7
3
  #
4
+ # ===== CHANGES vs v32.9.6 =====
5
+ # 1. Router: new fine-detail lane. is_human + cc_edge > 0.15 → birefnet.
6
+ # Fixes wedding dress / lace / veil / embroidered fabric routing to isnet.
7
+ # 2. isnet post-processing: skip HairRefiner (it preserved the halo). Add
8
+ # _tighten_alpha() that clips alpha<40, sharpens [40,215]. Birefnet and
9
+ # u2net_human_seg are NOT tightened (already sharp).
10
+ # 3. _safe_open_image returns (image, true_size). Fixes original_size
11
+ # reporting after JPEG draft() reduced the decode size.
12
+ # 4. Upload cap 30 → 50 MB. Allows 24 MP JPEGs (8-15 MB) and moderate
13
+ # 24 MP PNGs (30-50 MB).
14
+ # 5. /api/process/image response includes X-Alpha-Tightened header so
15
+ # callers can verify when tightening fired.
16
+ #
17
+ # ===== PRESERVED from v32.9.6 =====
18
+ # ONNX threads 2/1, OMP 2, MALLOC env, birefnet bg preload at t+60s,
19
+ # explicit request block up to 25s, RSS gate on anon not VmRSS,
20
+ # BIREFNET_INFERENCE_RSS_MB=150, MODEL_RES_CAPS at native resolutions.
21
 
22
  import starlette.formparsers as _sfp
23
  _orig_spooled = _sfp.SpooledTemporaryFile
 
66
  if 'sess_options' not in kwargs and 'so' not in kwargs:
67
  try:
68
  so = _ort.SessionOptions()
69
+ so.intra_op_num_threads = 2
70
  so.inter_op_num_threads = 1
71
  so.enable_cpu_mem_arena = False
72
  so.enable_mem_pattern = False
 
77
  return _orig_session_init(self, *args, **kwargs)
78
 
79
  _ort.InferenceSession.__init__ = _patched_session_init
80
+ print("ONNX Runtime patched: arena=OFF, mem_pattern=OFF, threads=2/1")
81
  except Exception as e:
82
  print(f"Could not patch ONNX Runtime: {e}")
83
 
 
517
 
518
 
519
  os.environ["U2NET_HOME"] = "/tmp/u2net_models"
520
+ os.environ["OMP_NUM_THREADS"] = "2"
521
  os.environ["CUDA_VISIBLE_DEVICES"] = ""
522
  os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
523
  os.environ["PYTHONUNBUFFERED"] = "1"
 
536
  _image_semaphore = threading.Semaphore(1)
537
  _birefnet_semaphore = threading.Semaphore(1)
538
  BIREFNET_RSS_GATE_PERCENT = 88.0
539
+ BIREFNET_INFERENCE_RSS_MB = 150
540
 
541
  ALPHA_SMOOTH_WEIGHT = 0.35
542
  ALPHA_CACHE_MAX_SESSIONS = 8
 
804
  return (max(1, int(w * scale)), max(1, int(h * scale)))
805
 
806
 
807
+ def _tighten_alpha(alpha: np.ndarray, lo: int = 40, hi: int = 215) -> np.ndarray:
808
+ a = alpha.astype(np.float32) / 255.0
809
+ lo_f = lo / 255.0
810
+ hi_f = hi / 255.0
811
+ a[a < lo_f] = 0.0
812
+ a[a > hi_f] = 1.0
813
+ band = (a > 0.0) & (a < 1.0)
814
+ if band.any():
815
+ t = (a[band] - lo_f) / (hi_f - lo_f)
816
+ a[band] = t * t * (3.0 - 2.0 * t)
817
+ return np.clip(a * 255, 0, 255).astype(np.uint8)
818
+
819
+
820
+ def _safe_open_image(data: bytes, draft_target: int = 2048) -> tuple:
821
  try:
822
  img = Image.open(io.BytesIO(data))
823
  except Exception as e:
824
  raise HTTPException(400, f"Cannot decode image: {str(e)[:100]}")
825
+ true_size = img.size
826
+ w, h = true_size
827
  if w * h > MAX_IMAGE_PIXELS:
828
  raise HTTPException(
829
  413,
 
838
  if img.mode != 'RGBA':
839
  img = img.convert('RGBA')
840
  img.load()
841
+ return img, true_size
842
 
843
 
844
  def process_with_neural(image, session, model_name,
 
1057
 
1058
 
1059
  logger.info("=" * 60)
1060
+ logger.info("Background Remover v32.9.7")
1061
  logger.info(f"Preload: {[n for n, _ in PRELOAD_MODELS]}")
1062
  logger.info(f"Lazy active: {sorted(LAZY_ACTIVE_MODELS)}")
1063
  logger.info(f"Dormant: {sorted(DORMANT_MODELS.keys())}")
1064
  logger.info(f"MODEL_RES_CAPS: {MODEL_RES_CAPS}")
1065
+ logger.info(f"BIREFNET_RSS_GATE_PERCENT: {BIREFNET_RSS_GATE_PERCENT} "
1066
+ f"(transient {BIREFNET_INFERENCE_RSS_MB}MB)")
1067
  logger.info(f"SERIALIZE_INFERENCE: {SERIALIZE_INFERENCE}")
1068
+ logger.info("Router: isnet workhorse; birefnet for very_hard / hair / fine_detail")
1069
  logger.info("=" * 60)
1070
 
1071
  preload_all_models()
 
1073
  _prewarm_models()
1074
  _start_housekeeping()
1075
 
1076
+
1077
+ _birefnet_preload_event = threading.Event()
1078
+ _birefnet_preload_lock = threading.Lock()
1079
+ _birefnet_preload_started = False
1080
+
1081
+
1082
+ def _load_birefnet_now():
1083
+ global _birefnet_preload_started
1084
+ with _birefnet_preload_lock:
1085
+ if _birefnet_preload_started:
1086
+ return
1087
+ _birefnet_preload_started = True
1088
+ try:
1089
+ logger.info("[birefnet] loading...")
1090
+ t0 = time.time()
1091
+ session = get_session_for_model('birefnet-general-lite')
1092
+ if session is not None:
1093
+ _warm_single_model('birefnet-general-lite', session)
1094
+ logger.info(f"[birefnet] ready in {time.time() - t0:.1f}s")
1095
+ else:
1096
+ logger.warning("[birefnet] load returned None")
1097
+ except Exception as e:
1098
+ logger.warning(f"[birefnet] load failed: {e}")
1099
+ finally:
1100
+ _birefnet_preload_event.set()
1101
+
1102
+
1103
+ def _trigger_birefnet_now():
1104
+ if 'birefnet-general-lite' in model_manager.models:
1105
+ _birefnet_preload_event.set()
1106
+ return
1107
+ threading.Thread(
1108
+ target=_load_birefnet_now, daemon=True, name="birefnet-now"
1109
+ ).start()
1110
+
1111
+
1112
+ def _background_birefnet_preload():
1113
+ time.sleep(60)
1114
+ if 'birefnet-general-lite' in model_manager.models:
1115
+ _birefnet_preload_event.set()
1116
+ return
1117
+ mem = get_container_memory()
1118
+ real_mb = mem['anon_mb'] if mem['anon_mb'] > 0 else mem['current_rss_mb']
1119
+ if mem['total_mb'] > 0 and (real_mb / mem['total_mb'] * 100) > 60:
1120
+ logger.warning(
1121
+ f"[birefnet] skipping bg preload: anon {real_mb}MB "
1122
+ f"({real_mb/mem['total_mb']*100:.0f}%) > 60%"
1123
+ )
1124
+ _birefnet_preload_event.set()
1125
+ return
1126
+ logger.info("[birefnet] background preload starting (t+60s)")
1127
+ _load_birefnet_now()
1128
+
1129
+
1130
+ threading.Thread(
1131
+ target=_background_birefnet_preload, daemon=True, name="birefnet-bg"
1132
+ ).start()
1133
+
1134
  _log_rss("boot complete")
1135
  logger.info("=" * 60)
1136
 
 
1167
  total_mb = mem['total_mb']
1168
  if total_mb <= 0:
1169
  return True
1170
+ real_mb = mem['anon_mb'] if mem['anon_mb'] > 0 else mem['current_rss_mb']
1171
+ projected_mb = real_mb + BIREFNET_INFERENCE_RSS_MB
1172
  projected_percent = (projected_mb / total_mb) * 100
1173
  return projected_percent <= BIREFNET_RSS_GATE_PERCENT
1174
 
 
1250
  has_u2net_human = 'u2net_human_seg' in loaded
1251
  rss_pct = round(get_container_memory()['current_rss_percent'], 1)
1252
 
1253
+ subject_fine_detail = (
1254
+ is_human
1255
+ and cc_cat in ('human_hair', 'human')
1256
+ and cc_edge > 0.15
1257
+ )
1258
+
1259
  tier_map = {
1260
  'vehicle': 'VEHICLE', 'simple_graphic': 'GRAPHIC',
1261
  'very_hard': 'VERY_HARD', 'human_hair': 'HUMAN_HAIR',
 
1273
  'is_human': is_human, 'is_graphic': is_graphic,
1274
  'hair_complexity': hc,
1275
  'cc_category': cc_cat, 'cc_confidence': 0.7,
1276
+ 'cc_edge': round(cc_edge, 3),
1277
+ 'subject_fine_detail': subject_fine_detail,
1278
  'available': {
1279
  'isnet': has_isnet,
1280
  'birefnet_viable': has_birefnet_viable,
 
1292
  return _route('flood_fill', 'simple_graphic', 'classical',
1293
  'simple graphic')
1294
 
1295
+ if is_human and (
1296
+ (hc['route'] in ('wispy_hair', 'complex_hair') and complexity > 45)
1297
+ or (subject_fine_detail and complexity > 30)
1298
+ ):
1299
+ reason_core = (
1300
+ f'human+{hc["route"]}+cx{complexity:.0f}'
1301
+ if hc['route'] in ('wispy_hair', 'complex_hair')
1302
+ else f'human+fine_detail(edge={cc_edge:.2f})+cx{complexity:.0f}'
1303
+ )
1304
  if has_birefnet_viable:
1305
  return _route('birefnet-general-lite', 'human_hair', 'neural',
1306
+ f'{reason_core} -> birefnet')
1307
  if has_isnet:
1308
  return _route('isnet-general-use', 'human_hair', 'neural',
1309
+ f'{reason_core} -> isnet '
1310
+ f'(birefnet not viable at {rss_pct}% RSS — '
1311
+ f'try BiRefNet Lite for best quality)')
1312
  return _route('silueta', 'human_hair', 'neural',
1313
+ f'{reason_core} -> silueta')
1314
 
1315
  is_very_hard = (
1316
  max(image.size) > 2400
 
1410
  logger.info(f"[REQ {req}] acquired")
1411
 
1412
  try:
1413
+ image, original_size = _safe_open_image(
1414
+ image_data, draft_target=max(1024, max_size * 2)
1415
+ )
1416
+
1417
+ if (model_name == 'birefnet-general-lite'
1418
+ and 'birefnet-general-lite' not in model_manager.models):
1419
+ logger.info(f"[REQ {req}] birefnet requested but not loaded — triggering load")
1420
+ _trigger_birefnet_now()
1421
+ got = _birefnet_preload_event.wait(timeout=25)
1422
+ if not got or 'birefnet-general-lite' not in model_manager.models:
1423
+ logger.warning(
1424
+ f"[REQ {req}] birefnet not ready after 25s — falling back to auto"
1425
+ )
1426
+ model_name = None
1427
+ else:
1428
+ logger.info(f"[REQ {req}] birefnet ready — proceeding")
1429
 
1430
  if _has_meaningful_alpha(image) and model_name is None:
1431
  target = _cap_output_size(image.size, max_size)
 
1454
  'router_category': 'alpha_passthrough',
1455
  'router_confidence': 1.0,
1456
  'mask_confidence': 1.0, 'mask_issues': [], 'hair_route': '',
1457
+ 'hair_refined': False, 'alpha_tightened': False,
1458
+ 'diagnostics': [],
1459
  'dormant_rerouted': None, 'birefnet_swapped': None}
1460
 
1461
  if model_name:
 
1478
  )
1479
 
1480
  birefnet_swapped = None
1481
+ if selected == 'birefnet-general-lite':
1482
  mem = get_container_memory()
1483
  total_mb = mem['total_mb'] or 1
1484
+ real_mb = mem['anon_mb'] if mem['anon_mb'] > 0 else mem['current_rss_mb']
1485
+ projected_mb = real_mb + BIREFNET_INFERENCE_RSS_MB
1486
  projected_percent = (projected_mb / total_mb) * 100
1487
  if projected_percent > BIREFNET_RSS_GATE_PERCENT:
1488
  fallback = ('isnet-general-use'
1489
  if 'isnet-general-use' in model_manager.models
1490
  else 'silueta')
1491
  logger.warning(
1492
+ f"Birefnet would push anon to {projected_percent:.1f}% "
1493
  f"({projected_mb:.0f}MB, gate {BIREFNET_RSS_GATE_PERCENT}%) "
1494
  f"-> {fallback}"
1495
  )
 
1524
  tried.add(candidate)
1525
 
1526
  if (candidate == 'birefnet-general-lite'
1527
+ and candidate not in model_manager.models):
 
1528
  continue
1529
 
1530
  cand_session = get_session_for_model(candidate)
 
1556
  f"All models failed. First: {json.dumps(diagnostics[:2])[:400]}"
1557
  )
1558
 
1559
+ HAIR_REFINER_MODELS = {'u2netp', 'silueta'}
1560
+
1561
  hair_refined = False
1562
+ alpha_tightened = False
1563
  mask_quality = {'confidence': 1.0, 'issues': [], 'passed': True}
1564
  if (result.mode == 'RGBA'
1565
  and preserve_hair
 
1568
  alpha = np.array(result)[:, :, 3]
1569
  q = mask_checker.check(alpha)
1570
  mask_quality = q
1571
+
1572
+ if selected in HAIR_REFINER_MODELS:
1573
+ if not q['passed']:
1574
+ refined = hair_refiner.refine(alpha)
1575
+ arr = np.array(result.convert('RGBA'))
1576
+ arr[:, :, 3] = refined
1577
+ result = Image.fromarray(arr, 'RGBA')
1578
+ hair_refined = True
1579
+ mask_quality = mask_checker.check(
1580
+ np.array(result)[:, :, 3]
1581
+ )
1582
+
1583
+ elif selected == 'isnet-general-use':
1584
+ hair_route = ''
1585
+ if route_analysis:
1586
+ hair_route = (route_analysis.get('hair_complexity', {})
1587
+ or {}).get('route', '')
1588
+ if hair_route in ('wispy_hair', 'complex_hair'):
1589
+ tightened = _tighten_alpha(alpha, lo=15, hi=240)
1590
+ else:
1591
+ tightened = _tighten_alpha(alpha, lo=40, hi=215)
1592
  arr = np.array(result.convert('RGBA'))
1593
+ arr[:, :, 3] = tightened
1594
  result = Image.fromarray(arr, 'RGBA')
1595
+ alpha_tightened = True
1596
+ mask_quality = mask_checker.check(
1597
+ np.array(result)[:, :, 3]
1598
+ )
1599
+ except Exception as e:
1600
+ logger.warning(f"post-processing failed: {e}")
1601
 
1602
  if selected in ('u2netp', 'silueta'):
1603
  frag = {'fragment_ratio': 0.0, 'quality_score': 100.0,
 
1644
  'mask_confidence': mask_quality.get('confidence', 0),
1645
  'mask_issues': mask_quality.get('issues', []),
1646
  'hair_route': (route_analysis.get('hair_complexity', {}) or {}).get('route', '') if route_analysis else '',
1647
+ 'hair_refined': hair_refined,
1648
+ 'alpha_tightened': alpha_tightened,
1649
+ 'diagnostics': diagnostics,
1650
  'dormant_rerouted': None, 'birefnet_swapped': birefnet_swapped}
1651
  except HTTPException:
1652
  raise
 
1760
  return results
1761
 
1762
 
1763
+ app = FastAPI(title="Background Remover", version="32.9.7")
1764
  app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True,
1765
  allow_methods=["*"], allow_headers=["*"])
1766
 
 
1829
  raise HTTPException(400, "Not an image")
1830
  contents = await file.read()
1831
  if not contents: raise HTTPException(400, "Empty")
1832
+ if len(contents) > 50 * 1024 * 1024:
1833
+ raise HTTPException(413, "Too large (server max 50 MB)")
1834
  if not AI_AVAILABLE: raise HTTPException(503, "AI unavailable")
1835
 
1836
  user_model = None
 
1865
  'X-Router-Tier': _header_safe(result_data.get('router_tier', '')),
1866
  'X-Router-Score': f"{result_data.get('router_score', 0):.1f}",
1867
  'X-Router-Reason': _header_safe(result_data.get('router_reason', '')),
1868
+ 'X-Alpha-Tightened': str(result_data.get('alpha_tightened', False)).lower(),
1869
  'Content-Disposition': _content_disposition(
1870
  f"processed_{fn}.{ext}", fallback=f"processed.{ext}"
1871
  ),
 
2074
  'dormant_models': sorted(DORMANT_MODELS.keys()),
2075
  'alpha_cache': _alpha_cache_stats(),
2076
  'serialize_inference': SERIALIZE_INFERENCE,
2077
+ 'birefnet_preload_started': _birefnet_preload_started,
2078
+ 'birefnet_preload_done': _birefnet_preload_event.is_set(),
2079
  'malloc_env': {
2080
  'MALLOC_ARENA_MAX': os.environ.get('MALLOC_ARENA_MAX'),
2081
  'MALLOC_TRIM_THRESHOLD_': os.environ.get('MALLOC_TRIM_THRESHOLD_'),
 
2088
  async def debug_route(file: UploadFile = File(...)):
2089
  try:
2090
  contents = await file.read()
2091
+ image, _true_size = _safe_open_image(contents, draft_target=1024)
2092
  if image.mode not in ('RGB', 'L'):
2093
  image = image.convert('RGB')
2094
  analysis = analyze_image_complexity(image)
 
2102
  'complexity': analysis.get('score'),
2103
  'is_graphic': analysis.get('is_graphic'),
2104
  'is_human': analysis.get('is_human'),
2105
+ 'cc_edge': analysis.get('cc_edge'),
2106
+ 'subject_fine_detail': analysis.get('subject_fine_detail'),
2107
  'available': analysis.get('available'),
2108
  },
2109
  'memory': {
 
2112
  'birefnet_loaded': 'birefnet-general-lite' in model_manager.models,
2113
  'birefnet_viable': _birefnet_viable(),
2114
  },
2115
+ 'image': {'size': list(image.size), 'true_size': list(_true_size)},
2116
  }
2117
  except HTTPException:
2118
  raise
 
2171
  'video_max_batch': VIDEO_MAX_BATCH,
2172
  'birefnet_res_cap': MODEL_RES_CAPS.get('birefnet-general-lite'),
2173
  'birefnet_rss_gate': BIREFNET_RSS_GATE_PERCENT,
2174
+ 'birefnet_inference_rss_mb': BIREFNET_INFERENCE_RSS_MB,
2175
+ 'birefnet_preload_started': _birefnet_preload_started,
2176
+ 'birefnet_preload_done': _birefnet_preload_event.is_set(),
2177
  'preload_models': [n for n, _ in PRELOAD_MODELS],
2178
  'torch_loaded': 'torch' in sys.modules,
2179
+ 'onnx_threads': 2,
2180
+ 'version': '32.9.7',
2181
  'serialize_inference': SERIALIZE_INFERENCE,
2182
  }
2183
 
 
2189
  warmed = sum(1 for w in stats['warmed'].values() if w)
2190
  return HTMLResponse(f"""
2191
  <!DOCTYPE html><html><head><meta charset="UTF-8">
2192
+ <title>Background Remover v32.9.7</title>
2193
  <style>body{{font-family:system-ui;background:#0A0A0A;color:#fff;
2194
  min-height:100vh;display:flex;align-items:center;justify-content:center;
2195
  margin:0;padding:20px}}.c{{max-width:900px;background:#111;
 
2197
  .s{{padding:15px;border-radius:12px;margin:20px 0;background:#1a1a1a}}
2198
  a{{color:#7ED957}}</style>
2199
  </head><body><div class="c">
2200
+ <h1>Background Remover v32.9.7</h1>
2201
  <div class="s">AI online. {len(stats['loaded_models'])} models loaded ({warmed} warmed).<br>
2202
  RSS {mem['current_rss_percent']:.1f}% ({mem['current_rss_mb']}MB) ·
2203
  anon {mem['anon_percent']:.1f}% ({mem['anon_mb']}MB) ·
2204
  Peak {mem['peak_rss_percent']:.0f}%</div>
2205
  <p>Preload: u2netp · silueta · isnet (workhorse)</p>
2206
+ <p>Lazy: birefnet-lite (bg-loads at t+60s) · isnet-anime · u2net-human-seg</p>
2207
  <p><a href="/docs">API Docs</a> ·
2208
  <a href="/api/models">Models</a> ·
2209
  <a href="/api/debug/memory">Memory</a> ·
 
2260
  'silueta_ready': silueta_ready,
2261
  'isnet_ready': isnet_ready,
2262
  'birefnet_loaded': 'birefnet-general-lite' in stats['loaded_models'],
2263
+ 'birefnet_preload_done': _birefnet_preload_event.is_set(),
2264
  'preloaded_models': preload_names,
2265
  'lazy_active_models': sorted(LAZY_ACTIVE_MODELS),
2266
  'dormant_models': sorted(DORMANT_MODELS.keys()),
 
2277
  'video_force_model': VIDEO_FORCE_MODEL,
2278
  'birefnet_res_cap': MODEL_RES_CAPS.get('birefnet-general-lite'),
2279
  'birefnet_rss_gate': BIREFNET_RSS_GATE_PERCENT,
2280
+ 'birefnet_inference_rss_mb': BIREFNET_INFERENCE_RSS_MB,
2281
+ 'version': '32.9.7',
2282
  'alpha_smoothing': _alpha_cache_stats(),
2283
+ 'onnx_threads': 2,
2284
  'torch_loaded': 'torch' in sys.modules,
2285
  'serialize_inference': SERIALIZE_INFERENCE,
2286
  }
 
2302
  @app.on_event("startup")
2303
  async def startup():
2304
  logger.info("=" * 60)
2305
+ logger.info("v32.9.7 ready")
2306
  logger.info(f"Preload: {[n for n, _ in PRELOAD_MODELS]}")
2307
  logger.info(f"Lazy active: {sorted(LAZY_ACTIVE_MODELS)}")
2308
  logger.info(f"Dormant: {sorted(DORMANT_MODELS.keys())}")
2309
  logger.info(f"SERIALIZE_INFERENCE: {SERIALIZE_INFERENCE}")
2310
+ logger.info(f"ONNX threads: 2 intra / 1 inter, OMP: {os.environ.get('OMP_NUM_THREADS')}")
2311
  logger.info(f"MALLOC env: ARENA_MAX={os.environ.get('MALLOC_ARENA_MAX')}, "
2312
  f"TRIM={os.environ.get('MALLOC_TRIM_THRESHOLD_')}, "
2313
  f"MMAP={os.environ.get('MALLOC_MMAP_THRESHOLD_')}")
2314
+ logger.info("Router: fine_detail (edge>0.15 + human) → birefnet")
2315
+ logger.info("Post-process: isnet=tighten_alpha, u2netp/silueta=refiner, birefnet=skip")
2316
+ logger.info("Upload cap: 50 MB (24 MP support)")
2317
  logger.info("=" * 60)
2318
  _log_rss("startup")
2319