devluke commited on
Commit
df64439
Β·
verified Β·
1 Parent(s): e92a5db

Upload 12 files

Browse files
.dockerignore ADDED
@@ -0,0 +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
.gitattributes CHANGED
@@ -1,35 +1 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.h5 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environments
2
+ .env
3
+ .venv
4
+ env/
5
+ venv/
6
+ ENV/
7
+ env.bak/
8
+ venv.bak/
9
+
10
+ # Byte-compiled / optimized / DLL files
11
+ __pycache__/
12
+ *.py[cod]
13
+ *$py.class
14
+
15
+ # Uploads (ignore all files inside uploads except .gitkeep if it exists)
16
+ static/uploads/*
17
+ !static/uploads/.gitkeep
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/
25
+ .idea/
26
+ *.swp
27
+ *.swo
28
+ .DS_Store
29
+
30
+ # Virtualenv wrapper
31
+ .Python
32
+
33
+ # Distribution / packaging
34
+ build/
35
+ develop-eggs/
36
+ dist/
37
+ downloads/
38
+ eggs/
39
+ .eggs/
40
+ lib/
41
+ lib64/
42
+ parts/
43
+ sdist/
44
+ var/
45
+ wheels/
46
+ share/python-wheels/
47
+ *.egg-info/
48
+ .installed.cfg
49
+ *.egg
50
+
51
+ # Installer logs
52
+ pip-log.txt
53
+ pip-delete-this-directory.txt
54
+
55
+ # Jupyter Notebook
56
+ .ipynb_checkpoints
57
+
58
+ # Pytest / Coverage
59
+ .pytest_cache/
60
+ .coverage
61
+ htmlcov/
62
+
63
+ # Exclude large model
64
+ # models/best_ResNet50.h5
65
+ # models/best_MobileNetV2.h5
Dockerfile ADDED
@@ -0,0 +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
+ # 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,10 +1,79 @@
1
- ---
2
- title: Undertone Classification
3
- emoji: 🌍
4
- colorFrom: yellow
5
- colorTo: red
6
- sdk: docker
7
- pinned: false
8
- ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ app.run(debug=True, port=5000)
models/__init__.py ADDED
File without changes
models/best_MobileNetV2.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f39a5330f71361806dcb60d9d69de7d781cfcae3d89a1a2c42d52c42e573c4de
3
+ size 13775200
models/best_ResNet50.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:feb473b5e501f9a1f66ebaba11adc401315ddda5f08f7495ed8960191b1bee8c
3
+ size 217116584
requirements.txt ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.4.0
2
+ astunparse==1.6.3
3
+ blinker==1.9.0
4
+ certifi==2026.4.22
5
+ cffi==2.0.0
6
+ charset-normalizer==3.4.7
7
+ click==8.3.3
8
+ colorama==0.4.6
9
+ contourpy==1.3.3
10
+ cycler==0.12.1
11
+ Flask==3.1.3
12
+ flatbuffers==25.12.19
13
+ fonttools==4.62.1
14
+ gast==0.7.0
15
+ google-pasta==0.2.0
16
+ grpcio==1.80.0
17
+ h5py==3.14.0
18
+ idna==3.13
19
+ itsdangerous==2.2.0
20
+ Jinja2==3.1.6
21
+ keras==3.14.0
22
+ kiwisolver==1.5.0
23
+ libclang==18.1.1
24
+ markdown-it-py==4.0.0
25
+ MarkupSafe==3.0.3
26
+ matplotlib==3.10.9
27
+ mdurl==0.1.2
28
+ mediapipe==0.10.33
29
+ ml_dtypes==0.5.4
30
+ namex==0.1.0
31
+ numpy==2.4.4
32
+ opencv-contrib-python==4.13.0.92
33
+ opencv-python==4.13.0.92
34
+ opt_einsum==3.4.0
35
+ optree==0.19.0
36
+ packaging==26.2
37
+ pillow==12.2.0
38
+ protobuf==7.34.1
39
+ pycparser==3.0
40
+ Pygments==2.20.0
41
+ pyparsing==3.3.2
42
+ python-dateutil==2.9.0.post0
43
+ requests==2.33.1
44
+ rich==15.0.0
45
+ six==1.17.0
46
+ sounddevice==0.5.5
47
+ tensorflow==2.21.0
48
+ termcolor==3.3.0
49
+ typing_extensions==4.15.0
50
+ urllib3==2.6.3
51
+ Werkzeug==3.1.8
52
+ wrapt==2.1.2
static/uploads/.gitkeep ADDED
File without changes
templates/index.html ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta charset="UTF-8">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+ <title>Undertone Classification Dashboard</title>
8
+ <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
9
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
10
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
11
+
12
+ <style>
13
+ :root {
14
+ --primary: #1d4ed8;
15
+ --primary-light: #3b82f6;
16
+ --primary-pale: #eff6ff;
17
+ --dark-text: #0f172a;
18
+ --muted-text: #64748b;
19
+ --border: rgba(29, 78, 216, 0.15);
20
+ --card-bg: #ffffff;
21
+ --cool-color: #818cf8;
22
+ --neutral-color: #fb923c;
23
+ --warm-color: #f59e0b;
24
+ }
25
+
26
+ body {
27
+ background: linear-gradient(160deg, #eff6ff 0%, #f8fafc 60%, #e0f2fe 100%);
28
+ color: var(--dark-text);
29
+ font-family: 'Inter', sans-serif;
30
+ min-height: 100vh;
31
+ }
32
+
33
+ /* ── Cards ── */
34
+ .glass-card {
35
+ background: var(--card-bg);
36
+ border: 1px solid var(--border);
37
+ border-radius: 24px;
38
+ box-shadow: 0 4px 24px rgba(29, 78, 216, 0.08), 0 1px 4px rgba(0, 0, 0, 0.04);
39
+ }
40
+
41
+ /* ── Buttons ── */
42
+ .btn-gradient-primary {
43
+ background: linear-gradient(135deg, #2563eb, #1d4ed8);
44
+ color: #fff;
45
+ border: none;
46
+ border-radius: 12px;
47
+ transition: .25s;
48
+ }
49
+
50
+ .btn-gradient-success {
51
+ background: linear-gradient(135deg, #0ea5e9, #0284c7);
52
+ color: #fff;
53
+ border: none;
54
+ border-radius: 12px;
55
+ transition: .25s;
56
+ }
57
+
58
+ .btn-gradient-primary:hover,
59
+ .btn-gradient-success:hover {
60
+ transform: translateY(-2px);
61
+ color: #fff;
62
+ box-shadow: 0 8px 24px rgba(29, 78, 216, .3);
63
+ }
64
+
65
+ /* ── Video ── */
66
+ #video {
67
+ border-radius: 14px;
68
+ width: 100%;
69
+ background: #000;
70
+ border: 2px solid var(--border);
71
+ }
72
+
73
+ /* ── Nav tabs ── */
74
+ .nav-tabs {
75
+ border-bottom: 2px solid var(--border);
76
+ }
77
+
78
+ .nav-tabs .nav-link {
79
+ color: var(--muted-text);
80
+ border: none;
81
+ font-weight: 600;
82
+ padding: 12px 20px;
83
+ border-radius: 10px 10px 0 0;
84
+ }
85
+
86
+ .nav-tabs .nav-link.active {
87
+ background: var(--primary-pale);
88
+ color: var(--primary);
89
+ border-bottom: 3px solid var(--primary);
90
+ }
91
+
92
+ /* ── Form control ── */
93
+ .form-control {
94
+ background: #f8fafc;
95
+ border: 1px solid #cbd5e1;
96
+ color: var(--dark-text);
97
+ }
98
+
99
+ .form-control:focus {
100
+ border-color: var(--primary-light);
101
+ box-shadow: 0 0 0 3px rgba(59, 130, 246, .15);
102
+ }
103
+
104
+ /* ── Section headings ── */
105
+ h1,
106
+ h5 {
107
+ color: var(--dark-text);
108
+ }
109
+
110
+ .text-primary {
111
+ color: var(--primary) !important;
112
+ }
113
+
114
+ .text-secondary {
115
+ color: var(--muted-text) !important;
116
+ }
117
+
118
+ .text-muted {
119
+ color: #94a3b8 !important;
120
+ }
121
+
122
+ /* ── Spinner ── */
123
+ .loading-overlay {
124
+ display: flex;
125
+ flex-direction: column;
126
+ align-items: center;
127
+ justify-content: center;
128
+ }
129
+
130
+ .spinner-border {
131
+ width: 3rem;
132
+ height: 3rem;
133
+ color: var(--primary);
134
+ }
135
+
136
+ /* ── Undertone badge ── */
137
+ .undertone-badge {
138
+ display: inline-flex;
139
+ align-items: center;
140
+ gap: 10px;
141
+ padding: 10px 22px;
142
+ border-radius: 50px;
143
+ font-size: 1.4rem;
144
+ font-weight: 800;
145
+ letter-spacing: .03em;
146
+ animation: fadeUp .5s ease both;
147
+ }
148
+
149
+ .badge-cool {
150
+ background: linear-gradient(135deg, #312e81, #4338ca);
151
+ color: #c7d2fe;
152
+ box-shadow: 0 0 28px rgba(99, 102, 241, .3);
153
+ }
154
+
155
+ .badge-neutral {
156
+ background: linear-gradient(135deg, #7c2d12, #c2410c);
157
+ color: #fed7aa;
158
+ box-shadow: 0 0 28px rgba(251, 146, 60, .3);
159
+ }
160
+
161
+ .badge-warm {
162
+ background: linear-gradient(135deg, #78350f, #d97706);
163
+ color: #fef3c7;
164
+ box-shadow: 0 0 28px rgba(245, 158, 11, .3);
165
+ }
166
+
167
+ .swatch {
168
+ width: 22px;
169
+ height: 22px;
170
+ border-radius: 50%;
171
+ border: 2px solid rgba(255, 255, 255, .4);
172
+ }
173
+
174
+ /* ── Crop image ── */
175
+ .crop-preview {
176
+ width: 110px;
177
+ height: 110px;
178
+ border-radius: 50%;
179
+ object-fit: cover;
180
+ border: 4px solid #fff;
181
+ box-shadow: 0 0 0 4px var(--ring-color, #3b82f6), 0 4px 20px rgba(59, 130, 246, .25);
182
+ transition: box-shadow .4s;
183
+ }
184
+
185
+ /* ── Agreement pill ── */
186
+ .agree-pill {
187
+ display: inline-flex;
188
+ align-items: center;
189
+ gap: 6px;
190
+ font-size: .78rem;
191
+ font-weight: 700;
192
+ padding: 4px 14px;
193
+ border-radius: 50px;
194
+ text-transform: uppercase;
195
+ letter-spacing: .05em;
196
+ }
197
+
198
+ .agree-yes {
199
+ background: #f0fdf4;
200
+ color: #16a34a;
201
+ border: 1px solid #bbf7d0;
202
+ }
203
+
204
+ .agree-no {
205
+ background: #fef2f2;
206
+ color: #dc2626;
207
+ border: 1px solid #fecaca;
208
+ }
209
+
210
+ /* ── Radial ring ── */
211
+ .ring-wrap {
212
+ position: relative;
213
+ width: 80px;
214
+ height: 80px;
215
+ flex-shrink: 0;
216
+ }
217
+
218
+ .ring-wrap svg {
219
+ transform: rotate(-90deg);
220
+ }
221
+
222
+ .ring-bg {
223
+ fill: none;
224
+ stroke: #e2e8f0;
225
+ stroke-width: 7;
226
+ }
227
+
228
+ .ring-fill {
229
+ fill: none;
230
+ stroke-width: 7;
231
+ stroke-linecap: round;
232
+ transition: stroke-dashoffset 1s ease;
233
+ }
234
+
235
+ .ring-label {
236
+ position: absolute;
237
+ inset: 0;
238
+ display: flex;
239
+ flex-direction: column;
240
+ align-items: center;
241
+ justify-content: center;
242
+ font-weight: 800;
243
+ font-size: .85rem;
244
+ color: var(--dark-text);
245
+ }
246
+
247
+ .ring-sub {
248
+ font-size: .6rem;
249
+ font-weight: 500;
250
+ color: var(--muted-text);
251
+ margin-top: 1px;
252
+ }
253
+
254
+ /* ── Model score blocks ── */
255
+ .model-block {
256
+ border-radius: 16px;
257
+ padding: 16px 18px;
258
+ background: #f8fafc;
259
+ border: 1px solid #e2e8f0;
260
+ }
261
+
262
+ .model-title {
263
+ font-size: .7rem;
264
+ font-weight: 700;
265
+ text-transform: uppercase;
266
+ letter-spacing: .1em;
267
+ color: var(--primary);
268
+ margin-bottom: 12px;
269
+ }
270
+
271
+ .bar-track {
272
+ height: 8px;
273
+ background: #e2e8f0;
274
+ border-radius: 4px;
275
+ overflow: hidden;
276
+ margin-top: 5px;
277
+ }
278
+
279
+ .bar-fill {
280
+ height: 100%;
281
+ border-radius: 4px;
282
+ transition: width 1s ease;
283
+ }
284
+
285
+ .bar-cool {
286
+ background: linear-gradient(90deg, #4f46e5, #818cf8);
287
+ }
288
+
289
+ .bar-neutral {
290
+ background: linear-gradient(90deg, #c2410c, #fb923c);
291
+ }
292
+
293
+ .bar-warm {
294
+ background: linear-gradient(90deg, #b45309, #f59e0b);
295
+ }
296
+
297
+ /* ── Score label text ── */
298
+ .score-row span:first-child {
299
+ color: var(--dark-text);
300
+ }
301
+
302
+ .score-row span:last-child {
303
+ color: var(--primary);
304
+ }
305
+
306
+ /* ── Palette ── */
307
+ .palette-title {
308
+ font-size: .7rem;
309
+ font-weight: 700;
310
+ text-transform: uppercase;
311
+ letter-spacing: .1em;
312
+ color: var(--primary);
313
+ margin-bottom: 10px;
314
+ }
315
+
316
+ .palette-chip {
317
+ width: 36px;
318
+ height: 36px;
319
+ border-radius: 50%;
320
+ border: 2px solid rgba(0, 0, 0, .1);
321
+ cursor: default;
322
+ transition: transform .2s;
323
+ position: relative;
324
+ }
325
+
326
+ .palette-chip:hover {
327
+ transform: scale(1.2);
328
+ z-index: 2;
329
+ }
330
+
331
+ .palette-chip[title]:hover::after {
332
+ content: attr(title);
333
+ position: absolute;
334
+ bottom: calc(100% + 6px);
335
+ left: 50%;
336
+ transform: translateX(-50%);
337
+ background: var(--dark-text);
338
+ color: #fff;
339
+ font-size: .65rem;
340
+ white-space: nowrap;
341
+ padding: 3px 8px;
342
+ border-radius: 6px;
343
+ pointer-events: none;
344
+ }
345
+
346
+ /* ── Placeholder ── */
347
+ #placeholder i {
348
+ color: #93c5fd !important;
349
+ }
350
+
351
+ /* ── Animations ── */
352
+ @keyframes fadeUp {
353
+ from {
354
+ opacity: 0;
355
+ transform: translateY(12px)
356
+ }
357
+
358
+ to {
359
+ opacity: 1;
360
+ transform: none
361
+ }
362
+ }
363
+
364
+ .result-anim {
365
+ animation: fadeUp .45s ease both;
366
+ }
367
+
368
+ .result-anim:nth-child(2) {
369
+ animation-delay: .08s
370
+ }
371
+
372
+ .result-anim:nth-child(3) {
373
+ animation-delay: .16s
374
+ }
375
+
376
+ .result-anim:nth-child(4) {
377
+ animation-delay: .24s
378
+ }
379
+ </style>
380
+ </head>
381
+
382
+ <body>
383
+
384
+ <div class="container py-5">
385
+ <header class="text-center mb-5">
386
+ <h1 class="fw-bold mb-2"><i class="fas fa-microchip me-2 text-primary"></i>Undertone Classification
387
+ Dashboard</h1>
388
+ <p class="text-secondary">Artificial Intelligence System Powered by ResNet50 & MobileNetV2</p>
389
+ </header>
390
+
391
+ <div class="row g-4">
392
+ <div class="col-lg-6">
393
+ <div class="glass-card p-4 h-100">
394
+ <h5 class="mb-4"><i class="fas fa-camera me-2 text-primary"></i>Data Input Source</h5>
395
+
396
+ <ul class="nav nav-tabs mb-4" id="inputTab" role="tablist">
397
+ <li class="nav-item" role="presentation">
398
+ <button class="nav-link active" id="gallery-tab" data-bs-toggle="tab"
399
+ data-bs-target="#galleryTab" type="button" role="tab">
400
+ <i class="fas fa-upload me-2"></i>Gallery
401
+ </button>
402
+ </li>
403
+ <li class="nav-item" role="presentation">
404
+ <button class="nav-link" id="camera-tab" data-bs-toggle="tab" data-bs-target="#cameraTab"
405
+ type="button" role="tab">
406
+ <i class="fas fa-video me-2"></i>Live Session
407
+ </button>
408
+ </li>
409
+ </ul>
410
+
411
+ <div class="tab-content" id="inputTabContent">
412
+ <div class="tab-pane fade show active" id="galleryTab" role="tabpanel">
413
+ <div class="mb-4">
414
+ <label class="form-label small fw-semibold" style="color:var(--muted-text)">Select
415
+ Portrait Image</label>
416
+ <input type="file" id="fileInput" class="form-control">
417
+ </div>
418
+ <button id="btnGallery" onclick="uploadFile()"
419
+ class="btn btn-gradient-primary w-100 py-3 fw-bold">
420
+ <i class="fas fa-search me-2"></i>ANALYZE SELECTION
421
+ </button>
422
+ </div>
423
+
424
+ <div class="tab-pane fade" id="cameraTab" role="tabpanel">
425
+ <div class="ratio ratio-4x3 mb-3 overflow-hidden rounded">
426
+ <video id="video" autoplay playsinline></video>
427
+ </div>
428
+ <button id="btnCamera" onclick="captureCamera()"
429
+ class="btn btn-gradient-success w-100 py-3 fw-bold">
430
+ <i class="fas fa-bolt me-2"></i>CAPTURE & PROCESS
431
+ </button>
432
+ <canvas id="canvas" style="display:none;"></canvas>
433
+ </div>
434
+ </div>
435
+ </div>
436
+ </div>
437
+
438
+ <div class="col-lg-6" id="output-wrapper">
439
+ <div id="loadingSpinner" class="glass-card p-5 h-100 d-none loading-overlay">
440
+ <div class="spinner-border mb-3" role="status">
441
+ <span class="visually-hidden">Loading...</span>
442
+ </div>
443
+ <h5 class="text-primary">Processing Image...</h5>
444
+ <p class="text-muted small">Running Deep Learning Inference</p>
445
+ </div>
446
+
447
+ <div class="glass-card p-4 d-none" id="resultPanel">
448
+
449
+ <!-- β‘  Hero: crop + badge -->
450
+ <div class="d-flex align-items-center gap-3 mb-4 result-anim">
451
+ <img id="cropImg" class="crop-preview" src="" alt="Face crop">
452
+ <div>
453
+ <p class="text-secondary small mb-1"
454
+ style="font-size:.72rem;letter-spacing:.08em;text-transform:uppercase">Undertone
455
+ Detected</p>
456
+ <div id="resBadge" class="undertone-badge mb-2">β€”</div>
457
+ <div id="agreepill" class="agree-pill agree-yes">
458
+ <i class="fas fa-check-circle"></i> <span id="agreeText">Models agree</span>
459
+ </div>
460
+ </div>
461
+ </div>
462
+
463
+ <!-- β‘‘ Radial rings + bars -->
464
+ <div class="row g-3 mb-3">
465
+ <div class="col-12 result-anim">
466
+ <div class="model-block">
467
+ <div class="model-title"><i class="fas fa-brain me-1"></i> ResNet50</div>
468
+ <div id="resnetScores"></div>
469
+ </div>
470
+ </div>
471
+ <div class="col-12 result-anim">
472
+ <div class="model-block">
473
+ <div class="model-title"><i class="fas fa-microchip me-1"></i> MobileNetV2</div>
474
+ <div id="mobilenetScores"></div>
475
+ </div>
476
+ </div>
477
+ </div>
478
+
479
+ <!-- β‘’ Palette recommendation -->
480
+ <div class="model-block result-anim" id="paletteBlock">
481
+ <div class="palette-title"><i class="fas fa-palette me-1"></i> Recommended Colour Palette</div>
482
+ <div id="paletteChips" class="d-flex flex-wrap gap-2"></div>
483
+ <p id="paletteDesc" class="text-secondary mt-2 mb-0" style="font-size:.78rem"></p>
484
+ </div>
485
+
486
+ </div>
487
+
488
+ <div id="placeholder"
489
+ class="glass-card p-5 h-100 d-flex align-items-center justify-content-center text-center">
490
+ <div>
491
+ <i class="fas fa-hourglass-start fa-4x mb-4 text-secondary opacity-20"></i>
492
+ <h5 class="text-secondary">Ready for Analysis</h5>
493
+ <p class="text-muted small">Please provide an input image to start.</p>
494
+ </div>
495
+ </div>
496
+ </div>
497
+ </div>
498
+ </div>
499
+
500
+ <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
501
+
502
+ <script>
503
+ const video = document.getElementById('video');
504
+ const canvas = document.getElementById('canvas');
505
+
506
+ // ── Palette data per undertone ──────────────────────────────────────
507
+ const PALETTES = {
508
+ cool: {
509
+ swatch: '#818cf8',
510
+ ringColor: '#6366f1',
511
+ label: 'Cool',
512
+ colors: [
513
+ { hex: '#7c3aed', name: 'Violet' },
514
+ { hex: '#2563eb', name: 'Royal Blue' },
515
+ { hex: '#0e7490', name: 'Teal' },
516
+ { hex: '#be185d', name: 'Fuchsia' },
517
+ { hex: '#374151', name: 'Charcoal' },
518
+ { hex: '#e0e7ff', name: 'Lavender' },
519
+ { hex: '#f0fdf4', name: 'Mint White' },
520
+ { hex: '#c7d2fe', name: 'Periwinkle' },
521
+ ],
522
+ desc: 'Cool undertones suit jewel tones, icy blues, purples & true whites. Avoid yellow-based oranges.'
523
+ },
524
+ neutral: {
525
+ swatch: '#fb923c',
526
+ ringColor: '#f97316',
527
+ label: 'Neutral',
528
+ colors: [
529
+ { hex: '#92400e', name: 'Caramel' },
530
+ { hex: '#b45309', name: 'Amber' },
531
+ { hex: '#4f46e5', name: 'Indigo' },
532
+ { hex: '#065f46', name: 'Forest Green' },
533
+ { hex: '#be123c', name: 'Rose Red' },
534
+ { hex: '#d4a27f', name: 'Nude Beige' },
535
+ { hex: '#6b7280', name: 'Cool Grey' },
536
+ { hex: '#fef3c7', name: 'Cream' },
537
+ ],
538
+ desc: 'Neutral undertones are the most versatile β€” warm & cool tones both work. Earthy nudes and balanced jewels shine.'
539
+ },
540
+ warm: {
541
+ swatch: '#f59e0b',
542
+ ringColor: '#d97706',
543
+ label: 'Warm',
544
+ colors: [
545
+ { hex: '#b45309', name: 'Golden Brown' },
546
+ { hex: '#c2410c', name: 'Burnt Orange' },
547
+ { hex: '#a16207', name: 'Mustard' },
548
+ { hex: '#166534', name: 'Olive Green' },
549
+ { hex: '#7c2d12', name: 'Terracotta' },
550
+ { hex: '#fde68a', name: 'Warm Yellow' },
551
+ { hex: '#fca5a5', name: 'Peach' },
552
+ { hex: '#f9a8d4', name: 'Coral Pink' },
553
+ ],
554
+ desc: 'Warm undertones glow in earthy oranges, golds, browns & warm greens. Avoid icy or ashy tones.'
555
+ }
556
+ };
557
+
558
+ // ── Camera Init ─────────────────────────────────────────────────────
559
+ document.getElementById('camera-tab').addEventListener('shown.bs.tab', () => {
560
+ if (!video.srcObject)
561
+ navigator.mediaDevices.getUserMedia({ video: true }).then(s => video.srcObject = s);
562
+ });
563
+
564
+ // ── Loading toggle ──────────────────────────────────────────────────
565
+ function toggleLoading(show) {
566
+ const spinner = document.getElementById('loadingSpinner');
567
+ const placeholder = document.getElementById('placeholder');
568
+ const resultPanel = document.getElementById('resultPanel');
569
+ const btnGallery = document.getElementById('btnGallery');
570
+ const btnCamera = document.getElementById('btnCamera');
571
+ if (show) {
572
+ spinner.classList.remove('d-none');
573
+ placeholder.classList.add('d-none');
574
+ resultPanel.classList.add('d-none');
575
+ btnGallery.disabled = btnCamera.disabled = true;
576
+ } else {
577
+ spinner.classList.add('d-none');
578
+ btnGallery.disabled = btnCamera.disabled = false;
579
+ }
580
+ }
581
+
582
+ // ── Score bars ──────────────────────────────────────────────────────
583
+ function createScoreUI(scores, containerId) {
584
+ const container = document.getElementById(containerId);
585
+ container.innerHTML = '';
586
+ Object.entries(scores).forEach(([label, score]) => {
587
+ const pct = (score * 100).toFixed(1);
588
+ const barClass = `bar-${label.toLowerCase()}`;
589
+ container.innerHTML += `
590
+ <div class="mb-2">
591
+ <div class="d-flex justify-content-between align-items-center mb-1">
592
+ <span style="font-size:.8rem;font-weight:600;color:#334155">${label}</span>
593
+ <span style="font-size:.78rem;font-weight:700;color:#1d4ed8">${pct}%</span>
594
+ </div>
595
+ <div class="bar-track">
596
+ <div class="bar-fill ${barClass}" style="width:0%" data-target="${pct}%"></div>
597
+ </div>
598
+ </div>`;
599
+ });
600
+ // Animate bars after paint
601
+ requestAnimationFrame(() => requestAnimationFrame(() => {
602
+ container.querySelectorAll('.bar-fill').forEach(el => {
603
+ el.style.width = el.dataset.target;
604
+ });
605
+ }));
606
+ }
607
+
608
+ // ── Main result render ──────────────────────────────────────────────
609
+ function handleResponse(data) {
610
+ toggleLoading(false);
611
+
612
+ const resLabel = data.results.resnet.label; // e.g. 'cool'
613
+ const mobLabel = data.results.mobilenet.label; // e.g. 'warm'
614
+ const agree = resLabel === mobLabel;
615
+ const palette = PALETTES[resLabel] || PALETTES['neutral'];
616
+ const displayLabel = palette.label; // Title-case: 'Cool'
617
+
618
+ // Crop image + ring glow colour
619
+ const cropImg = document.getElementById('cropImg');
620
+ cropImg.src = `/static/uploads/${data.crop}`;
621
+ cropImg.style.setProperty('--ring-color', palette.ringColor);
622
+ cropImg.style.boxShadow = `0 0 0 4px ${palette.ringColor}, 0 0 30px ${palette.ringColor}55`;
623
+
624
+ // Badge
625
+ const badge = document.getElementById('resBadge');
626
+ badge.className = `undertone-badge badge-${resLabel}`;
627
+ badge.innerHTML = `<span class="swatch" style="background:${palette.swatch}"></span>${displayLabel}`;
628
+
629
+ // Agreement pill
630
+ const pill = document.getElementById('agreepill');
631
+ const agreeText = document.getElementById('agreeText');
632
+ if (agree) {
633
+ pill.className = 'agree-pill agree-yes';
634
+ pill.querySelector('i').className = 'fas fa-check-circle';
635
+ agreeText.textContent = 'Both models agree';
636
+ } else {
637
+ pill.className = 'agree-pill agree-no';
638
+ pill.querySelector('i').className = 'fas fa-exclamation-circle';
639
+ const mobDisplay = (PALETTES[mobLabel] || PALETTES['neutral']).label;
640
+ agreeText.textContent = `ResNet: ${displayLabel} Β· MobileNet: ${mobDisplay}`;
641
+ }
642
+
643
+ // Score bars
644
+ createScoreUI(data.results.resnet.scores, 'resnetScores');
645
+ createScoreUI(data.results.mobilenet.scores, 'mobilenetScores');
646
+
647
+ // Palette chips
648
+ const chips = document.getElementById('paletteChips');
649
+ chips.innerHTML = palette.colors.map(c =>
650
+ `<div class="palette-chip" style="background:${c.hex}" title="${c.name}"></div>`
651
+ ).join('');
652
+ document.getElementById('paletteDesc').textContent = palette.desc;
653
+
654
+ document.getElementById('resultPanel').classList.remove('d-none');
655
+ }
656
+
657
+ // ── Upload ──────────────────────────────────────────────────────────
658
+ async function uploadFile() {
659
+ const file = document.getElementById('fileInput').files[0];
660
+ if (!file) return alert('Select an image first');
661
+ toggleLoading(true);
662
+ const fd = new FormData();
663
+ fd.append('file', file);
664
+ try {
665
+ const res = await fetch('/predict', { method: 'POST', body: fd });
666
+ const data = await res.json();
667
+ if (res.ok) handleResponse(data);
668
+ else { alert(data.error); toggleLoading(false); document.getElementById('placeholder').classList.remove('d-none'); }
669
+ } catch { alert('Server error'); toggleLoading(false); }
670
+ }
671
+
672
+ // ── Camera capture ──────────────────────────────────────────────────
673
+ async function captureCamera() {
674
+ canvas.width = video.videoWidth;
675
+ canvas.height = video.videoHeight;
676
+ canvas.getContext('2d').drawImage(video, 0, 0);
677
+ toggleLoading(true);
678
+ try {
679
+ const res = await fetch('/predict', {
680
+ method: 'POST',
681
+ headers: { 'Content-Type': 'application/json' },
682
+ body: JSON.stringify({ image: canvas.toDataURL('image/jpeg') })
683
+ });
684
+ const data = await res.json();
685
+ if (res.ok) handleResponse(data);
686
+ else { alert(data.error); toggleLoading(false); document.getElementById('placeholder').classList.remove('d-none'); }
687
+ } catch { alert('Server error'); toggleLoading(false); }
688
+ }
689
+ </script>
690
+ </body>
691
+
692
+ </html>