AshanGimhana
commited on
Commit
•
646ccb4
1
Parent(s):
02f81b2
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import subprocess
|
3 |
+
|
4 |
+
os.system("pip install gradio==3.50")
|
5 |
+
os.system("pip install dlib==19.24.2")
|
6 |
+
|
7 |
+
#############################################
|
8 |
+
|
9 |
+
import torch
|
10 |
+
print(f"Is CUDA available: {torch.cuda.is_available()}")
|
11 |
+
# True
|
12 |
+
print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
|
13 |
+
|
14 |
+
###################################################
|
15 |
+
|
16 |
+
|
17 |
+
from argparse import Namespace
|
18 |
+
import pprint
|
19 |
+
import numpy as np
|
20 |
+
from PIL import Image
|
21 |
+
import torch
|
22 |
+
import torchvision.transforms as transforms
|
23 |
+
import cv2
|
24 |
+
import dlib
|
25 |
+
import matplotlib.pyplot as plt
|
26 |
+
import gradio as gr # Importing Gradio as gr
|
27 |
+
from tensorflow.keras.preprocessing.image import img_to_array
|
28 |
+
from huggingface_hub import hf_hub_download, login
|
29 |
+
from datasets.augmentations import AgeTransformer
|
30 |
+
from utils.common import tensor2im
|
31 |
+
from models.psp import pSp
|
32 |
+
|
33 |
+
# Huggingface login
|
34 |
+
login(token=os.getenv("TOKENKEY"))
|
35 |
+
|
36 |
+
# Download models from Huggingface
|
37 |
+
age_prototxt = hf_hub_download(repo_id="AshanGimhana/Age_Detection_caffe", filename="age.prototxt")
|
38 |
+
caffe_model = hf_hub_download(repo_id="AshanGimhana/Age_Detection_caffe", filename="dex_imdb_wiki.caffemodel")
|
39 |
+
sam_ffhq_aging = hf_hub_download(repo_id="AshanGimhana/Face_Agin_model", filename="sam_ffhq_aging.pt")
|
40 |
+
|
41 |
+
# Age prediction model setup
|
42 |
+
age_net = cv2.dnn.readNetFromCaffe(age_prototxt, caffe_model)
|
43 |
+
|
44 |
+
# Face detection and landmarks predictor setup
|
45 |
+
detector = dlib.get_frontal_face_detector()
|
46 |
+
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
|
47 |
+
|
48 |
+
# Load the pretrained aging model
|
49 |
+
EXPERIMENT_TYPE = 'ffhq_aging'
|
50 |
+
EXPERIMENT_DATA_ARGS = {
|
51 |
+
"ffhq_aging": {
|
52 |
+
"model_path": sam_ffhq_aging,
|
53 |
+
"transform": transforms.Compose([
|
54 |
+
transforms.Resize((256, 256)),
|
55 |
+
transforms.ToTensor(),
|
56 |
+
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
|
57 |
+
])
|
58 |
+
}
|
59 |
+
}
|
60 |
+
EXPERIMENT_ARGS = EXPERIMENT_DATA_ARGS[EXPERIMENT_TYPE]
|
61 |
+
model_path = EXPERIMENT_ARGS['model_path']
|
62 |
+
ckpt = torch.load(model_path, map_location='cpu')
|
63 |
+
opts = ckpt['opts']
|
64 |
+
pprint.pprint(opts)
|
65 |
+
opts['checkpoint_path'] = model_path
|
66 |
+
opts = Namespace(**opts)
|
67 |
+
net = pSp(opts)
|
68 |
+
net.eval()
|
69 |
+
net.cuda()
|
70 |
+
|
71 |
+
print('Model successfully loaded!')
|
72 |
+
|
73 |
+
|
74 |
+
# Functions for face and mouth region
|
75 |
+
def get_face_region(image):
|
76 |
+
gray = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)
|
77 |
+
faces = detector(gray)
|
78 |
+
if len(faces) > 0:
|
79 |
+
return faces[0]
|
80 |
+
return None
|
81 |
+
|
82 |
+
def get_mouth_region(image):
|
83 |
+
gray = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)
|
84 |
+
faces = detector(gray)
|
85 |
+
for face in faces:
|
86 |
+
landmarks = predictor(gray, face)
|
87 |
+
mouth_points = [(landmarks.part(i).x, landmarks.part(i).y) for i in range(48, 68)]
|
88 |
+
return np.array(mouth_points, np.int32)
|
89 |
+
return None
|
90 |
+
|
91 |
+
# Function to predict age
|
92 |
+
def predict_age(image):
|
93 |
+
image = np.array(image)
|
94 |
+
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
|
95 |
+
blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size=(224, 224), mean=(104.0, 177.0, 123.0), swapRB=False)
|
96 |
+
age_net.setInput(blob)
|
97 |
+
predictions = age_net.forward()
|
98 |
+
predicted_age = np.dot(predictions[0], np.arange(0, 101)).flatten()[0]
|
99 |
+
return int(predicted_age)
|
100 |
+
|
101 |
+
# Function for color correction
|
102 |
+
def color_correct(source, target):
|
103 |
+
mean_src = np.mean(source, axis=(0, 1))
|
104 |
+
std_src = np.std(source, axis=(0, 1))
|
105 |
+
mean_tgt = np.mean(target, axis=(0, 1))
|
106 |
+
std_tgt = np.std(target, axis=(0, 1))
|
107 |
+
src_normalized = (source - mean_src) / std_src
|
108 |
+
src_corrected = (src_normalized * std_tgt) + mean_tgt
|
109 |
+
return np.clip(src_corrected, 0, 255).astype(np.uint8)
|
110 |
+
|
111 |
+
# Function to replace teeth
|
112 |
+
def replace_teeth(temp_image, aged_image):
|
113 |
+
temp_image = np.array(temp_image)
|
114 |
+
aged_image = np.array(aged_image)
|
115 |
+
temp_mouth = get_mouth_region(temp_image)
|
116 |
+
aged_mouth = get_mouth_region(aged_image)
|
117 |
+
if temp_mouth is None or aged_mouth is None:
|
118 |
+
return aged_image
|
119 |
+
temp_mask = np.zeros_like(temp_image)
|
120 |
+
cv2.fillConvexPoly(temp_mask, temp_mouth, (255, 255, 255))
|
121 |
+
temp_mouth_region = cv2.bitwise_and(temp_image, temp_mask)
|
122 |
+
temp_mouth_bbox = cv2.boundingRect(temp_mouth)
|
123 |
+
aged_mouth_bbox = cv2.boundingRect(aged_mouth)
|
124 |
+
temp_mouth_crop = temp_mouth_region[temp_mouth_bbox[1]:temp_mouth_bbox[1] + temp_mouth_bbox[3], temp_mouth_bbox[0]:temp_mouth_bbox[0] + temp_mouth_bbox[2]]
|
125 |
+
temp_mask_crop = temp_mask[temp_mouth_bbox[1]:temp_mouth_bbox[1] + temp_mouth_bbox[3], temp_mouth_bbox[0]:temp_mouth_bbox[0] + temp_mouth_bbox[2]]
|
126 |
+
temp_mouth_crop_resized = cv2.resize(temp_mouth_crop, (aged_mouth_bbox[2], aged_mouth_bbox[3]))
|
127 |
+
temp_mask_crop_resized = cv2.resize(temp_mask_crop, (aged_mouth_bbox[2], aged_mouth_bbox[3]))
|
128 |
+
aged_mouth_crop = aged_image[aged_mouth_bbox[1]:aged_mouth_bbox[1] + aged_mouth_bbox[3], aged_mouth_bbox[0]:aged_mouth_bbox[0] + aged_mouth_bbox[2]]
|
129 |
+
temp_mouth_crop_resized = color_correct(temp_mouth_crop_resized, aged_mouth_crop)
|
130 |
+
center = (aged_mouth_bbox[0] + aged_mouth_bbox[2] // 2, aged_mouth_bbox[1] + aged_mouth_bbox[3] // 2)
|
131 |
+
seamless_teeth = cv2.seamlessClone(temp_mouth_crop_resized, aged_image, temp_mask_crop_resized, center, cv2.NORMAL_CLONE)
|
132 |
+
return seamless_teeth
|
133 |
+
|
134 |
+
# Function to run alignment
|
135 |
+
def run_alignment(image):
|
136 |
+
from scripts.align_all_parallel import align_face
|
137 |
+
temp_image_path = "/tmp/temp_image.jpg"
|
138 |
+
image.save(temp_image_path)
|
139 |
+
aligned_image = align_face(filepath=temp_image_path, predictor=predictor)
|
140 |
+
return aligned_image
|
141 |
+
|
142 |
+
# Function to apply aging
|
143 |
+
def apply_aging(image, target_age):
|
144 |
+
img_transforms = EXPERIMENT_DATA_ARGS[EXPERIMENT_TYPE]['transform']
|
145 |
+
input_image = img_transforms(image)
|
146 |
+
age_transformers = [AgeTransformer(target_age=target_age)]
|
147 |
+
results = []
|
148 |
+
for age_transformer in age_transformers:
|
149 |
+
with torch.no_grad():
|
150 |
+
input_image_age = [age_transformer(input_image.cpu()).to('cuda')]
|
151 |
+
input_image_age = torch.stack(input_image_age)
|
152 |
+
result_tensor = net(input_image_age.float(), randomize_noise=False, resize=False)[0]
|
153 |
+
result_image = tensor2im(result_tensor)
|
154 |
+
results.append(np.array(result_image))
|
155 |
+
final_result = results[0]
|
156 |
+
return final_result
|
157 |
+
|
158 |
+
# Function to process the image
|
159 |
+
def process_image(uploaded_image):
|
160 |
+
# Loading images for good and bad teeth
|
161 |
+
temp_images_good = [Image.open(f"good_teeth/G{i}.JPG") for i in range(1, 4)]
|
162 |
+
temp_images_bad = [Image.open(f"bad_teeth/B{i}.jpeg") for i in range(1, 7)]
|
163 |
+
|
164 |
+
# Predicting the age
|
165 |
+
predicted_age = predict_age(uploaded_image)
|
166 |
+
target_age = predicted_age + 5
|
167 |
+
|
168 |
+
# Aligning the face in the uploaded image
|
169 |
+
aligned_image = run_alignment(uploaded_image)
|
170 |
+
|
171 |
+
# Applying aging effect
|
172 |
+
aged_image = apply_aging(aligned_image, target_age=target_age)
|
173 |
+
|
174 |
+
# Randomly selecting teeth images
|
175 |
+
good_teeth_image = temp_images_good[np.random.randint(0, len(temp_images_good))]
|
176 |
+
bad_teeth_image = temp_images_bad[np.random.randint(0, len(temp_images_bad))]
|
177 |
+
|
178 |
+
# Replacing teeth in aged image
|
179 |
+
aged_image_good_teeth = replace_teeth(good_teeth_image, aged_image)
|
180 |
+
aged_image_bad_teeth = replace_teeth(bad_teeth_image, aged_image)
|
181 |
+
|
182 |
+
return aged_image_good_teeth, aged_image_bad_teeth, predicted_age, target_age
|
183 |
+
|
184 |
+
# Gradio Interface
|
185 |
+
def show_results(uploaded_image):
|
186 |
+
aged_image_good_teeth, aged_image_bad_teeth, predicted_age, target_age = process_image(uploaded_image)
|
187 |
+
return aged_image_good_teeth, aged_image_bad_teeth, f"Predicted Age: {predicted_age}, Target Age: {target_age}"
|
188 |
+
|
189 |
+
iface = gr.Interface(
|
190 |
+
fn=show_results,
|
191 |
+
inputs=gr.Image(type="pil"),
|
192 |
+
outputs=[gr.Image(type="pil"), gr.Image(type="pil"), gr.Textbox()],
|
193 |
+
title="Aging Effect with Teeth Replacement",
|
194 |
+
description="Upload an image to apply an aging effect. The application will generate two results: one with good teeth and one with bad teeth."
|
195 |
+
)
|
196 |
+
|
197 |
+
iface.launch()
|