sourav520 commited on
Commit
a913f61
·
verified ·
1 Parent(s): f485a55

Upload 4 files

Browse files
Files changed (3) hide show
  1. Dockerfile +1 -0
  2. main.py +26 -9
  3. requirements.txt +3 -0
Dockerfile CHANGED
@@ -18,6 +18,7 @@ RUN pip install --no-cache-dir --upgrade pip && \
18
  pip install --no-cache-dir -r requirements.txt
19
 
20
  COPY --chown=user main.py .
 
21
 
22
  RUN mkdir -p uploads outputs
23
 
 
18
  pip install --no-cache-dir -r requirements.txt
19
 
20
  COPY --chown=user main.py .
21
+ COPY --chown=user u2net.onnx .
22
 
23
  RUN mkdir -p uploads outputs
24
 
main.py CHANGED
@@ -27,6 +27,12 @@ try:
27
  except ImportError:
28
  BG_AVAILABLE = False
29
 
 
 
 
 
 
 
30
  basedir = os.path.abspath(os.path.dirname(__file__))
31
  load_dotenv(os.path.join(basedir, '.env'))
32
 
@@ -47,7 +53,9 @@ if BG_AVAILABLE:
47
  model_path = os.path.join(basedir, 'u2net.onnx')
48
  if os.path.exists(model_path):
49
  session = ort.InferenceSession(model_path)
50
- logger.info("ONNX model loaded")
 
 
51
  except Exception as e:
52
  logger.warning(f"ONNX not loaded: {e}")
53
 
@@ -137,30 +145,39 @@ def index():
137
  def health():
138
  return jsonify({
139
  'status': 'healthy',
140
- 'background_removal': BG_AVAILABLE and session is not None
 
141
  })
142
 
143
 
144
  @app.route('/remove', methods=['POST'])
145
  def remove():
146
  if not BG_AVAILABLE or session is None:
147
- return jsonify({'error': 'Background removal not available'}), 503
148
  try:
149
  if 'image' not in request.files:
150
  return jsonify({'error': 'No image provided'}), 400
151
- img = Image.open(request.files['image'].stream)
152
  orig_size = img.size
153
- inp = img.convert('RGB').resize((320, 320))
154
- arr = np.expand_dims(np.transpose(np.array(inp).astype(np.float32) / 255.0, (2, 0, 1)), 0)
 
 
 
155
  mask = session.run(None, {'input.1': arr})[0][0].squeeze()
156
- mask = (mask - mask.min()) / (mask.max() - mask.min())
157
- mask = Image.fromarray((mask * 255).astype(np.uint8)).resize(orig_size)
 
 
158
  out = img.convert('RGBA')
159
- out.putdata([(r, g, b, m) for (r, g, b, a), m in zip(out.getdata(), mask.getdata())])
 
160
  buf = io.BytesIO()
161
  out.save(buf, format='PNG')
 
162
  return jsonify({'image': 'data:image/png;base64,' + base64.b64encode(buf.getvalue()).decode()})
163
  except Exception as e:
 
164
  return jsonify({'error': str(e)}), 500
165
 
166
 
 
27
  except ImportError:
28
  BG_AVAILABLE = False
29
 
30
+ try:
31
+ from PIL import Image as PILImage
32
+ PIL_AVAILABLE = True
33
+ except ImportError:
34
+ PIL_AVAILABLE = False
35
+
36
  basedir = os.path.abspath(os.path.dirname(__file__))
37
  load_dotenv(os.path.join(basedir, '.env'))
38
 
 
53
  model_path = os.path.join(basedir, 'u2net.onnx')
54
  if os.path.exists(model_path):
55
  session = ort.InferenceSession(model_path)
56
+ logger.info("ONNX u2net model loaded")
57
+ else:
58
+ logger.warning(f"u2net.onnx not found at {model_path}")
59
  except Exception as e:
60
  logger.warning(f"ONNX not loaded: {e}")
61
 
 
145
  def health():
146
  return jsonify({
147
  'status': 'healthy',
148
+ 'background_removal': BG_AVAILABLE and session is not None,
149
+ 'u2net_model': session is not None
150
  })
151
 
152
 
153
  @app.route('/remove', methods=['POST'])
154
  def remove():
155
  if not BG_AVAILABLE or session is None:
156
+ return jsonify({'error': 'Background removal not available - u2net.onnx model missing'}), 503
157
  try:
158
  if 'image' not in request.files:
159
  return jsonify({'error': 'No image provided'}), 400
160
+ img = Image.open(request.files['image'].stream).convert('RGB')
161
  orig_size = img.size
162
+ # Preprocess
163
+ resized = img.resize((320, 320))
164
+ arr = np.array(resized).astype(np.float32) / 255.0
165
+ arr = np.expand_dims(np.transpose(arr, (2, 0, 1)), 0)
166
+ # Run inference
167
  mask = session.run(None, {'input.1': arr})[0][0].squeeze()
168
+ # Normalize mask
169
+ mask = (mask - mask.min()) / (mask.max() - mask.min() + 1e-8)
170
+ mask = Image.fromarray((mask * 255).astype(np.uint8)).resize(orig_size, Image.LANCZOS)
171
+ # Apply mask as alpha channel
172
  out = img.convert('RGBA')
173
+ r_ch, g_ch, b_ch, _ = out.split()
174
+ out = Image.merge('RGBA', (r_ch, g_ch, b_ch, mask))
175
  buf = io.BytesIO()
176
  out.save(buf, format='PNG')
177
+ buf.seek(0)
178
  return jsonify({'image': 'data:image/png;base64,' + base64.b64encode(buf.getvalue()).decode()})
179
  except Exception as e:
180
+ logger.error(f"Remove error: {e}", exc_info=True)
181
  return jsonify({'error': str(e)}), 500
182
 
183
 
requirements.txt CHANGED
@@ -8,3 +8,6 @@ PyMuPDF==1.24.5
8
  python-docx==1.1.2
9
  openpyxl==3.1.5
10
  lxml==5.2.2
 
 
 
 
8
  python-docx==1.1.2
9
  openpyxl==3.1.5
10
  lxml==5.2.2
11
+ pillow==10.4.0
12
+ onnxruntime==1.18.1
13
+ numpy==1.26.4