anujakkulkarni commited on
Commit
efec4b6
·
verified ·
1 Parent(s): 875e896

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -80
app.py CHANGED
@@ -32,86 +32,92 @@ def home():
32
 
33
  @app.route("/analyze", methods=["POST"])
34
  def analyze():
35
- if "file" not in request.files:
36
- return jsonify({"success": False, "analysis": []}), 400
37
-
38
- file = request.files["file"]
39
- file_bytes = np.frombuffer(file.read(), np.uint8)
40
- img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
41
- if img is None:
42
- return jsonify({"success": False, "error": "Invalid image"}), 400
43
-
44
- img_h, img_w = img.shape[:2]
45
-
46
- # -------------------- FACE DETECTION --------------------
47
- rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
48
- result = face_mesh.process(rgb_img)
49
-
50
- face_polygon = None
51
- face_area = 0
52
-
53
- if result.multi_face_landmarks:
54
- for landmarks in result.multi_face_landmarks:
55
- points = np.array([
56
- [int(lm.x * img_w), int(lm.y * img_h)]
57
- for lm in landmarks.landmark
58
- ])
59
- hull = cv2.convexHull(points)
60
- face_area = cv2.contourArea(hull)
61
- face_polygon = Polygon(hull.reshape(-1, 2))
62
- break # only process the first face
63
- else:
64
- return jsonify({"success": False, "error": "No face detected"}), 400
65
-
66
- # -------------------- RUN ALL MODELS --------------------
67
- all_percentages = {}
68
-
69
- for model_name, model in models.items():
70
- # Confidence per model
71
- conf = 0.03 if model_name == "newpig" else default_conf_threshold
72
-
73
- results = model(img, conf=conf, imgsz=imgsz)
74
- boxes_xy = results[0].boxes.xyxy.cpu().numpy()
75
- boxes_cls = results[0].boxes.cls.cpu().numpy().astype(int)
76
-
77
- class_polygons = defaultdict(list)
78
-
79
- for i, cls_id in enumerate(boxes_cls):
80
- cls_name = model.names.get(cls_id, str(cls_id))
81
-
82
- # Skip pores from newpig
83
- if model_name == "newpig" and cls_name.lower() == "pores":
84
- continue
85
-
86
- x1, y1, x2, y2 = boxes_xy[i].astype(int)
87
- det_poly = shapely_box(x1, y1, x2, y2)
88
- if face_polygon.intersects(det_poly):
89
- intersection = det_poly.intersection(face_polygon)
90
- if intersection.area > 0:
91
- class_polygons[cls_id].append(intersection)
92
-
93
- # Pre-fill with 0 for all classes
94
- skin_percentages = {
95
- name: 0.0 for name in model.names.values()
96
- }
97
-
98
- # Remove pores from newpig
99
- if model_name == "newpig" and "pores" in skin_percentages:
100
- skin_percentages.pop("pores")
101
-
102
- # Fill detected percentages
103
- for cls_id, polys in class_polygons.items():
104
- union_poly = unary_union(polys)
105
- pixels = union_poly.area
106
- percentage = (pixels / face_area) * 100 if face_area > 0 else 0.0
107
- cls_name = model.names.get(cls_id, str(cls_id))
108
- if model_name == "newpig" and cls_name.lower() == "pores":
109
- continue
110
- skin_percentages[cls_name] = round(percentage, 2)
111
-
112
- all_percentages[model_name] = skin_percentages
113
-
114
- return jsonify({"success": True, "percentages": all_percentages})
 
 
 
 
 
 
115
 
116
  # -------------------- RUN --------------------
117
  if __name__ == "__main__":
 
32
 
33
  @app.route("/analyze", methods=["POST"])
34
  def analyze():
35
+ try:
36
+ if "file" not in request.files:
37
+ return jsonify({"success": False, "analysis": [], "error": "Server error."}), 400
38
+
39
+ file = request.files["file"]
40
+ file_bytes = np.frombuffer(file.read(), np.uint8)
41
+ img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
42
+ if img is None:
43
+ return jsonify({"success": False, "analysis": [], "error": "Server error."}), 400
44
+
45
+ img_h, img_w = img.shape[:2]
46
+
47
+ # -------------------- FACE DETECTION --------------------
48
+ rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
49
+ result = face_mesh.process(rgb_img)
50
+
51
+ face_polygon = None
52
+ face_area = 0
53
+
54
+ if result.multi_face_landmarks:
55
+ for landmarks in result.multi_face_landmarks:
56
+ points = np.array([
57
+ [int(lm.x * img_w), int(lm.y * img_h)]
58
+ for lm in landmarks.landmark
59
+ ])
60
+ hull = cv2.convexHull(points)
61
+ face_area = cv2.contourArea(hull)
62
+ face_polygon = Polygon(hull.reshape(-1, 2))
63
+ break
64
+ else:
65
+ return jsonify({"success": False, "analysis": [], "error": "Server error."}), 400
66
+
67
+ # -------------------- RUN ALL MODELS --------------------
68
+ combined_percentages = {}
69
+
70
+ for model_name, model in models.items():
71
+ conf = 0.03 if model_name == "newpig" else default_conf_threshold
72
+
73
+ results = model(img, conf=conf, imgsz=imgsz)
74
+ boxes_xy = results[0].boxes.xyxy.cpu().numpy()
75
+ boxes_cls = results[0].boxes.cls.cpu().numpy().astype(int)
76
+
77
+ class_polygons = defaultdict(list)
78
+
79
+ for i, cls_id in enumerate(boxes_cls):
80
+ cls_name = model.names.get(cls_id, str(cls_id))
81
+
82
+ # Skip pores from newpig
83
+ if model_name == "newpig" and cls_name.lower() == "pores":
84
+ continue
85
+
86
+ x1, y1, x2, y2 = boxes_xy[i].astype(int)
87
+ det_poly = shapely_box(x1, y1, x2, y2)
88
+ if face_polygon.intersects(det_poly):
89
+ intersection = det_poly.intersection(face_polygon)
90
+ if intersection.area > 0:
91
+ class_polygons[cls_id].append(intersection)
92
+
93
+ # Pre-fill with 0 for all classes
94
+ skin_percentages = {name: 0.0 for name in model.names.values()}
95
+
96
+ if model_name == "newpig" and "pores" in skin_percentages:
97
+ skin_percentages.pop("pores")
98
+
99
+ # Fill detected percentages
100
+ for cls_id, polys in class_polygons.items():
101
+ union_poly = unary_union(polys)
102
+ pixels = union_poly.area
103
+ percentage = (pixels / face_area) * 100 if face_area > 0 else 0.0
104
+ cls_name = model.names.get(cls_id, str(cls_id))
105
+ if model_name == "newpig" and cls_name.lower() == "pores":
106
+ continue
107
+ skin_percentages[cls_name] = round(percentage, 2)
108
+
109
+ combined_percentages.update(skin_percentages)
110
+
111
+ # -------------------- FORMAT INTO ANALYSIS STRING --------------------
112
+ analysis_str = "\n".join([
113
+ f"{cls_name.upper()}: {value}%" for cls_name, value in combined_percentages.items()
114
+ ])
115
+
116
+ return jsonify({"success": True, "analysis": [analysis_str]})
117
+
118
+ except Exception as e:
119
+ return jsonify({"success": False, "analysis": [], "error": "Server error."}), 500
120
+
121
 
122
  # -------------------- RUN --------------------
123
  if __name__ == "__main__":