3v324v23 commited on
Commit
318219d
·
0 Parent(s):

Add application file

Browse files
Files changed (7) hide show
  1. .gitattributes +35 -0
  2. .gitignore +216 -0
  3. README.md +62 -0
  4. app.py +418 -0
  5. face_shape_model.pkl +3 -0
  6. label_encoder_rf.pkl +3 -0
  7. requirements.txt +6 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
.gitignore ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+
204
+ # Ruff stuff:
205
+ .ruff_cache/
206
+
207
+ # PyPI configuration file
208
+ .pypirc
209
+
210
+ # Marimo
211
+ marimo/_static/
212
+ marimo/_lsp/
213
+ __marimo__/
214
+
215
+ # Streamlit
216
+ .streamlit/secrets.toml
README.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: AIFaceShapeDetector
3
+ emoji: ⚡
4
+ colorFrom: blue
5
+ colorTo: gray
6
+ sdk: gradio
7
+ sdk_version: 6.5.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: cc-by-nc-4.0
11
+ short_description: Smple Face Shape Detection using Mediapipe and ML
12
+ ---
13
+
14
+ ## AI Face Shape Detector (Hugging Face Space)
15
+
16
+ Upload a front-facing photo (or use your webcam) and this Space predicts your **face shape** and shows a **MediaPipe face-mesh overlay** plus **confidence scores**.
17
+
18
+ Full app available at [attractivenesstest.com/face_shape](https://attractivenesstest.com/face_shape).
19
+
20
+ ### Supported face shapes
21
+
22
+ - **Oval**
23
+ - **Round**
24
+ - **Square**
25
+ - **Heart**
26
+ - **Oblong**
27
+
28
+ ### How it works (from `app.py`)
29
+
30
+ - **Face landmark extraction**: Uses **MediaPipe Face Mesh** (up to **478 landmarks**) to detect a single face.
31
+ - **Landmark normalization**: Centers landmarks using the eye/iris center, applies roll correction, and scales by inter-eye distance.
32
+ - **Classification**: Flattens normalized landmark coordinates and runs a **pickled scikit-learn classifier** (loaded from `face_shape_model.pkl`) with a label encoder (`label_encoder_rf.pkl`).
33
+ - **Outputs**:
34
+ - An image with a face mesh/contour overlay
35
+ - A formatted result card (shape + description + styling tip)
36
+ - Per-class confidence scores
37
+
38
+ ### Tips for best results
39
+
40
+ - Use a **front-facing** photo with good lighting
41
+ - Ensure your **entire face** is visible
42
+ - Remove glasses if possible
43
+ - Avoid tilting your head
44
+
45
+ ### Run locally
46
+
47
+ ```bash
48
+ python -m venv .venv
49
+ source .venv/bin/activate
50
+ pip install -r requirements.txt
51
+ python app.py
52
+ ```
53
+
54
+ Then open the Gradio URL printed in your terminal.
55
+
56
+ ### Notes / limitations
57
+
58
+ - This demo expects **one clear, visible face** in the image (`max_num_faces=1`).
59
+ - If no face is detected, the app will return an error message asking for a clearer photo.
60
+ - Uploaded images are processed in-memory by the app; the code does not intentionally save uploads to disk.
61
+
62
+ ---
app.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Face Shape Detection - Hugging Face Space App
3
+ Uses MediaPipe for face mesh extraction and a trained ML model for classification.
4
+ """
5
+
6
+ import cv2
7
+ import mediapipe as mp
8
+ import numpy as np
9
+ import pickle
10
+ import gradio as gr
11
+ from pathlib import Path
12
+ from PIL import Image
13
+
14
+ # Paths to model files
15
+ PROJECT_DIR = Path(__file__).parent
16
+ MODEL_FILE = PROJECT_DIR / 'face_shape_model.pkl'
17
+ LABEL_ENCODER_FILE = PROJECT_DIR / 'label_encoder_rf.pkl'
18
+
19
+ # Face shape descriptions for user-friendly output
20
+ FACE_SHAPE_INFO = {
21
+ "oval": {
22
+ "emoji": "🥚",
23
+ "description": "Balanced proportions with a slightly narrower forehead and jaw. Often considered the most versatile face shape.",
24
+ "tips": "Most hairstyles and glasses work well with oval faces."
25
+ },
26
+ "round": {
27
+ "emoji": "🌕",
28
+ "description": "Equal width and length with soft, curved lines. Full cheeks and a rounded chin.",
29
+ "tips": "Angular frames and layered hairstyles can add definition."
30
+ },
31
+ "square": {
32
+ "emoji": "⬛",
33
+ "description": "Strong, angular jawline with forehead and jaw of similar width.",
34
+ "tips": "Round or oval glasses and soft, layered hairstyles complement this shape."
35
+ },
36
+ "heart": {
37
+ "emoji": "❤️",
38
+ "description": "Wider forehead tapering to a narrower chin, often with prominent cheekbones.",
39
+ "tips": "Bottom-heavy frames and chin-length hairstyles work great."
40
+ },
41
+ "oblong": {
42
+ "emoji": "📏",
43
+ "description": "Longer than wide with a straight cheek line and sometimes a longer nose.",
44
+ "tips": "Wide frames and voluminous hairstyles add width and balance."
45
+ }
46
+ }
47
+
48
+
49
+ def normalize_landmarks(keypoints, width, height):
50
+ """
51
+ Normalize keypoints to be centered, roll-corrected, and scaled.
52
+ Retains 3D coordinates (Z) but aligns to the 2D plane based on eyes.
53
+ """
54
+ if not keypoints:
55
+ return []
56
+
57
+ landmarks = np.array([[kp["x"], kp["y"], kp["z"]] for kp in keypoints])
58
+
59
+ # Denormalize to pixel coordinates
60
+ landmarks[:, 0] *= width
61
+ landmarks[:, 1] *= height
62
+ landmarks[:, 2] *= width
63
+
64
+ # Iris indices (refine_landmarks=True gives 478 points)
65
+ left_iris_idx = 468
66
+ right_iris_idx = 473
67
+
68
+ if len(landmarks) > right_iris_idx:
69
+ left_iris = landmarks[left_iris_idx]
70
+ right_iris = landmarks[right_iris_idx]
71
+ else:
72
+ # Fallback to eye corners
73
+ p1 = landmarks[33]
74
+ p2 = landmarks[133]
75
+ left_iris = (p1 + p2) / 2
76
+ p3 = landmarks[362]
77
+ p4 = landmarks[263]
78
+ right_iris = (p3 + p4) / 2
79
+
80
+ # 1. Centering
81
+ eye_center = (left_iris + right_iris) / 2.0
82
+ landmarks -= eye_center
83
+
84
+ # 2. Rotation (Roll Correction)
85
+ delta = left_iris - right_iris
86
+ dX, dY = delta[0], delta[1]
87
+ angle = np.arctan2(dY, dX)
88
+ c, s = np.cos(-angle), np.sin(-angle)
89
+
90
+ R = np.array([
91
+ [c, -s, 0],
92
+ [s, c, 0],
93
+ [0, 0, 1]
94
+ ])
95
+
96
+ landmarks = landmarks.dot(R.T)
97
+
98
+ # 3. Scaling
99
+ dist = np.sqrt(dX**2 + dY**2)
100
+ if dist > 0:
101
+ scale = 1.0 / dist
102
+ landmarks *= scale
103
+
104
+ return [(round(float(l[0]), 5), round(float(l[1]), 5), round(float(l[2]), 5))
105
+ for l in landmarks]
106
+
107
+
108
+ def process_image_for_mesh(img_array):
109
+ """
110
+ Process image array to get face mesh data using MediaPipe.
111
+ Returns: keypoints, processed_img or None if failed
112
+ """
113
+ max_width_or_height = 512
114
+
115
+ mp_face_mesh = mp.solutions.face_mesh
116
+
117
+ with mp_face_mesh.FaceMesh(
118
+ static_image_mode=True,
119
+ max_num_faces=1,
120
+ refine_landmarks=True,
121
+ min_detection_confidence=0.5) as face_mesh:
122
+
123
+ # Convert PIL to numpy if needed
124
+ if isinstance(img_array, Image.Image):
125
+ img_array = np.array(img_array)
126
+
127
+ # Handle RGBA images
128
+ if len(img_array.shape) == 3 and img_array.shape[2] == 4:
129
+ img_array = cv2.cvtColor(img_array, cv2.COLOR_RGBA2RGB)
130
+
131
+ # Ensure RGB format
132
+ if len(img_array.shape) == 3 and img_array.shape[2] == 3:
133
+ img_rgb = img_array.copy()
134
+ else:
135
+ return None, None, "Invalid image format"
136
+
137
+ # Downscale large images
138
+ h, w = img_rgb.shape[:2]
139
+ longest = max(h, w)
140
+ if longest > max_width_or_height:
141
+ scale = max_width_or_height / float(longest)
142
+ new_w = max(1, int(round(w * scale)))
143
+ new_h = max(1, int(round(h * scale)))
144
+ img_rgb = cv2.resize(img_rgb, (new_w, new_h), interpolation=cv2.INTER_AREA)
145
+
146
+ # Process the image
147
+ results = face_mesh.process(img_rgb)
148
+
149
+ if not results.multi_face_landmarks:
150
+ return None, None, "No face detected in the image. Please upload a clear photo with a visible face."
151
+
152
+ keypoints = []
153
+ for landmark in results.multi_face_landmarks[0].landmark:
154
+ keypoints.append({
155
+ "x": round(landmark.x, 5),
156
+ "y": round(landmark.y, 5),
157
+ "z": round(landmark.z, 5)
158
+ })
159
+
160
+ return keypoints, img_rgb, None
161
+
162
+
163
+ def draw_face_mesh_overlay(img_rgb, keypoints):
164
+ """Draw face mesh overlay on the image for visualization."""
165
+ img_overlay = img_rgb.copy()
166
+ h, w = img_overlay.shape[:2]
167
+
168
+ mp_face_mesh = mp.solutions.face_mesh
169
+ mp_drawing = mp.solutions.drawing_utils
170
+ mp_drawing_styles = mp.solutions.drawing_styles
171
+
172
+ # Draw key landmark points
173
+ for i, kp in enumerate(keypoints):
174
+ x = int(kp["x"] * w)
175
+ y = int(kp["y"] * h)
176
+ # Draw small circles at landmark positions
177
+ cv2.circle(img_overlay, (x, y), 1, (0, 255, 200), -1)
178
+
179
+ # Draw face contour (simplified)
180
+ contour_indices = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,
181
+ 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,
182
+ 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109, 10]
183
+
184
+ for i in range(len(contour_indices) - 1):
185
+ idx1 = contour_indices[i]
186
+ idx2 = contour_indices[i + 1]
187
+ if idx1 < len(keypoints) and idx2 < len(keypoints):
188
+ pt1 = (int(keypoints[idx1]["x"] * w), int(keypoints[idx1]["y"] * h))
189
+ pt2 = (int(keypoints[idx2]["x"] * w), int(keypoints[idx2]["y"] * h))
190
+ cv2.line(img_overlay, pt1, pt2, (100, 255, 180), 2)
191
+
192
+ return img_overlay
193
+
194
+
195
+ # Load model at startup
196
+ print("Loading face shape classification model...")
197
+ try:
198
+ with open(MODEL_FILE, 'rb') as f:
199
+ model = pickle.load(f)
200
+ with open(LABEL_ENCODER_FILE, 'rb') as f:
201
+ label_encoder = pickle.load(f)
202
+ print("Model loaded successfully!")
203
+ MODEL_LOADED = True
204
+ except Exception as e:
205
+ print(f"Error loading model: {e}")
206
+ MODEL_LOADED = False
207
+ model = None
208
+ label_encoder = None
209
+
210
+
211
+ def predict_face_shape(image):
212
+ """
213
+ Main prediction function for Gradio interface.
214
+ """
215
+ if image is None:
216
+ return None, "Please upload an image.", ""
217
+
218
+ if not MODEL_LOADED:
219
+ return None, "Model not loaded. Please check server logs.", ""
220
+
221
+ # Process image and extract landmarks
222
+ keypoints, img_processed, error = process_image_for_mesh(image)
223
+
224
+ if error:
225
+ return None, error, ""
226
+
227
+ # Create visualization
228
+ img_overlay = draw_face_mesh_overlay(img_processed, keypoints)
229
+
230
+ # Normalize landmarks
231
+ h, w = img_processed.shape[:2]
232
+ normalized_kpts = normalize_landmarks(keypoints, w, h)
233
+
234
+ # Prepare features (flatten x, y only)
235
+ flattened_features = []
236
+ for kp in normalized_kpts:
237
+ flattened_features.extend([kp[0], kp[1]])
238
+
239
+ features_array = np.array([flattened_features])
240
+
241
+ # Predict
242
+ probas = model.predict_proba(features_array)[0]
243
+ prediction_idx = model.predict(features_array)[0]
244
+ predicted_label = label_encoder.inverse_transform([prediction_idx])[0]
245
+
246
+ # Build results
247
+ info = FACE_SHAPE_INFO.get(predicted_label.lower(), {
248
+ "emoji": "✨",
249
+ "description": "A unique face shape.",
250
+ "tips": "Embrace your unique features!"
251
+ })
252
+
253
+ # Format confidence scores
254
+ confidence_text = ""
255
+ class_indices = np.argsort(probas)[::-1]
256
+ for i in class_indices:
257
+ class_name = label_encoder.classes_[i]
258
+ score = probas[i]
259
+ bar = "█" * int(score * 20)
260
+ confidence_text += f"{class_name.capitalize():10} {bar} {score*100:.1f}%\n"
261
+
262
+ # Main result
263
+ result_html = f"""
264
+ <div style="text-align: center; padding: 20px;">
265
+ <h1 style="font-size: 3em; margin-bottom: 10px;">{info['emoji']}</h1>
266
+ <h2 style="font-size: 2em; color: #1d4ed8; margin-bottom: 15px;">
267
+ {predicted_label.upper()}
268
+ </h2>
269
+ <p style="font-size: 1.1em; color: #4b5563; margin-bottom: 15px;">
270
+ {info['description']}
271
+ </p>
272
+ <div style="background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
273
+ padding: 15px; border-radius: 12px; margin-top: 15px;">
274
+ <strong>💡 Style Tips:</strong><br>
275
+ {info['tips']}
276
+ </div>
277
+ </div>
278
+ """
279
+
280
+ return img_overlay, result_html, confidence_text
281
+
282
+
283
+ # Custom CSS for beautiful UI
284
+ custom_css = """
285
+ .gradio-container {
286
+ font-family: 'Segoe UI', system-ui, sans-serif !important;
287
+ }
288
+ .gradio-container a,
289
+ .gradio-container a:visited {
290
+ color: #1d4ed8;
291
+ }
292
+ .main-title {
293
+ text-align: center;
294
+ background: linear-gradient(135deg, #0ea5e9 0%, #2563eb 55%, #0f172a 100%);
295
+ -webkit-background-clip: text;
296
+ -webkit-text-fill-color: transparent;
297
+ background-clip: text;
298
+ font-size: 2.5em !important;
299
+ font-weight: 700 !important;
300
+ margin-bottom: 0.5em !important;
301
+ }
302
+ .header-links {
303
+ display: flex;
304
+ justify-content: center;
305
+ gap: 12px;
306
+ flex-wrap: wrap;
307
+ margin: 0.25em 0 1.1em 0;
308
+ }
309
+ .header-link {
310
+ display: inline-flex;
311
+ align-items: center;
312
+ gap: 8px;
313
+ padding: 8px 12px;
314
+ border-radius: 999px;
315
+ border: 1px solid #cbd5e1;
316
+ background: #ffffff;
317
+ color: #0f172a !important;
318
+ text-decoration: none !important;
319
+ font-weight: 600;
320
+ font-size: 0.95em;
321
+ box-shadow: 0 1px 2px rgba(15, 23, 42, 0.06);
322
+ }
323
+ .header-link:hover {
324
+ border-color: #2563eb;
325
+ box-shadow: 0 6px 18px rgba(37, 99, 235, 0.15);
326
+ transform: translateY(-1px);
327
+ }
328
+ .header-link:focus-visible {
329
+ outline: 3px solid rgba(37, 99, 235, 0.35);
330
+ outline-offset: 2px;
331
+ }
332
+ .subtitle {
333
+ text-align: center;
334
+ color: #6b7280;
335
+ font-size: 1.1em;
336
+ margin-bottom: 1.5em;
337
+ }
338
+ footer {
339
+ visibility: hidden;
340
+ }
341
+ """
342
+
343
+ # Build Gradio Interface
344
+ with gr.Blocks(
345
+ css=custom_css,
346
+ theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky", neutral_hue="slate"),
347
+ ) as demo:
348
+ gr.HTML("""
349
+ <h1 class="main-title">AI Face Shape Detector</h1>
350
+ <div class="header-links">
351
+ <a class="header-link" href="https://attractivenesstest.com/face_shape" target="_blank" rel="noopener noreferrer">
352
+ Face Shape Detection App
353
+ </a>
354
+ <a class="header-link" href="https://github.com/rs75/FaceShapeAI" target="_blank" rel="noopener noreferrer">
355
+ GitHub
356
+ </a>
357
+ </div>
358
+ <p class="subtitle">Upload a photo to discover your face shape using AI-powered analysis</p>
359
+ """)
360
+
361
+ with gr.Row():
362
+ with gr.Column(scale=1):
363
+ input_image = gr.Image(
364
+ label="📷 Upload Your Photo",
365
+ type="numpy",
366
+ sources=["upload", "webcam"],
367
+ height=400
368
+ )
369
+ analyze_btn = gr.Button("✨ Analyze Face Shape", variant="primary", size="lg")
370
+
371
+ gr.Markdown("""
372
+ ### 📋 Tips for Best Results
373
+ - Use a **front-facing** photo with good lighting
374
+ - Ensure your **entire face** is visible
375
+ - Remove glasses if possible
376
+ - Avoid tilting your head
377
+ """)
378
+
379
+ with gr.Column(scale=1):
380
+ output_image = gr.Image(
381
+ label="🎯 Face Mesh Analysis",
382
+ height=400
383
+ )
384
+ result_html = gr.HTML(label="Result")
385
+
386
+ with gr.Accordion("📊 Confidence Scores", open=False):
387
+ confidence_output = gr.Textbox(
388
+ label="",
389
+ lines=6,
390
+ interactive=False
391
+ )
392
+
393
+ gr.HTML("""
394
+ <div style="text-align: center; margin-top: 30px; padding: 20px;
395
+ background: #f8fafc; border-radius: 12px;">
396
+ <p style="color: #6b7280; font-size: 0.9em;">
397
+ 🔬 Powered by <strong>MediaPipe</strong> Face Mesh & Machine Learning<br>
398
+ 📐 Analyzes 478 facial landmarks for accurate shape detection
399
+ </p>
400
+ </div>
401
+ """)
402
+
403
+ # Event handlers
404
+ analyze_btn.click(
405
+ fn=predict_face_shape,
406
+ inputs=[input_image],
407
+ outputs=[output_image, result_html, confidence_output]
408
+ )
409
+
410
+ input_image.change(
411
+ fn=predict_face_shape,
412
+ inputs=[input_image],
413
+ outputs=[output_image, result_html, confidence_output]
414
+ )
415
+
416
+
417
+ if __name__ == "__main__":
418
+ demo.launch()
face_shape_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:790585e7c236f108d1131d4d295f28f68b2cbe2702f81ba500c5b8a9ec3294f2
3
+ size 1308871
label_encoder_rf.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ed219dcc5c0195ddd7f21aed8a86714ba9bada51c3684961a9331bf072af1d7
3
+ size 283
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ mediapipe==0.10.21
3
+ opencv-python-headless>=4.8.0
4
+ numpy>=1.24.0
5
+ scikit-learn>=1.3.0
6
+ Pillow>=10.0.0