Spaces:
Runtime error
Runtime error
Upload 87 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +27 -27
- .gitattributes +2 -1
- .gitignore +1 -1
- Dockerfile +69 -97
- README.md +79 -86
- app.py +236 -236
- models/best_MobileNetV2.h5 +2 -2
- models/best_ResNet50.h5 +2 -2
- static/uploads/Screenshot_2026-06-04_213003.png +3 -0
- static/uploads/WhatsApp_Image_2026-06-04_at_21.19.01.jpeg +0 -0
- static/uploads/cam_20260604_213126.jpg +0 -0
- static/uploads/cam_20260708_163346.jpg +0 -0
- static/uploads/cam_20260708_163415.jpg +0 -0
- static/uploads/cam_20260708_163424.jpg +0 -0
- static/uploads/cam_20260708_163452.jpg +0 -0
- static/uploads/cam_20260708_163503.jpg +0 -0
- static/uploads/cam_20260708_163508.jpg +0 -0
- static/uploads/cam_20260708_163516.jpg +0 -0
- static/uploads/cam_20260708_163520.jpg +0 -0
- static/uploads/cam_20260708_163526.jpg +0 -0
- static/uploads/cam_20260708_163532.jpg +0 -0
- static/uploads/cam_20260708_163541.jpg +0 -0
- static/uploads/cam_20260708_163700.jpg +0 -0
- static/uploads/cam_20260708_163709.jpg +0 -0
- static/uploads/cam_20260708_163715.jpg +0 -0
- static/uploads/cam_20260708_163724.jpg +0 -0
- static/uploads/cam_20260708_163731.jpg +0 -0
- static/uploads/cam_20260708_163748.jpg +0 -0
- static/uploads/cam_20260708_163818.jpg +0 -0
- static/uploads/cam_20260708_163824.jpg +0 -0
- static/uploads/cam_20260708_163830.jpg +0 -0
- static/uploads/cam_20260708_163837.jpg +0 -0
- static/uploads/cam_20260708_163847.jpg +0 -0
- static/uploads/cam_20260709_084845.jpg +0 -0
- static/uploads/cam_20260709_085000.jpg +0 -0
- static/uploads/cam_20260709_085021.jpg +0 -0
- static/uploads/cam_20260709_085046.jpg +0 -0
- static/uploads/cam_20260709_085055.jpg +0 -0
- static/uploads/cam_20260709_085107.jpg +0 -0
- static/uploads/cam_20260709_085116.jpg +0 -0
- static/uploads/cam_20260709_085136.jpg +0 -0
- static/uploads/cam_20260709_085151.jpg +0 -0
- static/uploads/cam_20260709_085209.jpg +0 -0
- static/uploads/cam_20260709_085224.jpg +0 -0
- static/uploads/crop_Screenshot_2026-06-04_213003.png +0 -0
- static/uploads/crop_WhatsApp_Image_2026-06-04_at_21.19.01.jpeg +0 -0
- static/uploads/crop_cam_20260604_213126.jpg +0 -0
- static/uploads/crop_cam_20260708_163346.jpg +0 -0
- static/uploads/crop_cam_20260708_163415.jpg +0 -0
- 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 |
-
#
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
libgl1 \
|
| 13 |
-
libglib2.0-0 \
|
| 14 |
-
libgomp1 \
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
#
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
#
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
#
|
| 58 |
-
#
|
| 59 |
-
#
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
#
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
# 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 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
-
|
| 16 |
-
|
| 17 |
-
##
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
```
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
```
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
```
|
| 47 |
-
|
| 48 |
-
``
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
``
|
| 52 |
-
|
| 53 |
-
```
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
##
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
```
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
``
|
| 74 |
-
|
| 75 |
-
``
|
| 76 |
-
|
| 77 |
-
##
|
| 78 |
-
-
|
| 79 |
-
-
|
| 80 |
-
- `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:
|
| 3 |
-
size
|
|
|
|
| 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:
|
| 3 |
-
size
|
|
|
|
| 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
|
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
|