Spaces:
Sleeping
Sleeping
update the model to new version
Browse files
app.py
CHANGED
|
@@ -1,47 +1,78 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import CLIPProcessor, CLIPModel
|
| 3 |
from PIL import Image
|
| 4 |
-
|
| 5 |
import base64
|
| 6 |
import json
|
| 7 |
import requests
|
| 8 |
from io import BytesIO
|
| 9 |
-
from openai import OpenAI
|
| 10 |
import os
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
"
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
bmi_classes_model2 = [
|
| 25 |
-
"MALE",
|
| 26 |
-
"FEMALE"
|
| 27 |
-
]
|
| 28 |
-
|
| 29 |
-
def chatgpt_openai(height='', gender='', bmi_class_model1=''):
|
| 30 |
-
os.environ["OPENAI_API_KEY"] = "sk-proj-M9n0SkRnVKXIJDk67ci3T3BlbkFJt2VaN0rYZwaTz9xzHvVD"
|
| 31 |
-
client = OpenAI()
|
| 32 |
-
content = f"""i have a {gender} who is {height} and classified as {bmi_class_model1}.
|
| 33 |
-
on average, using USA stats, what is the average BMI for someone like this.
|
| 34 |
-
|
| 35 |
-
Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation.
|
| 36 |
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
{{
|
| 41 |
-
"
|
|
|
|
|
|
|
|
|
|
| 42 |
}}"""
|
| 43 |
-
|
| 44 |
-
|
| 45 |
model="gpt-4o",
|
| 46 |
messages=[
|
| 47 |
{
|
|
@@ -53,95 +84,86 @@ def chatgpt_openai(height='', gender='', bmi_class_model1=''):
|
|
| 53 |
"content": content
|
| 54 |
}
|
| 55 |
]
|
| 56 |
-
)
|
| 57 |
-
json_object = json.loads(completion.choices[0].message.content)
|
| 58 |
return json_object
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
"underweight (x < 18.5 bmi)": [16.0, 18.5],
|
| 65 |
-
"normal weight (18.5 < x < 25 bmi)": [18.5, 25],
|
| 66 |
-
"overweight (25 bmi < x < 30)": [25, 30],
|
| 67 |
-
"obesity (x > 30 bmi)": [30, 40]
|
| 68 |
}
|
| 69 |
-
|
| 70 |
-
# Determine the specific BMI range based on the output from MODEL 4
|
| 71 |
-
if "BMI >" in bmi_range:
|
| 72 |
-
value = float(bmi_range.split('>')[1].strip())
|
| 73 |
-
lower_bound, upper_bound = bmi_classes_model5[predicted_bmi_class.lower()]
|
| 74 |
-
return [f"BMI = {i}" for i in range(int(value) + 1, int(upper_bound) + 1)]
|
| 75 |
-
elif "BMI <=" in bmi_range:
|
| 76 |
-
value = float(bmi_range.split('<=')[1].strip())
|
| 77 |
-
lower_bound, upper_bound = bmi_classes_model5[predicted_bmi_class.lower()]
|
| 78 |
-
return [f"BMI = {i}" for i in range(int(lower_bound), int(value) + 1)]
|
| 79 |
-
else:
|
| 80 |
-
return []
|
| 81 |
|
|
|
|
|
|
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
outputs_model5 = model(**inputs_model5)
|
| 114 |
-
probs_model5 = outputs_model5.logits_per_image.softmax(dim=1)
|
| 115 |
-
|
| 116 |
-
max_prob_index_model5 = probs_model5.argmax().item()
|
| 117 |
-
predicted_bmi_class5 = get_bmi_class_model5[max_prob_index_model5]
|
| 118 |
-
|
| 119 |
-
bmi_prediction = float(predicted_bmi_class5.split('=')[1].strip())
|
| 120 |
|
| 121 |
-
# Calculate weight using user-provided height
|
| 122 |
-
predicted_weight = calculate_weight(bmi_prediction, height_in_inches)
|
| 123 |
-
|
| 124 |
result = {
|
| 125 |
-
"weightCategory": f"{
|
| 126 |
-
"bmiPrediction": f"{bmi_prediction:.2f}",
|
| 127 |
"height": str(height_in_inches),
|
| 128 |
-
"
|
|
|
|
| 129 |
}
|
| 130 |
|
| 131 |
return result
|
| 132 |
-
|
| 133 |
-
def
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
| 138 |
|
| 139 |
# Create Gradio interface with updated input components
|
| 140 |
interface = gr.Interface(
|
| 141 |
fn=predict_bmi,
|
| 142 |
inputs=[
|
| 143 |
gr.Image(type="pil"),
|
| 144 |
-
gr.Number(label="Height in inches")
|
|
|
|
| 145 |
],
|
| 146 |
outputs="json",
|
| 147 |
title="BMI Prediction",
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import CLIPProcessor, CLIPModel
|
| 3 |
from PIL import Image
|
|
|
|
| 4 |
import base64
|
| 5 |
import json
|
| 6 |
import requests
|
| 7 |
from io import BytesIO
|
|
|
|
| 8 |
import os
|
| 9 |
|
| 10 |
+
# Constants
|
| 11 |
+
API_URL = "https://api-inference.huggingface.co/models/openai/clip-vit-large-patch14"
|
| 12 |
+
|
| 13 |
+
# Fetch the Hugging Face API token from environment variables
|
| 14 |
+
HF_API_TOKEN = os.getenv("HF_API_TOKEN")
|
| 15 |
+
|
| 16 |
+
if HF_API_TOKEN is None:
|
| 17 |
+
raise ValueError("Hugging Face API token is not set. Please add it as an environment variable.")
|
| 18 |
+
|
| 19 |
+
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
| 20 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
# BMI model classes
|
| 23 |
+
model1_classes = ["underweight (x < 18.5 BMI)", "normal weight (18.5 < x < 25 BMI)", "overweight (25 BMI < x < 30)", "obesity (x > 30 BMI)"]
|
| 24 |
+
|
| 25 |
+
model2_classes = ["MALE", "FEMALE"]
|
| 26 |
+
|
| 27 |
+
# Define the default BMI classes and ranges
|
| 28 |
+
bmi_classes_ranges = {
|
| 29 |
+
"underweight (x < 18.5 bmi)": [16.0, 18.5],
|
| 30 |
+
"normal weight (18.5 < x < 25 bmi)": [18.5, 25],
|
| 31 |
+
"overweight (25 bmi < x < 30)": [25, 30],
|
| 32 |
+
"obesity (x > 30 bmi)": [30, 40]
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
# Function to convert image to base64
|
| 36 |
+
def encode_image_to_base64(image):
|
| 37 |
+
buffered = BytesIO()
|
| 38 |
+
image.save(buffered, format="JPEG")
|
| 39 |
+
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 40 |
+
return img_str
|
| 41 |
+
|
| 42 |
+
# Function to call the Hugging Face API
|
| 43 |
+
def query(data):
|
| 44 |
+
payload = {
|
| 45 |
+
"parameters": data["parameters"],
|
| 46 |
+
"inputs": data["image_base64"]
|
| 47 |
+
}
|
| 48 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
| 49 |
+
return response.json()
|
| 50 |
+
|
| 51 |
+
def get_bmi_classes_range(predicted_bmi_class, bmi_range):
|
| 52 |
+
# Determine the specific BMI range based on the output
|
| 53 |
+
lower_bound, upper_bound = bmi_classes_ranges[predicted_bmi_class.lower()]
|
| 54 |
+
if "BMI <=" in bmi_range:
|
| 55 |
+
value = float(bmi_range.split('<=')[1].strip())
|
| 56 |
+
return [lower_bound, value]
|
| 57 |
+
elif "BMI >" in bmi_range:
|
| 58 |
+
value = float(bmi_range.split('>')[1].strip())
|
| 59 |
+
return [value, upper_bound]
|
| 60 |
+
else:
|
| 61 |
+
return []
|
| 62 |
|
| 63 |
+
def chatgpt_openai(height='', gender='', bmi_class_model1='', age=''):
|
| 64 |
+
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
|
| 65 |
+
content = f"""I have a person {gender} who is {height} and classified as {bmi_class_model1}.
|
| 66 |
+
Can you suggest a reasonable range of BMI values that typically represent people who are {bmi_class_model1}.
|
| 67 |
+
Output JSON in this format:
|
| 68 |
{{
|
| 69 |
+
"bmi_range": {{
|
| 70 |
+
"min": 24.3,
|
| 71 |
+
"max": 28.9
|
| 72 |
+
}}
|
| 73 |
}}"""
|
| 74 |
+
client = OpenAI()
|
| 75 |
+
completion = client.chat.completions.create(
|
| 76 |
model="gpt-4o",
|
| 77 |
messages=[
|
| 78 |
{
|
|
|
|
| 84 |
"content": content
|
| 85 |
}
|
| 86 |
]
|
| 87 |
+
)
|
| 88 |
+
json_object = json.loads(completion.choices[0].message.content)
|
| 89 |
return json_object
|
| 90 |
|
| 91 |
+
def predict_bmi(image, height_in_inches, age):
|
| 92 |
+
image_base64 = encode_image_to_base64(image)
|
| 93 |
+
|
| 94 |
+
request_payload = {
|
| 95 |
+
"image_base64": image_base64,
|
| 96 |
+
"parameters": {"candidate_labels": model1_classes}
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
# API call to get the model1 output
|
| 100 |
+
output = query(request_payload)
|
| 101 |
+
|
| 102 |
+
# Process the model1 output
|
| 103 |
+
predicted_class = max(output, key=lambda x: x['score'])['label']
|
| 104 |
|
| 105 |
+
request_payload2 = {
|
| 106 |
+
"image_base64": image_base64,
|
| 107 |
+
"parameters": {"candidate_labels": model2_classes}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
# API call to get the model2 output
|
| 111 |
+
output2 = query(request_payload2)
|
| 112 |
|
| 113 |
+
# Process the model2 output
|
| 114 |
+
predicted_class2 = max(output2, key=lambda x: x['score'])['label']
|
| 115 |
+
|
| 116 |
+
bmi_range = bmi_classes_ranges[predicted_class.lower()]
|
| 117 |
+
|
| 118 |
+
if "normal weight" in predicted_class or "overweight" in predicted_class:
|
| 119 |
+
# Calculate the average BMI
|
| 120 |
+
average_bmi = (bmi_range[0] + bmi_range[1]) / 2
|
| 121 |
+
|
| 122 |
+
model3_classes = [f"BMI <= {average_bmi:.1f}", f"BMI > {average_bmi:.1f}"]
|
| 123 |
+
|
| 124 |
+
request_payload3 = {
|
| 125 |
+
"image_base64": image_base64,
|
| 126 |
+
"parameters": {"candidate_labels": model3_classes}
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
# API call to get the model3 output
|
| 130 |
+
output3 = query(request_payload3)
|
| 131 |
+
|
| 132 |
+
# Process the model3 output
|
| 133 |
+
predicted_class3 = max(output3, key=lambda x: x['score'])['label']
|
| 134 |
+
|
| 135 |
+
get_bmi_range = get_bmi_classes_range(predicted_class, predicted_class3)
|
| 136 |
+
else:
|
| 137 |
+
model3_gpt = chatgpt_openai(height_in_inches, predicted_class2, predicted_class, age)
|
| 138 |
+
data = model3_gpt['bmi_range']
|
| 139 |
+
get_bmi_range = [data["min"], data["max"]]
|
| 140 |
+
|
| 141 |
+
weight_min, weight_max = get_weight_range(get_bmi_range[0], get_bmi_range[1], height_in_inches)
|
| 142 |
+
print(f"Predicted weight range: {weight_min:.2f} lbs - {weight_max:.2f} lbs")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
|
|
|
|
|
|
|
|
|
| 144 |
result = {
|
| 145 |
+
"weightCategory": f"{predicted_class}",
|
|
|
|
| 146 |
"height": str(height_in_inches),
|
| 147 |
+
"bmi_range": get_bmi_range,
|
| 148 |
+
"predictedWeightRange": f"{weight_min:.2f} lbs - {weight_max:.2f} lbs"
|
| 149 |
}
|
| 150 |
|
| 151 |
return result
|
| 152 |
+
|
| 153 |
+
def get_weight_range(bmi_min, bmi_max, height):
|
| 154 |
+
# BMI formula: BMI = weight (lb) / [height (in)]^2 * 703
|
| 155 |
+
# Rearranged to find weight: weight = BMI * height^2 / 703
|
| 156 |
+
weight_min = (bmi_min * height ** 2) / 703
|
| 157 |
+
weight_max = (bmi_max * height ** 2) / 703
|
| 158 |
+
return weight_min, weight_max
|
| 159 |
|
| 160 |
# Create Gradio interface with updated input components
|
| 161 |
interface = gr.Interface(
|
| 162 |
fn=predict_bmi,
|
| 163 |
inputs=[
|
| 164 |
gr.Image(type="pil"),
|
| 165 |
+
gr.Number(label="Height in inches"),
|
| 166 |
+
gr.Number(label="Age")
|
| 167 |
],
|
| 168 |
outputs="json",
|
| 169 |
title="BMI Prediction",
|