This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50) hide show
  1. .dockerignore +27 -27
  2. .gitattributes +2 -1
  3. .gitignore +1 -1
  4. Dockerfile +69 -97
  5. README.md +79 -86
  6. app.py +236 -236
  7. models/best_MobileNetV2.h5 +2 -2
  8. models/best_ResNet50.h5 +2 -2
  9. static/uploads/Screenshot_2026-06-04_213003.png +3 -0
  10. static/uploads/WhatsApp_Image_2026-06-04_at_21.19.01.jpeg +0 -0
  11. static/uploads/cam_20260604_213126.jpg +0 -0
  12. static/uploads/cam_20260708_163346.jpg +0 -0
  13. static/uploads/cam_20260708_163415.jpg +0 -0
  14. static/uploads/cam_20260708_163424.jpg +0 -0
  15. static/uploads/cam_20260708_163452.jpg +0 -0
  16. static/uploads/cam_20260708_163503.jpg +0 -0
  17. static/uploads/cam_20260708_163508.jpg +0 -0
  18. static/uploads/cam_20260708_163516.jpg +0 -0
  19. static/uploads/cam_20260708_163520.jpg +0 -0
  20. static/uploads/cam_20260708_163526.jpg +0 -0
  21. static/uploads/cam_20260708_163532.jpg +0 -0
  22. static/uploads/cam_20260708_163541.jpg +0 -0
  23. static/uploads/cam_20260708_163700.jpg +0 -0
  24. static/uploads/cam_20260708_163709.jpg +0 -0
  25. static/uploads/cam_20260708_163715.jpg +0 -0
  26. static/uploads/cam_20260708_163724.jpg +0 -0
  27. static/uploads/cam_20260708_163731.jpg +0 -0
  28. static/uploads/cam_20260708_163748.jpg +0 -0
  29. static/uploads/cam_20260708_163818.jpg +0 -0
  30. static/uploads/cam_20260708_163824.jpg +0 -0
  31. static/uploads/cam_20260708_163830.jpg +0 -0
  32. static/uploads/cam_20260708_163837.jpg +0 -0
  33. static/uploads/cam_20260708_163847.jpg +0 -0
  34. static/uploads/cam_20260709_084845.jpg +0 -0
  35. static/uploads/cam_20260709_085000.jpg +0 -0
  36. static/uploads/cam_20260709_085021.jpg +0 -0
  37. static/uploads/cam_20260709_085046.jpg +0 -0
  38. static/uploads/cam_20260709_085055.jpg +0 -0
  39. static/uploads/cam_20260709_085107.jpg +0 -0
  40. static/uploads/cam_20260709_085116.jpg +0 -0
  41. static/uploads/cam_20260709_085136.jpg +0 -0
  42. static/uploads/cam_20260709_085151.jpg +0 -0
  43. static/uploads/cam_20260709_085209.jpg +0 -0
  44. static/uploads/cam_20260709_085224.jpg +0 -0
  45. static/uploads/crop_Screenshot_2026-06-04_213003.png +0 -0
  46. static/uploads/crop_WhatsApp_Image_2026-06-04_at_21.19.01.jpeg +0 -0
  47. static/uploads/crop_cam_20260604_213126.jpg +0 -0
  48. static/uploads/crop_cam_20260708_163346.jpg +0 -0
  49. static/uploads/crop_cam_20260708_163415.jpg +0 -0
  50. static/uploads/crop_cam_20260708_163424.jpg +0 -0
.dockerignore CHANGED
@@ -1,27 +1,27 @@
1
- # Git
2
- .git
3
- .gitignore
4
- .gitattributes
5
-
6
- # Dev tooling
7
- .devcontainer
8
- *.md
9
-
10
- # Python cache
11
- __pycache__
12
- *.py[cod]
13
- *.pyo
14
- *.pyd
15
- .Python
16
-
17
- # Virtual environments
18
- .venv
19
- venv
20
- env
21
-
22
- # Uploaded files (runtime data — not needed at build time)
23
- static/uploads/
24
-
25
- # OS artefacts
26
- .DS_Store
27
- Thumbs.db
 
