Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
import torchvision.transforms as transforms
|
5 |
+
from PIL import Image
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
# ------------------- Model Definition -------------------
|
9 |
+
class SimpleCNN(nn.Module):
|
10 |
+
def __init__(self, num_classes=1):
|
11 |
+
super(SimpleCNN, self).__init__()
|
12 |
+
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
|
13 |
+
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
|
14 |
+
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
|
15 |
+
self.pool = nn.MaxPool2d(2, 2)
|
16 |
+
self.fc1 = nn.Linear(128 * 28 * 28, 512)
|
17 |
+
self.fc2 = nn.Linear(512, num_classes)
|
18 |
+
|
19 |
+
def forward(self, x):
|
20 |
+
x = self.pool(F.relu(self.conv1(x)))
|
21 |
+
x = self.pool(F.relu(self.conv2(x)))
|
22 |
+
x = self.pool(F.relu(self.conv3(x)))
|
23 |
+
x = x.view(-1, 128 * 28 * 28)
|
24 |
+
x = F.relu(self.fc1(x))
|
25 |
+
x = self.fc2(x)
|
26 |
+
return x
|
27 |
+
|
28 |
+
# ------------------- Load Model -------------------
|
29 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
30 |
+
model = SimpleCNN()
|
31 |
+
model.load_state_dict(torch.load("age_prediction_model1.pth", map_location=device))
|
32 |
+
model.to(device)
|
33 |
+
model.eval()
|
34 |
+
|
35 |
+
# ------------------- Transform -------------------
|
36 |
+
transform = transforms.Compose([
|
37 |
+
transforms.Resize((224, 224)),
|
38 |
+
transforms.ToTensor(),
|
39 |
+
transforms.Normalize([0.485, 0.456, 0.406],
|
40 |
+
[0.229, 0.224, 0.225])
|
41 |
+
])
|
42 |
+
|
43 |
+
# ------------------- Prediction Function -------------------
|
44 |
+
def predict(image):
|
45 |
+
image = transform(image).unsqueeze(0).to(device)
|
46 |
+
with torch.no_grad():
|
47 |
+
output = model(image).squeeze().item()
|
48 |
+
return f"Predicted Age: {round(output, 2)} years"
|
49 |
+
|
50 |
+
# ------------------- Gradio Interface -------------------
|
51 |
+
iface = gr.Interface(fn=predict,
|
52 |
+
inputs=gr.Image(type="pil"),
|
53 |
+
outputs="text",
|
54 |
+
title="Face Age Prediction",
|
55 |
+
description="Upload a face image and get a predicted age")
|
56 |
+
|
57 |
+
iface.launch()
|