FaceAgePredict / app.py
MoinulwithAI's picture
Create app.py
0d5c920 verified
raw
history blame
2.02 kB
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from PIL import Image
import gradio as gr
# ------------------- Model Definition -------------------
class SimpleCNN(nn.Module):
def __init__(self, num_classes=1):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(128 * 28 * 28, 512)
self.fc2 = nn.Linear(512, num_classes)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = self.pool(F.relu(self.conv3(x)))
x = x.view(-1, 128 * 28 * 28)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
# ------------------- Load Model -------------------
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = SimpleCNN()
model.load_state_dict(torch.load("age_prediction_model1.pth", map_location=device))
model.to(device)
model.eval()
# ------------------- Transform -------------------
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
])
# ------------------- Prediction Function -------------------
def predict(image):
image = transform(image).unsqueeze(0).to(device)
with torch.no_grad():
output = model(image).squeeze().item()
return f"Predicted Age: {round(output, 2)} years"
# ------------------- Gradio Interface -------------------
iface = gr.Interface(fn=predict,
inputs=gr.Image(type="pil"),
outputs="text",
title="Face Age Prediction",
description="Upload a face image and get a predicted age")
iface.launch()