Skip to content

Commit 3643af6

Browse files
committed
fix image not being masked and annotated while downloading
1 parent 95740d7 commit 3643af6

File tree

3 files changed

+56
-25
lines changed

3 files changed

+56
-25
lines changed

server/app.py

+53-22
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import json
1515
from PIL import Image, ImageDraw
1616
import os
17+
import traceback
1718
from dotenv import load_dotenv
1819

1920
app = Flask(__name__)
@@ -271,20 +272,25 @@ def download_image_with_annotations():
271272
# Draw polygon with thicker outline
272273
draw.line(scaled_points + [scaled_points[0]], fill=color, width=3) # Change width as desired
273274
elif all(key in region for key in ('x', 'y', 'w', 'h')):
274-
x = float(region['x'][1:-1]) * width # Remove brackets and convert to float
275-
y = float(region['y'][1:-1]) * height
276-
w = float(region['w'][1:-1]) * width
277-
h = float(region['h'][1:-1]) * height
275+
try:
276+
x = float(region['x'][1:-1]) * width if isinstance(region['x'], str) else float(region['x'][0]) * width
277+
y = float(region['y'][1:-1]) * height if isinstance(region['y'], str) else float(region['y'][0]) * height
278+
w = float(region['w'][1:-1]) * width if isinstance(region['w'], str) else float(region['w'][0]) * width
279+
h = float(region['h'][1:-1]) * height if isinstance(region['h'], str) else float(region['h'][0]) * height
280+
except (ValueError, TypeError) as e:
281+
raise ValueError(f"Invalid format in region dimensions: {region}, Error: {e}")
278282
# Draw rectangle with thicker outline
279283
draw.rectangle([x, y, x + w, y + h], outline=color, width=3)
280-
281284
elif all(key in region for key in ('rx', 'ry', 'rw', 'rh')):
282-
rx = float(region['rx'][1:-1]) * width # Remove brackets and convert to float
283-
ry = float(region['ry'][1:-1]) * height
284-
rw = float(region['rw'][1:-1]) * width
285-
rh = float(region['rh'][1:-1]) * height
285+
try:
286+
rx = float(region['rx'][1:-1]) * width if isinstance(region['rx'], str) else float(region['rx'][0]) * width
287+
ry = float(region['ry'][1:-1]) * height if isinstance(region['ry'], str) else float(region['ry'][0]) * height
288+
rw = float(region['rw'][1:-1]) * width if isinstance(region['rw'], str) else float(region['rw'][0]) * width
289+
rh = float(region['rh'][1:-1]) * height if isinstance(region['rh'], str) else float(region['rh'][0]) * height
290+
except (ValueError, TypeError) as e:
291+
raise ValueError(f"Invalid format in region dimensions: {region}, Error: {e}")
286292
# Draw ellipse (circle if rw and rh are equal)
287-
draw.ellipse([rx, ry, rx + rw, ry + rh], outline=color, width=3)
293+
draw.ellipse([rx, ry, rx + rw, ry + rh], outline=color, width=3)
288294

289295

290296

@@ -294,10 +300,20 @@ def download_image_with_annotations():
294300

295301
return send_file(img_byte_arr, mimetype='image/png', as_attachment=True, download_name=image_info.get("image-name"))
296302

303+
except ValueError as ve:
304+
print('ValueError:', ve)
305+
traceback.print_exc()
306+
return jsonify({'error': str(ve)}), 400
307+
except requests.exceptions.RequestException as re:
308+
print('RequestException:', re)
309+
traceback.print_exc()
310+
return jsonify({'error': 'Error fetching image from URL'}), 500
297311
except Exception as e:
298-
print('Error:', e)
312+
print('General error:', e)
313+
traceback.print_exc()
299314
return jsonify({'error': str(e)}), 500
300315

