jinkedon commited on
Commit
85062cc
Β·
verified Β·
1 Parent(s): fccf468

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -7
app.py CHANGED
@@ -6,8 +6,11 @@ from PIL import Image
6
  import requests
7
  import logging
8
 
9
- # Import the withoutBG library
10
- from withoutbg import WithoutBG
 
 
 
11
 
12
  # Configure logging
13
  logging.basicConfig(level=logging.INFO)
@@ -16,10 +19,35 @@ logger = logging.getLogger(__name__)
16
  app = Flask(__name__)
17
  CORS(app)
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  # Initialize the model once at startup
20
  try:
21
  logger.info("πŸš€ Loading withoutBG model...")
22
- model = WithoutBG.opensource()
23
  logger.info("βœ… Model loaded successfully!")
24
  except Exception as e:
25
  logger.error(f"❌ Failed to load model: {e}")
@@ -72,12 +100,12 @@ def remove_background():
72
 
73
  # Open image
74
  img = Image.open(image_data)
75
- logger.info(f"πŸ–ΌοΈ Image loaded: {img.size}")
76
 
77
- # Remove background using withoutBG
78
- logger.info("πŸ”„ Removing background...")
79
  result = model.remove_background(img)
80
- logger.info(f"βœ… Background removed successfully! Mode: {result.mode}, Size: {result.size}")
81
 
82
  # Convert to RGBA first if not already
83
  if result.mode != 'RGBA':
@@ -110,6 +138,8 @@ def remove_background():
110
 
111
  except Exception as e:
112
  logger.error(f"❌ Error: {e}")
 
 
113
  return jsonify({
114
  'success': False,
115
  'error': str(e)
 
6
  import requests
7
  import logging
8
 
9
+ # Import the withoutBG library (correct way from Qiita article)
10
+ from withoutbg.core import WithoutBGOpenSource
11
+ from huggingface_hub import hf_hub_download
12
+ from pathlib import Path
13
+ import shutil
14
 
15
  # Configure logging
16
  logging.basicConfig(level=logging.INFO)
 
19
  app = Flask(__name__)
20
  CORS(app)
21
 
22
+ # Model directory
23
+ MODEL_DIR = Path("/app/models")
24
+ MODEL_DIR.mkdir(parents=True, exist_ok=True)
25
+
26
+ def _ensure_model_file(filename: str) -> Path:
27
+ """Download model file from HuggingFace if not exists"""
28
+ target = MODEL_DIR / filename
29
+ if target.exists():
30
+ return target
31
+ logger.info(f"πŸ“₯ Downloading model file: {filename}")
32
+ downloaded = Path(hf_hub_download(repo_id="withoutbg/focus", filename=filename))
33
+ shutil.copy2(downloaded, target)
34
+ logger.info(f"βœ… Model file downloaded: {filename}")
35
+ return target
36
+
37
+ def _create_model() -> WithoutBGOpenSource:
38
+ """Create WithoutBG model instance"""
39
+ logger.info("πŸš€ Creating WithoutBG model...")
40
+ return WithoutBGOpenSource(
41
+ depth_model_path=_ensure_model_file("depth_anything_v2_vits_slim.onnx"),
42
+ isnet_model_path=_ensure_model_file("isnet.onnx"),
43
+ matting_model_path=_ensure_model_file("focus_matting_1.0.0.onnx"),
44
+ refiner_model_path=_ensure_model_file("focus_refiner_1.0.0.onnx"),
45
+ )
46
+
47
  # Initialize the model once at startup
48
  try:
49
  logger.info("πŸš€ Loading withoutBG model...")
50
+ model = _create_model()
51
  logger.info("βœ… Model loaded successfully!")
52
  except Exception as e:
53
  logger.error(f"❌ Failed to load model: {e}")
 
100
 
101
  # Open image
102
  img = Image.open(image_data)
103
+ logger.info(f"πŸ–ΌοΈ Image loaded: {img.size}, mode: {img.mode}")
104
 
105
+ # Remove background using withoutBG (Qiita article method)
106
+ logger.info("πŸ”„ Removing background with WithoutBGOpenSource...")
107
  result = model.remove_background(img)
108
+ logger.info(f"βœ… Background removed! Result mode: {result.mode}, Size: {result.size}")
109
 
110
  # Convert to RGBA first if not already
111
  if result.mode != 'RGBA':
 
138
 
139
  except Exception as e:
140
  logger.error(f"❌ Error: {e}")
141
+ import traceback
142
+ traceback.print_exc()
143
  return jsonify({
144
  'success': False,
145
  'error': str(e)