devluke commited on
Commit
d9572ee
·
verified ·
1 Parent(s): e05e60f

Upload app.py

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