1
+ # Git
2
+ .git
3
+ .gitignore
4
+ .gitattributes
5
+
6
+ # Dev tooling
7
+ .devcontainer
8
+ *.md
9
+
10
+ # Python cache
11
+ __pycache__
12
+ *.py[cod]
13
+ *.pyo
14
+ *.pyd
15
+ .Python
16
+
17
+ # Virtual environments
18
+ .venv
19
+ venv
20
+ env
21
+
22
+ # Uploaded files (runtime data — not needed at build time)
23
+ static/uploads/
24
+
25
+ # OS artefacts
26
+ .DS_Store
27
+ Thumbs.db
.gitattributes CHANGED
@@ -1,2 +1,3 @@
1
  *.h5 filter=lfs diff=lfs merge=lfs -text
2
- detector.tflite filter=lfs diff=lfs merge=lfs -text
 
 
1
  *.h5 filter=lfs diff=lfs merge=lfs -text
2
+ models/detector.tflite filter=lfs diff=lfs merge=lfs -text
3
+ static/uploads/Screenshot_2026-06-04_213003.png filter=lfs diff=lfs merge=lfs -text
.gitignore CHANGED
@@ -18,7 +18,7 @@ static/uploads/*
18
 
19
  # Downloaded MediaPipe Models
20
  # We ignore .tflite because the code automatically downloads it
21
- models/*.tflite
22
 
23
  # IDEs / Editor folders
24
  .vscode/
 
18
 
19
  # Downloaded MediaPipe Models
20
  # We ignore .tflite because the code automatically downloads it
21
+ # models/*.tflite
22
 
23
  # IDEs / Editor folders
24
  .vscode/
Dockerfile CHANGED
@@ -1,97 +1,69 @@
1
- # ============================================================
2
- # Stage 1: Builder — install Python dependencies
3
- # ============================================================
4
- FROM python:3.11-slim AS builder
5
-
6
- WORKDIR /install
7
-
8
- # Build-time system deps (compilers, headers needed by grpcio, cffi, etc.)
9
- RUN apt-get update && apt-get install -y --no-install-recommends \
10
- build-essential \
11
- wget \
12
- libgl1 \
13
- libglib2.0-0 \
14
- libgomp1 \
15
- libsm6 \
16
- libxext6 \
17
- libxrender1 \
18
- && rm -rf /var/lib/apt/lists/*
19
-
20
- COPY requirements.txt .
21
-
22
- # Install all Python deps + gunicorn into an isolated prefix
23
- RUN pip install --no-cache-dir --prefix=/python-deps -r requirements.txt gunicorn
24
-
25
- # Pre-download the MediaPipe face-detector tflite model at build time
26
- # so the container never needs to reach out to Google Storage at runtime.
27
- RUN mkdir -p /models && \
28
- wget -q -O /models/detector.tflite \
29
- "https://storage.googleapis.com/mediapipe-models/face_detector/blaze_face_short_range/float16/1/blaze_face_short_range.tflite"
30
-
31
-
32
- # ============================================================
33
- # Stage 2: Runtime image
34
- # ============================================================
35
- FROM python:3.11-slim
36
-
37
- LABEL maintainer="undertone-classification"
38
- LABEL description="Skin undertone classification — Flask + TensorFlow + MediaPipe (HF Spaces)"
39
-
40
- # Runtime system libs required by OpenCV and MediaPipe
41
- # libgles2 → provides libGLESv2.so.2 (MediaPipe C bindings hard-require this)
42
- # libegl1 → provides libEGL.so.1 (MediaPipe GPU/EGL path)
43
- RUN apt-get update && apt-get install -y --no-install-recommends \
44
- libgl1 \
45
- libglib2.0-0 \
46
- libgomp1 \
47
- libsm6 \
48
- libxext6 \
49
- libxrender1 \
50
- libgles2 \
51
- libegl1 \
52
- && rm -rf /var/lib/apt/lists/*
53
-
54
- # Copy installed Python packages from the builder stage
55
- COPY --from=builder /python-deps /usr/local
56
-
57
- # ── Hugging Face Spaces requirement ──────────────────────────
58
- # HF Spaces runs containers with a non-root user (UID=1000, GID=1000).
59
- # We create that user and make /app writable so Flask can write uploads.
60
- RUN useradd -m -u 1000 appuser
61
-
62
- WORKDIR /app
63
-
64
- # Copy application source code
65
- COPY app.py .
66
- COPY templates/ templates/
67
- COPY static/ static/
68
- COPY models/ models/
69
-
70
- # Copy the pre-downloaded tflite model into the models directory
71
- COPY --from=builder /models/detector.tflite models/detector.tflite
72
-
73
- # Ensure the uploads directory exists and is owned by the runtime user
74
- RUN mkdir -p static/uploads && \
75
- chown -R appuser:appuser /app
76
-
77
- USER appuser
78
-
79
- # ── Port ──────────────────────────────────────────────────────
80
- # Hugging Face Spaces Docker SDK expects port 7860.
81
- EXPOSE 7860
82
-
83
- ENV FLASK_ENV=production \
84
- PYTHONUNBUFFERED=1 \
85
- PYTHONDONTWRITEBYTECODE=1 \
86
- # Silence unnecessary TF / oneDNN log noise
87
- TF_CPP_MIN_LOG_LEVEL=2 \
88
- TF_ENABLE_ONEDNN_OPTS=0
89
-
90
- # 1 worker → global ai_engine singleton is shared; 180 s timeout for
91
- # model load + first inference.
92
- CMD ["gunicorn", \
93
- "--bind", "0.0.0.0:7860", \
94
- "--workers", "1", \
95
- "--timeout", "180", \
96
- "--log-level", "info", \
97
- "app:app"]
 
1
+ # ============================================================
2
+ # Stage 1: Builder — install Python dependencies
3
+ # ============================================================
4
+ FROM python:3.11-slim AS builder
5
+
6
+ WORKDIR /install
7
+
8
+ # System dependencies required to build some Python packages
9
+ # (OpenCV, MediaPipe, grpcio, cffi, etc.)
10
+ RUN apt-get update && apt-get install -y --no-install-recommends \
11
+ build-essential \
12
+ libgl1 \
13
+ libglib2.0-0 \
14
+ libgomp1 \
15
+ && rm -rf /var/lib/apt/lists/*
16
+
17
+ COPY requirements.txt .
18
+
19
+ # Install all Python deps into an isolated prefix so we can copy
20
+ # only the built packages to the final stage
21
+ # Also install gunicorn as the production WSGI server
22
+ RUN pip install --no-cache-dir --prefix=/python-deps -r requirements.txt gunicorn
23
+
24
+
25
+ # ============================================================
26
+ # Stage 2: Runtime image
27
+ # ============================================================
28
+ FROM python:3.11-slim
29
+
30
+ LABEL maintainer="undertone-classification"
31
+ LABEL description="Skin undertone classification — Flask + TensorFlow + MediaPipe"
32
+
33
+ # Runtime system libs (OpenCV needs libGL/libGLib; MediaPipe needs libgomp)
34
+ RUN apt-get update && apt-get install -y --no-install-recommends \
35
+ libgl1 \
36
+ libglib2.0-0 \
37
+ libgomp1 \
38
+ && rm -rf /var/lib/apt/lists/*
39
+
40
+ # Copy installed Python packages from the builder stage
41
+ COPY --from=builder /python-deps /usr/local
42
+
43
+ WORKDIR /app
44
+
45
+ # Copy application source code
46
+ COPY app.py .
47
+ COPY templates/ templates/
48
+ COPY static/ static/
49
+ COPY models/ models/
50
+
51
+ # Create uploads directory that Flask writes to at runtime
52
+ RUN mkdir -p static/uploads
53
+
54
+ # Expose Flask's default port
55
+ EXPOSE 5000
56
+
57
+ # Run with Gunicorn for production (single worker keeps model in memory)
58
+ # Falls back gracefully: if gunicorn is unavailable the CMD can be swapped
59
+ # to `python app.py` during development.
60
+ ENV FLASK_ENV=production \
61
+ PYTHONUNBUFFERED=1 \
62
+ PYTHONDONTWRITEBYTECODE=1
63
+
64
+ # Use gunicorn; 1 worker so the global ai_engine singleton is shared
65
+ CMD ["python", "-m", "gunicorn", \
66
+ "--bind", "0.0.0.0:5000", \
67
+ "--workers", "1", \
68
+ "--timeout", "120", \
69
+ "app:app"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,86 +1,79 @@
1
- ---
2
- title: Undertone Classification
3
- sdk: docker
4
- emoji: 📊
5
- colorFrom: blue
6
- colorTo: green
7
- ---
8
- # Skin Undertone Classification
9
-
10
- Aplikasi web berbasis Flask untuk mendeteksi dan mengklasifikasikan *skin undertone* (Cool, Neutral, atau Warm) dari wajah seseorang. Aplikasi ini menggunakan MediaPipe untuk mendeteksi wajah dan memotongnya (cropping) sebelum diproses oleh model Deep Learning (ResNet50 dan MobileNetV2) menggunakan TensorFlow/Keras.
11
-
12
- ## Fitur Utama
13
- - **Face Detection:** Menggunakan MediaPipe (BlazeFace) untuk mendeteksi area wajah.
14
- - **Undertone Classification:** Menggunakan model ResNet50 dan MobileNetV2 untuk memprediksi probabilitas undertone kulit ke dalam 3 kategori: `Cool`, `Neutral`, dan `Warm`.
15
- - **Upload & Camera Input:** Mendukung prediksi dari gambar yang diunggah pengguna maupun gambar yang diambil langsung melalui kamera web (webcam).
16
-
17
- ## Persyaratan (Requirements)
18
- Aplikasi ini dikembangkan dan direkomendasikan untuk dijalankan menggunakan **Python 3.11**.
19
-
20
- ## Instalasi dan Setup (Menggunakan Virtual Environment)
21
-
22
- Ikuti langkah-langkah berikut untuk mengatur lingkungan (environment) dan menjalankan aplikasi di komputer Anda.
23
-
24
- ### 1. Buat Virtual Environment (venv)
25
- Buka terminal (Command Prompt/PowerShell di Windows, atau Terminal di Mac/Linux), arahkan ke direktori proyek ini, lalu jalankan perintah berikut untuk membuat *virtual environment*:
26
-
27
- **Windows:**
28
- ```bash
29
- python -m venv venv
30
- ```
31
-
32
- **Mac/Linux:**
33
- ```bash
34
- python3.11 -m venv venv
35
- ```
36
-
37
- ### 2. Aktifkan Virtual Environment
38
- Setelah berhasil dibuat, *virtual environment* harus diaktifkan.
39
-
40
- **Windows (Command Prompt):**
41
- ```cmd
42
- venv\Scripts\activate.bat
43
- ```
44
-
45
- **Windows (PowerShell):**
46
- ```powershell
47
- .\venv\Scripts\Activate.ps1
48
- ```
49
-
50
- **Mac/Linux:**
51
- ```bash
52
- source venv/bin/activate
53
- ```
54
-
55
- *Catatan: Anda akan melihat tulisan `(venv)` di awal baris terminal Anda jika environment sudah berhasil aktif.*
56
-
57
- ### 3. Instalasi Library (Dependensi)
58
- Pastikan *virtual environment* masih aktif, lalu instal semua *library* yang dibutuhkan dengan menggunakan `pip`:
59
-
60
- ```bash
61
- pip install flask mediapipe opencv-python tensorflow
62
- ```
63
-
64
- ## Cara Menjalankan Aplikasi
65
-
66
- Setelah semua library berhasil diinstal, Anda dapat menjalankan server Flask lokal dengan cara mengeksekusi file `app.py`:
67
-
68
- ```bash
69
- python app.py
70
- ```
71
-
72
- Jika server berhasil berjalan, buka browser Anda dan kunjungi alamat berikut:
73
- ```text
74
- http://127.0.0.1:5000/
75
- ```
76
-
77
- ## Keterangan Kode (Struktur Proyek)
78
- - `app.py`: File utama aplikasi (backend) yang menggunakan Flask. Menangani konfigurasi rute web, upload file gambar, menangkap gambar dari webcam, dan menghubungkannya dengan logika model AI (`UnderToneAI`).
79
- - `UnderToneAI (di app.py)`: Kelas yang mengelola *loading* model klasifikasi `.h5`, mengunduh model Face Detector secara otomatis, serta melakukan pemotongan gambar wajah berdasarkan *bounding box* dari MediaPipe sebelum memprediksinya.
80
- - `templates/index.html`: File antarmuka pengguna (frontend) tempat pengguna dapat berinteraksi (mengunggah foto atau mengambil dari webcam).
81
- - `models/`: Folder tempat menyimpan model *machine learning* yang telah dilatih (`best_ResNet50.h5` dan `best_MobileNetV2.h5`) beserta detektor wajah MediaPipe.
82
- - `static/uploads/`: Folder sementara tempat gambar asli dan gambar *crop* wajah disimpan agar dapat dimuat kembali dan ditampilkan di UI.
83
-
84
- ## Catatan
85
- - Pastikan file model klasifikasi (`best_ResNet50.h5` dan `best_MobileNetV2.h5`) sudah diletakkan di dalam folder `models/` agar aplikasi tidak mengalami error saat inisialisasi.
86
- - Aplikasi akan otomatis mendownload model *Face Detector* dari MediaPipe (`blaze_face_short_range.tflite`) ke folder `models` pada saat pertama kali dijalankan, jadi pastikan Anda terkoneksi ke internet.
 
1
+ # Skin Undertone Classification
2
+
3
+ Aplikasi web berbasis Flask untuk mendeteksi dan mengklasifikasikan *skin undertone* (Cool, Neutral, atau Warm) dari wajah seseorang. Aplikasi ini menggunakan MediaPipe untuk mendeteksi wajah dan memotongnya (cropping) sebelum diproses oleh model Deep Learning (ResNet50 dan MobileNetV2) menggunakan TensorFlow/Keras.
4
+
5
+ ## Fitur Utama
6
+ - **Face Detection:** Menggunakan MediaPipe (BlazeFace) untuk mendeteksi area wajah.
7
+ - **Undertone Classification:** Menggunakan model ResNet50 dan MobileNetV2 untuk memprediksi probabilitas undertone kulit ke dalam 3 kategori: `Cool`, `Neutral`, dan `Warm`.
8
+ - **Upload & Camera Input:** Mendukung prediksi dari gambar yang diunggah pengguna maupun gambar yang diambil langsung melalui kamera web (webcam).
9
+
10
+ ## Persyaratan (Requirements)
11
+ Aplikasi ini dikembangkan dan direkomendasikan untuk dijalankan menggunakan **Python 3.11**.
12
+
13
+ ## Instalasi dan Setup (Menggunakan Virtual Environment)
14
+
15
+ Ikuti langkah-langkah berikut untuk mengatur lingkungan (environment) dan menjalankan aplikasi di komputer Anda.
16
+
17
+ ### 1. Buat Virtual Environment (venv)
18
+ Buka terminal (Command Prompt/PowerShell di Windows, atau Terminal di Mac/Linux), arahkan ke direktori proyek ini, lalu jalankan perintah berikut untuk membuat *virtual environment*:
19
+
20
+ **Windows:**
21
+ ```bash
22
+ python -m venv venv
23
+ ```
24
+
25
+ **Mac/Linux:**
26
+ ```bash
27
+ python3.11 -m venv venv
28
+ ```
29
+
30
+ ### 2. Aktifkan Virtual Environment
31
+ Setelah berhasil dibuat, *virtual environment* harus diaktifkan.
32
+
33
+ **Windows (Command Prompt):**
34
+ ```cmd
35
+ venv\Scripts\activate.bat
36
+ ```
37
+
38
+ **Windows (PowerShell):**
39
+ ```powershell
40
+ .\venv\Scripts\Activate.ps1
41
+ ```
42
+
43
+ **Mac/Linux:**
44
+ ```bash
45
+ source venv/bin/activate
46
+ ```
47
+
48
+ *Catatan: Anda akan melihat tulisan `(venv)` di awal baris terminal Anda jika environment sudah berhasil aktif.*
49
+
50
+ ### 3. Instalasi Library (Dependensi)
51
+ Pastikan *virtual environment* masih aktif, lalu instal semua *library* yang dibutuhkan dengan menggunakan `pip`:
52
+
53
+ ```bash
54
+ pip install flask mediapipe opencv-python tensorflow
55
+ ```
56
+
57
+ ## Cara Menjalankan Aplikasi
58
+
59
+ Setelah semua library berhasil diinstal, Anda dapat menjalankan server Flask lokal dengan cara mengeksekusi file `app.py`:
60
+
61
+ ```bash
62
+ python app.py
63
+ ```
64
+
65
+ Jika server berhasil berjalan, buka browser Anda dan kunjungi alamat berikut:
66
+ ```text
67
+ http://127.0.0.1:5000/
68
+ ```
69
+
70
+ ## Keterangan Kode (Struktur Proyek)
71
+ - `app.py`: File utama aplikasi (backend) yang menggunakan Flask. Menangani konfigurasi rute web, upload file gambar, menangkap gambar dari webcam, dan menghubungkannya dengan logika model AI (`UnderToneAI`).
72
+ - `UnderToneAI (di app.py)`: Kelas yang mengelola *loading* model klasifikasi `.h5`, mengunduh model Face Detector secara otomatis, serta melakukan pemotongan gambar wajah berdasarkan *bounding box* dari MediaPipe sebelum memprediksinya.
73
+ - `templates/index.html`: File antarmuka pengguna (frontend) tempat pengguna dapat berinteraksi (mengunggah foto atau mengambil dari webcam).
74
+ - `models/`: Folder tempat menyimpan model *machine learning* yang telah dilatih (`best_ResNet50.h5` dan `best_MobileNetV2.h5`) beserta detektor wajah MediaPipe.
75
+ - `static/uploads/`: Folder sementara tempat gambar asli dan gambar *crop* wajah disimpan agar dapat dimuat kembali dan ditampilkan di UI.
76
+
77
+ ## Catatan
78
+ - Pastikan file model klasifikasi (`best_ResNet50.h5` dan `best_MobileNetV2.h5`) sudah diletakkan di dalam folder `models/` agar aplikasi tidak mengalami error saat inisialisasi.
79
+ - Aplikasi akan otomatis mendownload model *Face Detector* dari MediaPipe (`blaze_face_short_range.tflite`) ke folder `models` pada saat pertama kali dijalankan, jadi pastikan Anda terkoneksi ke internet.
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,237 +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 _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)
 
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)
models/best_MobileNetV2.h5 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:409176b4f87badcc4ac61b2bcfbeb9e31c7d59f58e2711fcbc5316e6727446dd
3
- size 13350064
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54a5ba4759b56a43a3cb06619b6f0b57dd8beecf04bca9a74f69b2d5812ae51e
3
+ size 25587680
models/best_ResNet50.h5 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:86cd06a15463e420ef4de1b8eb5f31dbd8b33520365421c2df6089bdd81d449e
3
- size 101058000
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e00ccb91d5b001fd6162652e35e984cb5927e196239be8ef448061254400c48
3
+ size 216688264
static/uploads/Screenshot_2026-06-04_213003.png ADDED

Git LFS Details

  • SHA256: 2afaaa95ae3a20e99ea3ca24db69ed8d2d44a2a1adc7819497bbbe6ecbf276e6
  • Pointer size: 131 Bytes
  • Size of remote file: 136 kB
static/uploads/WhatsApp_Image_2026-06-04_at_21.19.01.jpeg ADDED
static/uploads/cam_20260604_213126.jpg ADDED
static/uploads/cam_20260708_163346.jpg ADDED
static/uploads/cam_20260708_163415.jpg ADDED
static/uploads/cam_20260708_163424.jpg ADDED
static/uploads/cam_20260708_163452.jpg ADDED
static/uploads/cam_20260708_163503.jpg ADDED
static/uploads/cam_20260708_163508.jpg ADDED
static/uploads/cam_20260708_163516.jpg ADDED
static/uploads/cam_20260708_163520.jpg ADDED
static/uploads/cam_20260708_163526.jpg ADDED
static/uploads/cam_20260708_163532.jpg ADDED
static/uploads/cam_20260708_163541.jpg ADDED
static/uploads/cam_20260708_163700.jpg ADDED
static/uploads/cam_20260708_163709.jpg ADDED
static/uploads/cam_20260708_163715.jpg ADDED
static/uploads/cam_20260708_163724.jpg ADDED
static/uploads/cam_20260708_163731.jpg ADDED
static/uploads/cam_20260708_163748.jpg ADDED
static/uploads/cam_20260708_163818.jpg ADDED
static/uploads/cam_20260708_163824.jpg ADDED
static/uploads/cam_20260708_163830.jpg ADDED
static/uploads/cam_20260708_163837.jpg ADDED
static/uploads/cam_20260708_163847.jpg ADDED
static/uploads/cam_20260709_084845.jpg ADDED
static/uploads/cam_20260709_085000.jpg ADDED
static/uploads/cam_20260709_085021.jpg ADDED
static/uploads/cam_20260709_085046.jpg ADDED
static/uploads/cam_20260709_085055.jpg ADDED
static/uploads/cam_20260709_085107.jpg ADDED
static/uploads/cam_20260709_085116.jpg ADDED
static/uploads/cam_20260709_085136.jpg ADDED
static/uploads/cam_20260709_085151.jpg ADDED
static/uploads/cam_20260709_085209.jpg ADDED
static/uploads/cam_20260709_085224.jpg ADDED
static/uploads/crop_Screenshot_2026-06-04_213003.png ADDED
static/uploads/crop_WhatsApp_Image_2026-06-04_at_21.19.01.jpeg ADDED
static/uploads/crop_cam_20260604_213126.jpg ADDED
static/uploads/crop_cam_20260708_163346.jpg ADDED
static/uploads/crop_cam_20260708_163415.jpg ADDED
static/uploads/crop_cam_20260708_163424.jpg ADDED