Spaces:
Runtime error
Runtime error
Download app.py from devluke/undertone-classification: direct link, hf CLI and curl.
- Browser
- Download file 9.19 kB
-
https://huggingface.co/spaces/devluke/undertone-classification/resolve/main/app.py
- Command line
-
hf download hf://spaces/devluke/undertone-classification/app.py
-
curl -L -o app.py https://huggingface.co/spaces/devluke/undertone-classification/resolve/main/app.py
9.19 kB
| 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 | |
| # ========================================== | |
| def index(): | |
| return render_template('index.html') | |
| 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) |