Create inference.py
Browse filesYou can input the image path and get the face shape classfication
- inference.py +82 -0
inference.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
import torch
|
| 4 |
+
import torchvision.transforms as T
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import torch.nn.functional as F # For softmax
|
| 7 |
+
|
| 8 |
+
# Define device
|
| 9 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 10 |
+
|
| 11 |
+
# Model and transformation setup
|
| 12 |
+
def download_model_if_not_exists(url, model_path):
|
| 13 |
+
"""Download model from Hugging Face repository if it doesn't exist locally."""
|
| 14 |
+
if not os.path.exists(model_path):
|
| 15 |
+
print("Model not found locally, downloading from Hugging Face...")
|
| 16 |
+
response = requests.get(url)
|
| 17 |
+
if response.status_code == 200:
|
| 18 |
+
with open(model_path, 'wb') as f:
|
| 19 |
+
f.write(response.content)
|
| 20 |
+
print(f"Model downloaded and saved to {model_path}")
|
| 21 |
+
else:
|
| 22 |
+
print("Failed to download model. Please check the URL.")
|
| 23 |
+
else:
|
| 24 |
+
print("Model already exists locally.")
|
| 25 |
+
|
| 26 |
+
def load_model(model_path):
|
| 27 |
+
"""Load model from the given path."""
|
| 28 |
+
model = torch.load(model_path, map_location=torch.device('cpu'))
|
| 29 |
+
model.eval() # Set model to evaluation mode
|
| 30 |
+
model.to(device)
|
| 31 |
+
return model
|
| 32 |
+
|
| 33 |
+
def preprocess_image(image_path):
|
| 34 |
+
transform = T.Compose([
|
| 35 |
+
T.Resize((224, 224)), # Resize image to 224x224
|
| 36 |
+
T.ToTensor(), # Convert image to Tensor
|
| 37 |
+
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # Normalize
|
| 38 |
+
])
|
| 39 |
+
image = Image.open(image_path).convert("RGB") # Open and convert image to RGB
|
| 40 |
+
return transform(image).unsqueeze(0) # Add batch dimension
|
| 41 |
+
|
| 42 |
+
def get_probabilities(logits):
|
| 43 |
+
"""Apply softmax to get probabilities."""
|
| 44 |
+
probabilities = F.softmax(logits, dim=1)
|
| 45 |
+
percentages = probabilities * 100
|
| 46 |
+
return percentages
|
| 47 |
+
|
| 48 |
+
def predict(image_path, model, class_names):
|
| 49 |
+
"""Make prediction using the trained model."""
|
| 50 |
+
image_tensor = preprocess_image(image_path).to(device)
|
| 51 |
+
model.eval()
|
| 52 |
+
with torch.inference_mode(): # Disable gradient calculations
|
| 53 |
+
outputs = model(image_tensor)
|
| 54 |
+
percentages = get_probabilities(outputs)
|
| 55 |
+
_, predicted_class = torch.max(outputs, 1) # Get the index of the highest logit
|
| 56 |
+
predicted_label = class_names[predicted_class.item()]
|
| 57 |
+
return predicted_label, percentages
|
| 58 |
+
|
| 59 |
+
# Define class names
|
| 60 |
+
class_names = ['Heart', 'Oblong', 'Oval', 'Round', 'Square']
|
| 61 |
+
|
| 62 |
+
# Path to the model file
|
| 63 |
+
model_path = r"model_85_nn_.pth" # Update this with the correct model path
|
| 64 |
+
model_url = "https://huggingface.co/fahd9999/model_85_nn_/resolve/main/model_85_nn_.pth?download=true"
|
| 65 |
+
|
| 66 |
+
# Download the model only if it doesn't exist locally
|
| 67 |
+
download_model_if_not_exists(model_url, model_path)
|
| 68 |
+
|
| 69 |
+
# Load the model
|
| 70 |
+
model = load_model(model_path)
|
| 71 |
+
|
| 72 |
+
def main(image_path):
|
| 73 |
+
"""Run the prediction process."""
|
| 74 |
+
predicted_label, percentages = predict(image_path, model, class_names)
|
| 75 |
+
result = {class_names[i]: percentages[0, i].item() for i in range(len(class_names))}
|
| 76 |
+
sorted_result = dict(sorted(result.items(), key=lambda item: item[1], reverse=True))
|
| 77 |
+
print(sorted_result)
|
| 78 |
+
|
| 79 |
+
# Call the function with the path to the image
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
image_path = "path_to_your_image.jpg" # Update this with your image path
|
| 82 |
+
main(image_path)
|