beth594 commited on
Commit
9ffbf88
·
verified ·
1 Parent(s): 9fe3fa1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +8 -115
app.py CHANGED
@@ -1,120 +1,13 @@
1
  #!/usr/bin/env python
2
 
3
- import functools
4
- import os
5
- import pathlib
6
-
7
- import cv2
8
- import dlib
9
  import gradio as gr
10
- import huggingface_hub
11
- import numpy as np
12
- import pretrainedmodels
13
- import torch
14
- import torch.nn as nn
15
- import torch.nn.functional as F
16
-
17
- DESCRIPTION = "# [Age Estimation](https://github.com/yu4u/age-estimation-pytorch)"
18
-
19
-
20
- def get_model(model_name="se_resnext50_32x4d", num_classes=101, pretrained="imagenet"):
21
- model = pretrainedmodels.__dict__[model_name](pretrained=pretrained)
22
- dim_feats = model.last_linear.in_features
23
- model.last_linear = nn.Linear(dim_feats, num_classes)
24
- model.avg_pool = nn.AdaptiveAvgPool2d(1)
25
- return model
26
-
27
-
28
- def load_model(device):
29
- model = get_model(model_name="se_resnext50_32x4d", pretrained=None)
30
- path = huggingface_hub.hf_hub_download("public-data/yu4u-age-estimation-pytorch", "pretrained.pth")
31
- model.load_state_dict(torch.load(path))
32
- model = model.to(device)
33
- model.eval()
34
- return model
35
-
36
-
37
- def load_image(path):
38
- image = cv2.imread(path)
39
- h_orig, w_orig = image.shape[:2]
40
- size = max(h_orig, w_orig)
41
- scale = 640 / size
42
- w, h = int(w_orig * scale), int(h_orig * scale)
43
- image = cv2.resize(image, (w, h))
44
- return image
45
-
46
-
47
- def draw_label(image, point, label, font=cv2.FONT_HERSHEY_SIMPLEX, font_scale=0.8, thickness=1):
48
- size = cv2.getTextSize(label, font, font_scale, thickness)[0]
49
- x, y = point
50
- cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)
51
- cv2.putText(image, label, point, font, font_scale, (255, 255, 255), thickness, lineType=cv2.LINE_AA)
52
-
53
-
54
- @torch.inference_mode()
55
- def predict(image, model, face_detector, device, margin=0.4, input_size=224):
56
- image = cv2.imread(image, cv2.IMREAD_COLOR)[:, :, ::-1].copy()
57
- image_h, image_w = image.shape[:2]
58
-
59
- # detect faces using dlib detector
60
- detected = face_detector(image, 1)
61
- faces = np.empty((len(detected), input_size, input_size, 3))
62
-
63
- if len(detected) > 0:
64
- for i, d in enumerate(detected):
65
- x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()
66
- xw1 = max(int(x1 - margin * w), 0)
67
- yw1 = max(int(y1 - margin * h), 0)
68
- xw2 = min(int(x2 + margin * w), image_w - 1)
69
- yw2 = min(int(y2 + margin * h), image_h - 1)
70
- faces[i] = cv2.resize(image[yw1 : yw2 + 1, xw1 : xw2 + 1], (input_size, input_size))
71
-
72
- cv2.rectangle(image, (x1, y1), (x2, y2), (255, 255, 255), 2)
73
- cv2.rectangle(image, (xw1, yw1), (xw2, yw2), (255, 0, 0), 2)
74
-
75
- # predict ages
76
- inputs = torch.from_numpy(np.transpose(faces.astype(np.float32), (0, 3, 1, 2))).to(device)
77
- outputs = F.softmax(model(inputs), dim=-1).cpu().numpy()
78
- ages = np.arange(0, 101)
79
- predicted_ages = (outputs * ages).sum(axis=-1)
80
-
81
- # draw results
82
- for age, d in zip(predicted_ages, detected):
83
- draw_label(image, (d.left(), d.top()), f"{int(age)}")
84
- return image, str(predicted_ages)
85
-
86
-
87
- device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
88
- model = load_model(device)
89
- face_detector = dlib.get_frontal_face_detector()
90
- fn = functools.partial(predict, model=model, face_detector=face_detector, device=device)
91
-
92
- image_dir = pathlib.Path("sample_images")
93
- examples = [path.as_posix() for path in sorted(image_dir.glob("*.jpg"))]
94
-
95
- with gr.Blocks(css="style.css") as demo:
96
- gr.Markdown(DESCRIPTION)
97
- with gr.Row():
98
- with gr.Column():
99
- image = gr.Image(label="Input", type="filepath")
100
- run_button = gr.Button("Run")
101
- with gr.Column():
102
- result = gr.Image(label="Result")
103
- digits = gr.Textbox()
104
 
105
- gr.Examples(
106
- examples=examples,
107
- inputs=image,
108
- outputs=result,
109
- fn=fn,
110
- cache_examples=os.getenv("CACHE_EXAMPLES") == "1",
111
- )
112
- run_button.click(
113
- fn=fn,
114
- inputs=image,
115
- outputs=result,
116
- api_name="predict",
117
- )
118
 
119
- if __name__ == "__main__":
120
- demo.queue(max_size=15).launch()
 
1
  #!/usr/bin/env python
2
 
 
 
 
 
 
 
3
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ def greet(text):
6
+ return text
7
+
8
+ with gr.Blocks() as demo:
9
+ input = gr.TextArea()
10
+ output = gr.TextArea()
11
+ gr.Button().click(fn=greet, inputs=input, outputs=output)
 
 
 
 
 
 
12
 
13
+ demo.launch(debug=True)