Spaces:
Runtime error
Runtime error
File size: 9,426 Bytes
11c6f05 d9572ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | import os
import cv2
import numpy as np
import tensorflow as tf
import base64
import urllib.request
from datetime import datetime
from flask import Flask, render_template, request, jsonify
from werkzeug.utils import secure_filename
# Needed as custom_objects when loading models that have Lambda(preprocess_input) inside
from tensorflow.keras.applications.resnet50 import preprocess_input as resnet_preprocess
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input as mobilenet_preprocess
# MediaPipe V2 Imports
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads'
MODEL_DIR = 'models'
DETECTOR_PATH = os.path.join(MODEL_DIR, 'detector.tflite')
# ==========================================
# 1. AI ENGINE
# ==========================================
class UnderToneAI:
def __init__(self, model_dir, detector_path):
self.model_dir = model_dir
self.model_path = detector_path
# Lowercase + alphabetical order — matches flow_from_dataframe class assignment
# cool=0, neutral=1, warm=2
self.classes = ['cool', 'neutral', 'warm']
self.models = {}
self.detector = None
self._load_classification_models()
self._prepare_detector()
# ------------------------------------------------------------------
def _load_classification_models(self):
"""
The notebook bakes preprocess_input as a Lambda layer inside the model:
x = layers.Lambda(preprocess)(inp)
So we must pass it via custom_objects on load.
compile=False avoids optimizer-state errors.
"""
try:
self.models['resnet'] = tf.keras.models.load_model(
os.path.join(self.model_dir, 'best_ResNet50.h5'),
custom_objects={'preprocess_input': resnet_preprocess},
compile=False
)
self.models['mobilenet'] = tf.keras.models.load_model(
os.path.join(self.model_dir, 'best_MobileNetV2.h5'),
custom_objects={'preprocess_input': mobilenet_preprocess},
compile=False
)
print("[SUCCESS] Classification models loaded.")
except Exception as e:
print(f"[ERROR] Failed to load models: {e}")
raise
# ------------------------------------------------------------------
def _prepare_detector(self):
url = (
"https://storage.googleapis.com/mediapipe-models/"
"face_detector/blaze_face_short_range/float16/1/"
"blaze_face_short_range.tflite"
)
os.makedirs(self.model_dir, exist_ok=True)
if not os.path.exists(self.model_path):
print(f"[INFO] Downloading detector to {self.model_path}...")
urllib.request.urlretrieve(url, self.model_path)
print("[SUCCESS] Download complete.")
base_options = python.BaseOptions(model_asset_path=self.model_path)
# No min_detection_confidence — use default, matching new notebook
options = vision.FaceDetectorOptions(base_options=base_options)
self.detector = vision.FaceDetector.create_from_options(options)
# ------------------------------------------------------------------
def color_constancy(self, img, power=6):
"""
Shades of Gray color constancy — matches FaceProcessor.color_constancy()
in the new notebook.
Formula: scale each channel by (mean_of_means / channel_p-mean).
Input/output: BGR uint8.
"""
img_f = img.astype(np.float32)
# p-norm mean per channel
mean = np.power(np.mean(np.power(img_f, power), axis=(0, 1)), 1.0 / power)
scale = np.mean(mean) / (mean + 1e-6) # avoid div-by-zero
img_f *= scale
return np.clip(img_f, 0, 255).astype(np.uint8)
# ------------------------------------------------------------------
def _encode_b64(self, img_bgr, max_dim=640):
"""Resize-then-encode a BGR image as a JPEG base64 data URL."""
h, w = img_bgr.shape[:2]
if max(h, w) > max_dim:
scale = max_dim / max(h, w)
img_bgr = cv2.resize(img_bgr, (int(w * scale), int(h * scale)))
_, buf = cv2.imencode('.jpg', img_bgr, [cv2.IMWRITE_JPEG_QUALITY, 85])
return 'data:image/jpeg;base64,' + base64.b64encode(buf).decode()
def predict(self, img_path):
# 1. Load
img_bgr = cv2.imread(img_path)
if img_bgr is None:
return None, "Gagal membaca gambar"
# 2. Shades of Gray color constancy — applied before detection,
# matching FaceProcessor.process_dataset() order in new notebook.
img_bgr = self.color_constancy(img_bgr)
# 2b. Encode original (constancy-corrected) image for frontend display
original_b64 = self._encode_b64(img_bgr)
# 3. Face detection — convert BGR→RGB then wrap in mp.Image
rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
mp_img = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
detection_result = self.detector.detect(mp_img)
if not detection_result.detections:
return None, "Wajah tidak terdeteksi"
# 4. Use first detection — matches new notebook (detections[0])
bbox = detection_result.detections[0].bounding_box
x1 = int(bbox.origin_x)
y1 = int(bbox.origin_y)
x2 = int(x1 + bbox.width)
y2 = int(y1 + bbox.height)
face = img_bgr[y1:y2, x1:x2]
if face.size == 0:
return None, "Wajah tidak terdeteksi"
# 5. Center ROI crop — take middle 40% of face region.
# Matches new notebook: face[h*0.3:h*0.7, w*0.3:w*0.7]
# This isolates cheek/nose skin, excluding hair, forehead, jaw.
h, w, _ = face.shape
roi = face[int(h * 0.3):int(h * 0.7),
int(w * 0.3):int(w * 0.7)]
# 6. Resize ROI to model input size
roi_resized = cv2.resize(roi, (224, 224))
# 7. Save ROI crop for frontend display and encode as base64
crop_name = f"crop_{os.path.basename(img_path)}"
cv2.imwrite(os.path.join(app.config['UPLOAD_FOLDER'], crop_name), roi_resized)
crop_b64 = self._encode_b64(roi_resized)
# 8. Prepare model input.
# val_aug = ImageDataGenerator() has NO rescale/preprocessing_function.
# Model has Lambda(preprocess_input) internally → feed raw [0-255] float32.
face_rgb = cv2.cvtColor(roi_resized, cv2.COLOR_BGR2RGB)
face_input = face_rgb.astype(np.float32) # [0, 255], no /255
face_input = np.expand_dims(face_input, axis=0) # (1, 224, 224, 3)
# 9. Inference
res_raw = self.models['resnet'].predict(face_input, verbose=0)[0].tolist()
mob_raw = self.models['mobilenet'].predict(face_input, verbose=0)[0].tolist()
return crop_name, original_b64, crop_b64, {
'resnet': {
'label': self.classes[int(np.argmax(res_raw))],
'scores': {self.classes[i]: score for i, score in enumerate(res_raw)}
},
'mobilenet': {
'label': self.classes[int(np.argmax(mob_raw))],
'scores': {self.classes[i]: score for i, score in enumerate(mob_raw)}
}
}
# ==========================================
# 2. GLOBAL INSTANCE
# ==========================================
ai_engine = UnderToneAI(MODEL_DIR, DETECTOR_PATH)
# ==========================================
# 3. FLASK ROUTES
# ==========================================
@app.route('/')
def index():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
try:
if 'file' in request.files:
file = request.files['file']
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
elif request.json and 'image' in request.json:
data = request.json['image']
_, encoded = data.split(",", 1)
decoded = base64.b64decode(encoded)
filename = f"cam_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
with open(filepath, "wb") as f:
f.write(decoded)
else:
return jsonify({'error': 'Invalid input'}), 400
crop_file, original_b64, crop_b64, results = ai_engine.predict(filepath)
if not crop_file:
return jsonify({'error': original_b64}), 400
return jsonify({
'original': filename,
'original_b64': original_b64,
'crop': crop_file,
'crop_b64': crop_b64,
'results': results
})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
app.run(debug=True, port=5000) |