Omarelrayes commited on
Commit
b837d75
Β·
verified Β·
1 Parent(s): 8b1f705

Update app/services/segmenter.py

Browse files
Files changed (1) hide show
  1. app/services/segmenter.py +46 -80
app/services/segmenter.py CHANGED
@@ -1,88 +1,54 @@
 
1
  import numpy as np
2
- from datetime import datetime
3
- from typing import Dict, Any
4
- from PIL import Image
5
- import io
6
  import tensorflow as tf
 
7
 
8
- from app.configs import get_segmentation_model, SEGMENTS_DIR
9
- from app.storage import update_history
10
  from app.core.preprocessing import preprocess_image
11
 
12
 
13
- async def run_segmentation(request_id: str, image_filename: str, image_path: str):
14
- """Run segmentation on image (background task)"""
15
- print(f"🎨 SEGMENTING {request_id}.......")
16
-
17
- seg_result: Dict[str, Any] = {
18
- "request_id": request_id,
19
- "image_filename": image_filename,
20
- "timestamp": datetime.now().isoformat(),
21
- "detections": []
22
- }
23
-
24
- # Get model
25
  model = get_segmentation_model()
26
-
27
  if model is None:
28
- seg_result["error"] = "Segmentation model not loaded"
29
- seg_path = None
30
- else:
31
- try:
32
- # Load image
33
- with open(image_path, 'rb') as f:
34
- img_bytes = f.read()
35
-
36
- # Preprocess for segmentation (256x256)
37
- img_array = preprocess_image(img_bytes, target_size=(256, 256))
38
-
39
- # πŸ”₯ Use SavedModel signature
40
- result = model(tf.constant(img_array))
41
-
42
- if isinstance(result, dict):
43
- masks = list(result.values())[0].numpy()
44
- else:
45
- masks = result.numpy()
46
-
47
- # Post-process mask
48
- mask = masks[0] # Remove batch dimension
49
-
50
- if mask.ndim == 3:
51
- mask = mask[:, :, 0] # Take first channel
52
-
53
- # Normalize to 0-255
54
- mask = (mask * 255).astype(np.uint8)
55
-
56
- # πŸ”₯ Save mask as PNG image
57
- mask_image = Image.fromarray(mask)
58
-
59
- # Resize to original image size if needed
60
- original_image = Image.open(io.BytesIO(img_bytes))
61
- original_size = original_image.size
62
- mask_image = mask_image.resize(original_size)
63
-
64
- # Save to segments directory
65
- seg_filename = f"{request_id}_mask.png"
66
- seg_path = str(SEGMENTS_DIR / seg_filename)
67
- mask_image.save(seg_path, format='PNG')
68
-
69
- seg_result.update({
70
- "model_used": True,
71
- "masks_shape": list(masks.shape),
72
- "max_confidence": float(np.max(masks)),
73
- "mask_path": seg_path
74
- })
75
-
76
- print(f"βœ… SEGMENTATION DONE {request_id}: {seg_path}")
77
-
78
- except Exception as e:
79
- seg_result["error"] = str(e)
80
- seg_path = None
81
- print(f"❌ SEGMENTATION FAILED {request_id}: {e}")
82
-
83
- # Update history
84
- update_history(
85
- request_id,
86
- segmentation_path=seg_path,
87
- status="segmented" if seg_path else "segmentation_failed"
88
- )
 
1
+ # app/services/segmenter.py
2
  import numpy as np
 
 
 
 
3
  import tensorflow as tf
4
+ from typing import Dict, Any
5
 
6
+ from app.configs import get_segmentation_model
 
7
  from app.core.preprocessing import preprocess_image
8
 
9
 
10
+ def segment_image(image_bytes: bytes) -> Dict[str, Any]:
11
+ """
12
+ Run segmentation on image bytes.
13
+
14
+ Returns:
15
+ Dict with keys: status, masks_shape, max_confidence, error (optional)
16
+ """
 
 
 
 
 
17
  model = get_segmentation_model()
18
+
19
  if model is None:
20
+ return {
21
+ "status": "failed",
22
+ "error": "Segmentation model not loaded",
23
+ }
24
+
25
+ try:
26
+ # Preprocess for segmentation (256x256)
27
+ img_array = preprocess_image(image_bytes, target_size=(256, 256))
28
+
29
+ # πŸ”₯ Call SavedModel signature
30
+ result = model(tf.constant(img_array))
31
+
32
+ if isinstance(result, dict):
33
+ masks = list(result.values())[0].numpy()
34
+ else:
35
+ masks = result.numpy()
36
+
37
+ # Extract stats
38
+ max_confidence = float(np.max(masks))
39
+ masks_shape = list(masks.shape)
40
+
41
+ print(f"🎨 SEGMENTATION: shape={masks_shape}, max_conf={max_confidence:.3f}")
42
+
43
+ return {
44
+ "status": "completed",
45
+ "masks_shape": masks_shape,
46
+ "max_confidence": max_confidence,
47
+ }
48
+
49
+ except Exception as e:
50
+ print(f"❌ SEGMENTATION FAILED: {e}")
51
+ return {
52
+ "status": "failed",
53
+ "error": str(e),
54
+ }