316+
301317
@app.route('/download_image_mask', methods=['POST'])
302318
@cross_origin(origin=client_url, headers=['Content-Type'])
303319
def download_image_mask():
@@ -336,28 +352,43 @@ def download_image_mask():
336352
scaled_points = [(int(x * width), int(y * height)) for x, y in points]
337353
draw.polygon(scaled_points, outline=color, fill=color)
338354
elif all(key in region for key in ('x', 'y', 'w', 'h')):
339-
x = float(region['x'][1:-1]) * width # Remove brackets and convert to float
340-
y = float(region['y'][1:-1]) * height
341-
w = float(region['w'][1:-1]) * width
342-
h = float(region['h'][1:-1]) * height
355+
try:
356+
x = float(region['x'][1:-1]) * width if isinstance(region['x'], str) else float(region['x'][0]) * width
357+
y = float(region['y'][1:-1]) * height if isinstance(region['y'], str) else float(region['y'][0]) * height
358+
w = float(region['w'][1:-1]) * width if isinstance(region['w'], str) else float(region['w'][0]) * width
359+
h = float(region['h'][1:-1]) * height if isinstance(region['h'], str) else float(region['h'][0]) * height
360+
except (ValueError, TypeError) as e:
361+
raise ValueError(f"Invalid format in region dimensions: {region}, Error: {e}")
343362
# Draw rectangle for bounding box
344363
draw.rectangle([x, y, x + w, y + h], outline=color, fill=color)
345364
elif all(key in region for key in ('rx', 'ry', 'rw', 'rh')):
346-
rx = float(region['rx'][1:-1]) * width # Remove brackets and convert to float
347-
ry = float(region['ry'][1:-1]) * height
348-
rw = float(region['rw'][1:-1]) * width
349-
rh = float(region['rh'][1:-1]) * height
365+
try:
366+
rx = float(region['rx'][1:-1]) * width if isinstance(region['rx'], str) else float(region['rx'][0]) * width
367+
ry = float(region['ry'][1:-1]) * height if isinstance(region['ry'], str) else float(region['ry'][0]) * height
368+
rw = float(region['rw'][1:-1]) * width if isinstance(region['rw'], str) else float(region['rw'][0]) * width
369+
rh = float(region['rh'][1:-1]) * height if isinstance(region['rh'], str) else float(region['rh'][0]) * height
370+
except (ValueError, TypeError) as e:
371+
raise ValueError(f"Invalid format in region dimensions: {region}, Error: {e}")
350372
# Draw ellipse (circle if rw and rh are equal)
351-
draw.ellipse([rx, ry, rx + rw, ry + rh], outline=color, fill=color)
373+
draw.ellipse([rx, ry, rx + rw, ry + rh], outline=color, width=3)
352374

353-
354375
mask_byte_arr = BytesIO()
355376
mask.save(mask_byte_arr, format='PNG')
356377
mask_byte_arr.seek(0)
357378

358379
return send_file(mask_byte_arr, mimetype='image/png', as_attachment=True, download_name=f"mask_{image_info.get('image-name')}")
380+
381+
except ValueError as ve:
382+
print('ValueError:', ve)
383+
traceback.print_exc()
384+
return jsonify({'error': str(ve)}), 400
385+
except requests.exceptions.RequestException as re:
386+
print('RequestException:', re)
387+
traceback.print_exc()
388+
return jsonify({'error': 'Error fetching image from URL'}), 500
359389
except Exception as e:
360-
print('Error:', e)
390+
print('General error:', e)
391+
traceback.print_exc()
361392
return jsonify({'error': str(e)}), 500
362393

363394
@app.route('/imagesInfo', methods=['GET'])

server/db/db_handler.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def regionType(type):
7070
# return regionData
7171

7272
def saveRegionInDB(self, database, idColumn, uid, data, status): # TODO if region then use one or zero changeSatus, remove in their
73-
73+
print(f"Database: {database}")
7474
index = self.findInfoInDb(database, idColumn, uid)
7575

7676
if index is not None: # set -> diff -> list

server/tests/test_app.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,12 @@ def test_download_configuration_no_image_name(self):
8686

8787
def test_download_image_with_annotations_no_image_name(self):
8888
response = self.app.post('/download_image_with_annotations', data=json.dumps({}), content_type='application/json')
89-
self.assertEqual(response.status_code, 500)
89+
self.assertEqual(response.status_code, 400)
9090
self.assertIn(b"'image_name' not found", response.data)
9191

9292
def test_download_image_mask_no_image_name(self):
9393
response = self.app.post('/download_image_mask', data=json.dumps({}), content_type='application/json')
94-
self.assertEqual(response.status_code, 500)
94+
self.assertEqual(response.status_code, 400)
9595
self.assertIn(b"'image_name' not found", response.data)
9696

9797
# def test_get_images_info_no_path(self):

0 commit comments

Comments
 (0)