fixed tabs and spaces
Browse files- handler.py +36 -37
handler.py
CHANGED
@@ -5,40 +5,39 @@ from flask import Flask, Response, request, jsonify
|
|
5 |
from segment_anything import SamPredictor, sam_model_registry
|
6 |
|
7 |
class EndpointHandler():
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
return jsonify(image_embedding)
|
|
|
5 |
from segment_anything import SamPredictor, sam_model_registry
|
6 |
|
7 |
class EndpointHandler():
|
8 |
+
def __init__(self, path=""):
|
9 |
+
# Preload all the elements you are going to need at inference.
|
10 |
+
model_type = "vit_b"
|
11 |
+
# prefix = "/opt/ml/model"
|
12 |
+
model_path = "tf_model.h5"
|
13 |
+
# model_checkpoint_path = os.path.join(prefix, "sam_vit_h_4b8939.pth")
|
14 |
+
sam = sam_model_registry[model_type](checkpoint=model_path)
|
15 |
+
self.predictor = SamPredictor(sam)
|
16 |
+
|
17 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
18 |
+
"""
|
19 |
+
data args:
|
20 |
+
inputs (:obj: `str` | `PIL.Image` | `np.array`)
|
21 |
+
kwargs
|
22 |
+
Return:
|
23 |
+
A :obj:`list` | `dict`: will be serialized and returned
|
24 |
+
"""
|
25 |
+
|
26 |
+
inputs = data.pop("inputs", data)
|
27 |
+
image_url = inputs.pop("imageUrl", None)
|
28 |
+
|
29 |
+
if not image_url:
|
30 |
+
return jsonify({"error": "image_url not provided"}), 400
|
31 |
+
|
32 |
+
try:
|
33 |
+
response = requests.get(image_url)
|
34 |
+
response.raise_for_status()
|
35 |
+
image = response.content
|
36 |
+
except requests.RequestException as e:
|
37 |
+
return jsonify({"error": f"Error downloading image: {str(e)}"}), 500
|
38 |
+
|
39 |
+
self.predictor.set_image(image)
|
40 |
+
|
41 |
+
image_embedding = self.predictor.get_image_embedding().cpu().numpy().tolist()
|
42 |
+
|
43 |
+
return jsonify(image_embedding)
|
|