sahadev10 commited on
Commit
3619fee
·
verified ·
1 Parent(s): 9c84dac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +172 -0
app.py CHANGED
@@ -1,3 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import torch
2
  import numpy as np
3
  import cv2
@@ -9,6 +137,10 @@ from detectron2.detectron2.config import get_cfg
9
  from detectron2 import model_zoo
10
  import torch_utils
11
  import dnnlib
 
 
 
 
12
  # Create output directory if it doesn't exist
13
  output_dir = "key/"
14
  os.makedirs(output_dir, exist_ok=True)
@@ -23,6 +155,9 @@ cfg.MODEL.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
23
  # Load the predictor
24
  predictor = DefaultPredictor(cfg)
25
 
 
 
 
26
  def process_image(image, user_height_cm):
27
  # Convert Gradio image input to OpenCV format
28
  image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
@@ -112,6 +247,33 @@ def process_image(image, user_height_cm):
112
 
113
  return measurements, cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  # Gradio Interface
116
  demo = gr.Interface(
117
  fn=process_image,
@@ -121,4 +283,14 @@ demo = gr.Interface(
121
  description="Upload an image, enter your height, and get body measurements based on keypoints.",
122
  )
123
 
 
 
 
 
 
 
 
 
 
 
124
  demo.launch()
 
1
+ # import torch
2
+ # import numpy as np
3
+ # import cv2
4
+ # import json
5
+ # import os
6
+ # import gradio as gr
7
+ # from detectron2.detectron2.engine import DefaultPredictor
8
+ # from detectron2.detectron2.config import get_cfg
9
+ # from detectron2 import model_zoo
10
+ # import torch_utils
11
+ # import dnnlib
12
+ # # Create output directory if it doesn't exist
13
+ # output_dir = "key/"
14
+ # os.makedirs(output_dir, exist_ok=True)
15
+ # output_file = os.path.join(output_dir, "keypoints.json")
16
+
17
+ # # Load pre-trained Keypoint R-CNN model
18
+ # cfg = get_cfg()
19
+ # cfg.merge_from_file(model_zoo.get_config_file("COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml"))
20
+ # cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml")
21
+ # cfg.MODEL.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
22
+
23
+ # # Load the predictor
24
+ # predictor = DefaultPredictor(cfg)
25
+
26
+ # def process_image(image, user_height_cm):
27
+ # # Convert Gradio image input to OpenCV format
28
+ # image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
29
+
30
+ # # Run keypoint detection
31
+ # outputs = predictor(image)
32
+
33
+ # # Extract keypoints
34
+ # instances = outputs["instances"]
35
+ # keypoints = instances.pred_keypoints.cpu().numpy().tolist() if instances.has("pred_keypoints") else None
36
+
37
+ # if not keypoints:
38
+ # return "No keypoints detected.", None
39
+
40
+ # # Save keypoints to JSON
41
+ # with open(output_file, "w") as f:
42
+ # json.dump({"keypoints": keypoints}, f, indent=4)
43
+
44
+ # keypoints = np.array(keypoints[0])[:, :2] # Extract (x, y) coordinates
45
+
46
+ # # COCO format indices
47
+ # NOSE, L_SHOULDER, R_SHOULDER = 0, 5, 6
48
+ # L_ELBOW, R_ELBOW = 7, 8
49
+ # L_WRIST, R_WRIST = 9, 10
50
+ # L_HIP, R_HIP = 11, 12
51
+ # L_ANKLE, R_ANKLE = 15, 16
52
+
53
+ # # Define Keypoint Pairs for Drawing Lines (COCO Format)
54
+ # skeleton = [(5, 6), (5, 11), (6, 12), (11, 12)]
55
+
56
+ # # Draw Keypoints
57
+ # for x, y in keypoints:
58
+ # cv2.circle(image, (int(x), int(y)), 5, (0, 255, 0), -1)
59
+
60
+ # # Draw Skeleton
61
+ # for pt1, pt2 in skeleton:
62
+ # x1, y1 = map(int, keypoints[pt1])
63
+ # x2, y2 = map(int, keypoints[pt2])
64
+ # cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
65
+
66
+ # # Function to calculate Euclidean distance
67
+ # def get_distance(p1, p2):
68
+ # return np.linalg.norm(np.array(p1) - np.array(p2))
69
+
70
+ # # Calculate full height (consider head length)
71
+ # ankle_mid = ((keypoints[L_ANKLE] + keypoints[R_ANKLE]) / 2).tolist()
72
+ # pixel_height = get_distance(keypoints[NOSE], ankle_mid)
73
+
74
+ # # Estimated full body height (add approx head length)
75
+ # estimated_full_pixel_height = pixel_height / 0.87 # Since 87% = nose to ankle
76
+ # pixels_per_cm = estimated_full_pixel_height / user_height_cm
77
+
78
+ # # Waist and shoulder measurements
79
+ # shoulder_width_px = get_distance(keypoints[L_SHOULDER], keypoints[R_SHOULDER])
80
+ # waist_width_px = get_distance(keypoints[L_HIP], keypoints[R_HIP])
81
+
82
+ # # Convert to cm
83
+ # shoulder_width_cm = shoulder_width_px / pixels_per_cm
84
+ # waist_width_cm = waist_width_px / pixels_per_cm
85
+
86
+ # # Torso Length (Neck to Pelvis)
87
+ # pelvis = ((keypoints[L_HIP] + keypoints[R_HIP]) / 2).tolist()
88
+ # neck = ((keypoints[L_SHOULDER] + keypoints[R_SHOULDER]) / 2).tolist()
89
+ # torso_length_px = get_distance(neck, pelvis)
90
+ # torso_length_cm = torso_length_px / pixels_per_cm
91
+
92
+ # # Arm Length (Shoulder to Wrist)
93
+ # arm_length_px = get_distance(keypoints[L_SHOULDER], keypoints[L_WRIST])
94
+ # arm_length_cm = arm_length_px / pixels_per_cm
95
+
96
+ # # Calculate waist and hip circumference (Ellipse approximation)
97
+ # # Waist circumference ≈ π × (waist_width / 2) × 2
98
+ # waist_circumference = np.pi * waist_width_cm
99
+ # hip_circumference = waist_circumference / 0.75 # Assuming hip is slightly bigger than waist
100
+
101
+ # # Improved body measurement calculation
102
+ # def calculate_body_measurements(waist_circumference, hip_circumference, shoulder_width_cm, torso_length_cm, arm_length_cm):
103
+ # return {
104
+ # "Waist Circumference (cm)": round(waist_circumference, 2),
105
+ # "Hip Circumference (cm)": round(hip_circumference, 2),
106
+ # "Shoulder Width (cm)": round(shoulder_width_cm, 2),
107
+ # "Torso Length (Neck to Pelvis, cm)": round(torso_length_cm, 2),
108
+ # "Full Arm Length (Shoulder to Wrist, cm)": round(arm_length_cm, 2),
109
+ # }
110
+
111
+ # measurements = calculate_body_measurements(waist_circumference, hip_circumference, shoulder_width_cm, torso_length_cm, arm_length_cm)
112
+
113
+ # return measurements, cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
114
+
115
+ # # Gradio Interface
116
+ # demo = gr.Interface(
117
+ # fn=process_image,
118
+ # inputs=[gr.Image(type="pil"), gr.Number(label="User Height (cm)")],
119
+ # outputs=[gr.JSON(label="Measurements"), gr.Image(type="pil", label="Keypoint Overlay")],
120
+ # title="Keypoint Measurement Extractor",
121
+ # description="Upload an image, enter your height, and get body measurements based on keypoints.",
122
+ # )
123
+
124
+ # demo.launch()
125
+
126
+
127
+
128
+
129
  import torch
130
  import numpy as np
131
  import cv2
 
137
  from detectron2 import model_zoo
138
  import torch_utils
139
  import dnnlib
140
+ import requests
141
+ import base64
142
+ from io import BytesIO
143
+
144
  # Create output directory if it doesn't exist
145
  output_dir = "key/"
146
  os.makedirs(output_dir, exist_ok=True)
 
155
  # Load the predictor
156
  predictor = DefaultPredictor(cfg)
157
 
158
+ # Replace with your actual Ngrok or backend URL
159
+ NGROK_URL = " https://9dbc-210-212-162-140.ngrok-free.app/upload" # Change this
160
+
161
  def process_image(image, user_height_cm):
162
  # Convert Gradio image input to OpenCV format
163
  image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
 
247
 
248
  return measurements, cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
249
 
250
+ # Save to database function
251
+ def save_to_database(measurements, image, user_height_cm):
252
+ if measurements is None or image is None:
253
+ return "No data to save."
254
+
255
+ # Convert image to base64
256
+ buffered = BytesIO()
257
+ pil_image = Image.fromarray(image)
258
+ pil_image.save(buffered, format="JPEG")
259
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
260
+
261
+ # Send POST request
262
+ response = requests.post(
263
+ "https://your-ngrok-url.ngrok.io/measurements", # Change this
264
+ json={
265
+ "imageBase64": img_str,
266
+ "heightCm": user_height_cm,
267
+ "waistCircumferenceCm": measurements["Waist Circumference (cm)"],
268
+ "shoulderwidth": measurements["Shoulder Width (cm)"],
269
+ "hipcircumference": measurements["Hip Circumference (cm)"],
270
+ "torsolength": measurements["Torso Length (Neck to Pelvis, cm)"],
271
+ "fullarmlength": measurements["Full Arm Length (Shoulder to Wrist, cm)"]
272
+ }
273
+ )
274
+
275
+ return f"Status: {response.status_code}, Message: {response.text}"
276
+
277
  # Gradio Interface
278
  demo = gr.Interface(
279
  fn=process_image,
 
283
  description="Upload an image, enter your height, and get body measurements based on keypoints.",
284
  )
285
 
286
+ # Add Save to Database button functionality
287
+ save_btn = gr.Button("Save to Database")
288
+ save_status = gr.Textbox(label="Save Status", interactive=False)
289
+
290
+ save_btn.click(
291
+ fn=save_to_database,
292
+ inputs=[demo.outputs[0], demo.outputs[1], gr.Number(label="User Height (cm)")],
293
+ outputs=save_status
294
+ )
295
+
296
  demo.launch()