Spaces:
Paused
Paused
Update app.py
Browse files123 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661674 unmodified lines17217317417517617727 unmodified lines20520620720820921021121221321438 unmodified lines2532542552562572582592602612622632642657 unmodified lines273274275276277278279280281282283284285286287288289290291292293294295296297298299300123 unmodified lines# demo.launch()import torchimport numpy as npimport cv2import jsonimport osimport gradio as grfrom detectron2.detectron2.engine import DefaultPredictorfrom detectron2.detectron2.config import get_cfgfrom detectron2 import model_zooimport torch_utilsimport dnnlibimport requestsimport base64from io import BytesIO# Create output directory if it doesn't existoutput_dir = "key/"os.makedirs(output_dir, exist_ok=True)output_file = os.path.join(output_dir, "keypoints.json")# Load pre-trained Keypoint R-CNN modelcfg = get_cfg()cfg.merge_from_file(model_zoo.get_config_file("COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml"))cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml")cfg.MODEL.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"# Load the predictorpredictor = DefaultPredictor(cfg)# Replace with your actual Ngrok or backend URLNGROK_URL = "https://your-ngrok-url.ngrok.io/measurements" # Change thisdef process_image(image, user_height_cm):# Convert Gradio image input to OpenCV formatimage = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)# Run keypoint detectionoutputs = predictor(image)# Extract keypoints4 unmodified linesreturn "No keypoints detected.", None# Save keypoints to JSONwith open(output_file, "w") as f:json.dump({"keypoints": keypoints}, f, indent=4)27 unmodified linesankle_mid = ((keypoints[L_ANKLE] + keypoints[R_ANKLE]) / 2).tolist()pixel_height = get_distance(keypoints[NOSE], ankle_mid)# Estimated full body height (add approx head length)estimated_full_pixel_height = pixel_height / 0.87 # Since 87% = nose to anklepixels_per_cm = estimated_full_pixel_height / user_height_cm# Waist and shoulder measurementsshoulder_width_px = get_distance(keypoints[L_SHOULDER], keypoints[R_SHOULDER])waist_width_px = get_distance(keypoints[L_HIP], keypoints[R_HIP])38 unmodified lines# Convert image to base64buffered = BytesIO()pil_image = Image.fromarray(image)pil_image.save(buffered, format="JPEG")img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")# Send POST requestresponse = requests.post("https://9dbc-210-212-162-140.ngrok-free.app/upload", # Change thisjson={"imageBase64": img_str,"heightCm": user_height_cm,7 unmodified linesreturn f"Status: {response.status_code}, Message: {response.text}"# Gradio Interfacedef create_interface():with gr.Blocks() as demo:with gr.Row():img_input = gr.Image(type="pil", label="Upload Image")height_input = gr.Number(label="User Height (cm)")with gr.Row():output_measurements = gr.JSON(label="Measurements")output_image = gr.Image(type="pil", label="Keypoint Overlay")save_btn = gr.Button("Save to Database")save_status = gr.Textbox(label="Save Status", interactive=False)img_input.change(fn=process_image, inputs=[img_input, height_input], outputs=[output_measurements, output_image])save_btn.click(fn=save_to_database,inputs=[output_measurements, output_image, height_input],outputs=save_status)return demodemo = create_interface()demo.launch()123 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461474 unmodified lines15215315415515615715827 unmodified lines18618718818919019119219319419519619719819920020120220338 unmodified lines2422432442452462472482492502512522532547 unmodified lines262263264265266267268269270271272273274275276277278279280281282283284285286123 unmodified lines# demo.launch()from PIL import Image # Importing Image from PIL (Pillow)import cv2import numpy as npimport jsonimport base64import requestsfrom io import BytesIO# Function to process the image and calculate measurementsdef process_image(image, user_height_cm):# Check if the user height is validif user_height_cm == 0 or user_height_cm is None:return "User height cannot be zero or None. Please provide a valid height.", None# Convert Gradio image input to OpenCV formatimage = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)# Run keypoint detection (using your predictor)outputs = predictor(image)# Extract keypoints4 unmodified linesreturn "No keypoints detected.", None# Save keypoints to JSONoutput_file = "keypoints.json"with open(output_file, "w") as f:json.dump({"keypoints": keypoints}, f, indent=4)27 unmodified linesankle_mid = ((keypoints[L_ANKLE] + keypoints[R_ANKLE]) / 2).tolist()pixel_height = get_distance(keypoints[NOSE], ankle_mid)# Check if pixel height is non-zero to avoid divide by zero errorif pixel_height == 0:return "Error in calculating pixel height. Please check the input image.", None# Estimated full body height (add approx head length)estimated_full_pixel_height = pixel_height / 0.87 # Since 87% = nose to anklepixels_per_cm = estimated_full_pixel_height / user_height_cm# Ensure pixels_per_cm is valid (non-zero)if pixels_per_cm == 0:return "Error in calculating pixels per cm. Ensure the user height is correct.", None# Waist and shoulder measurementsshoulder_width_px = get_distance(keypoints[L_SHOULDER], keypoints[R_SHOULDER])waist_width_px = get_distance(keypoints[L_HIP], keypoints[R_HIP])38 unmodified lines# Convert image to base64buffered = BytesIO()pil_image = Image.fromarray(image) # Convert to PIL Image from NumPy arraypil_image.save(buffered, format="JPEG")img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")# Send POST request to save measurements and image to the databaseresponse = requests.post("https://9dbc-210-212-162-140.ngrok-free.app/upload", # Replace with your actual URLjson={"imageBase64": img_str,"heightCm": user_height_cm,7 unmodified linesreturn f"Status: {response.status_code}, Message: {response.text}"# Example usage (integrating with your Gradio app)import gradio as gr# Gradio interface setupdef process_and_save(image, user_height_cm):measurements, processed_image = process_image(image, user_height_cm)if measurements:save_message = save_to_database(measurements, processed_image, user_height_cm)return processed_image, measurements, save_messageelse:return None, None, "Error in processing image."# Gradio interface setupiface = gr.Interface(fn=process_and_save,inputs=[gr.Image(type="numpy"), gr.Number(label="User Height (cm)")],outputs=[gr.Image(type="numpy"), gr.JSON(), gr.Textbox()],live=True)iface.launch(share=True)
app.py+43-57