anismizi commited on
Commit
e738c7c
Β·
1 Parent(s): ae4ca80

Add skin type classifier app with trained model

Browse files
Files changed (6) hide show
  1. README.md +20 -5
  2. app.py +245 -0
  3. best_skin_model.pth +3 -0
  4. face_sample1.jpg +0 -0
  5. label_maps.pkl +3 -0
  6. requirements.txt +5 -0
README.md CHANGED
@@ -1,13 +1,28 @@
1
  ---
2
  title: Skin Type Classifier
3
- emoji: πŸ†
4
  colorFrom: blue
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 5.35.0
8
  app_file: app.py
9
  pinned: false
10
- short_description: Image Classifier
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Skin Type Classifier
3
+ emoji: πŸ”¬
4
  colorFrom: blue
5
+ colorTo: green
6
  sdk: gradio
7
+ sdk_version: 4.44.1
8
  app_file: app.py
9
  pinned: false
10
+ license: mit
11
  ---
12
 
13
+ # πŸ”¬ Skin Type Classifier
14
+
15
+ A deep learning model for classifying skin types into dry and oily categories using computer vision.
16
+
17
+ ## Features
18
+ - Upload facial skin images
19
+ - Real-time classification (dry vs oily)
20
+ - Confidence scores and recommendations
21
+ - Built with ResNet50 architecture
22
+
23
+ ## How to Use
24
+ 1. Upload a clear facial skin image
25
+ 2. Get instant skin type classification
26
+ 3. View confidence scores and skincare recommendations
27
+
28
+ ⚠️ **Disclaimer**: This model is for educational and research purposes only. Consult a dermatologist for professional skin analysis.
app.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Hugging Face Space for Skin Type Classification
4
+ """
5
+
6
+ import gradio as gr
7
+ import torch
8
+ import torch.nn as nn
9
+ import pickle
10
+ from PIL import Image
11
+ import torchvision.transforms as transforms
12
+ from torchvision.models import resnet50
13
+ import os
14
+
15
+ # Model configuration
16
+ DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
17
+
18
+ # Global model variable
19
+ model = None
20
+ transform = None
21
+ label_mappings = None
22
+
23
+ def load_model():
24
+ """Load the model from local files"""
25
+ global model, transform, label_mappings
26
+
27
+ try:
28
+ # Load label mappings
29
+ if os.path.exists('label_maps.pkl'):
30
+ with open('label_maps.pkl', 'rb') as f:
31
+ label_mappings = pickle.load(f)
32
+ print("βœ… Label mappings loaded successfully!")
33
+ else:
34
+ # Fallback label mappings
35
+ label_mappings = {'index_label': {0: 'dry', 1: 'oily'}}
36
+ print("⚠️ Using fallback label mappings")
37
+
38
+ # Initialize model architecture
39
+ model = resnet50(weights=None)
40
+ model.fc = nn.Linear(model.fc.in_features, 2) # 2 classes (dry, oily)
41
+
42
+ # Load trained weights
43
+ if os.path.exists('best_skin_model.pth'):
44
+ model.load_state_dict(torch.load('best_skin_model.pth', map_location=DEVICE))
45
+ print("βœ… Model weights loaded successfully!")
46
+ else:
47
+ print("⚠️ Model weights not found, using randomly initialized model")
48
+
49
+ model.to(DEVICE)
50
+ model.eval()
51
+
52
+ # Define transforms
53
+ transform = transforms.Compose([
54
+ transforms.Resize((224, 224)),
55
+ transforms.ToTensor(),
56
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
57
+ ])
58
+
59
+ return True
60
+
61
+ except Exception as e:
62
+ print(f"Error initializing model: {e}")
63
+ return False
64
+
65
+ def predict_skin_type(image):
66
+ """Predict skin type from uploaded image"""
67
+ if image is None:
68
+ return "Please upload an image first.", {}
69
+
70
+ try:
71
+ # Ensure image is RGB
72
+ if image.mode != 'RGB':
73
+ image = image.convert('RGB')
74
+
75
+ # Preprocess image
76
+ input_tensor = transform(image).unsqueeze(0).to(DEVICE)
77
+
78
+ # Make prediction
79
+ with torch.no_grad():
80
+ outputs = model(input_tensor)
81
+ probabilities = torch.softmax(outputs, dim=1)
82
+ predicted_class = torch.argmax(probabilities, dim=1).item()
83
+ confidence = probabilities[0][predicted_class].item()
84
+
85
+ # Get predictions
86
+ dry_prob = float(probabilities[0][0])
87
+ oily_prob = float(probabilities[0][1])
88
+
89
+ # Determine skin type using label mappings
90
+ predicted_label = label_mappings['index_label'][predicted_class]
91
+ skin_type = predicted_label.title() # 'dry' -> 'Dry', 'oily' -> 'Oily'
92
+
93
+ # Create results
94
+ confidence_dict = {
95
+ "Dry Skin": dry_prob,
96
+ "Oily Skin": oily_prob
97
+ }
98
+
99
+ # Create detailed results text
100
+ result_text = f"""
101
+ ## πŸ”¬ Analysis Results
102
+
103
+ **Predicted Skin Type: {skin_type.upper()}**
104
+ **Confidence: {confidence:.1%}**
105
+
106
+ ### πŸ“Š Probabilities:
107
+ - Dry Skin: {dry_prob:.1%}
108
+ - Oily Skin: {oily_prob:.1%}
109
+
110
+ ### πŸ’‘ Skincare Recommendations:
111
+ """
112
+
113
+ if skin_type == "Dry":
114
+ result_text += """
115
+ - Use hydrating moisturizers with hyaluronic acid
116
+ - Avoid harsh cleansers that strip natural oils
117
+ - Try gentle, cream-based cleansers
118
+ - Apply moisturizer on damp skin
119
+ - Consider facial oils for extra hydration
120
+ """
121
+ else:
122
+ result_text += """
123
+ - Use oil-free, non-comedogenic products
124
+ - Try salicylic acid or niacinamide treatments
125
+ - Use gentle foaming cleansers
126
+ - Don't over-cleanse (can increase oil production)
127
+ - Consider clay masks 1-2 times per week
128
+ """
129
+
130
+ result_text += """
131
+ ### ⚠️ Important Note:
132
+ This is an AI prediction for educational purposes. For professional skin analysis and personalized skincare advice, consult a dermatologist.
133
+ """
134
+
135
+ return result_text, confidence_dict
136
+
137
+ except Exception as e:
138
+ error_msg = f"Error during prediction: {str(e)}"
139
+ return error_msg, {"Error": 1.0}
140
+
141
+ # Load model at startup
142
+ print("πŸš€ Initializing Skin Type Classifier...")
143
+ model_loaded = load_model()
144
+
145
+ if not model_loaded:
146
+ print("❌ Failed to load model")
147
+
148
+ # Create Gradio interface
149
+ with gr.Blocks(
150
+ title="πŸ”¬ Skin Type Classifier",
151
+ theme=gr.themes.Soft(),
152
+ css="""
153
+ .gradio-container {
154
+ max-width: 900px;
155
+ margin: auto;
156
+ }
157
+ """
158
+ ) as demo:
159
+
160
+ gr.Markdown("""
161
+ # πŸ”¬ AI Skin Type Classifier
162
+
163
+ Upload a facial skin image to determine if it's **dry** or **oily** skin type.
164
+
165
+ ### πŸ“Έ Tips for Best Results:
166
+ - Use clear, well-lit photos of facial skin
167
+ - Avoid heavily filtered or edited images
168
+ - Ensure the skin area is clearly visible
169
+ - Natural lighting works best
170
+ """)
171
+
172
+ with gr.Row():
173
+ with gr.Column(scale=1):
174
+ # Image input
175
+ image_input = gr.Image(
176
+ type="pil",
177
+ label="πŸ“· Upload Skin Image",
178
+ height=400
179
+ )
180
+
181
+ # Predict button
182
+ predict_btn = gr.Button(
183
+ "πŸ” Analyze Skin Type",
184
+ variant="primary",
185
+ size="lg"
186
+ )
187
+
188
+ with gr.Column(scale=1):
189
+ # Results
190
+ result_text = gr.Markdown(
191
+ value="Upload an image to see analysis results...",
192
+ label="πŸ“‹ Analysis Results"
193
+ )
194
+
195
+ confidence_output = gr.Label(
196
+ label="πŸ“Š Confidence Scores",
197
+ num_top_classes=2
198
+ )
199
+
200
+ # Event handlers
201
+ predict_btn.click(
202
+ fn=predict_skin_type,
203
+ inputs=[image_input],
204
+ outputs=[result_text, confidence_output]
205
+ )
206
+
207
+ # Auto-predict when image is uploaded
208
+ image_input.change(
209
+ fn=predict_skin_type,
210
+ inputs=[image_input],
211
+ outputs=[result_text, confidence_output]
212
+ )
213
+
214
+ gr.Markdown("""
215
+ ---
216
+
217
+ ### πŸ€– About This Model
218
+
219
+ - **Architecture**: ResNet50-based neural network
220
+ - **Classes**: Dry skin vs Oily skin
221
+ - **Training**: Custom dataset with skin type annotations
222
+ - **Purpose**: Educational and research use only
223
+
224
+ ### πŸ“š How It Works
225
+
226
+ 1. **Image Processing**: Resizes and normalizes your uploaded image
227
+ 2. **Feature Extraction**: Uses ResNet50 to extract skin features
228
+ 3. **Classification**: Predicts skin type with confidence scores
229
+ 4. **Recommendations**: Provides tailored skincare suggestions
230
+
231
+ ### ⚠️ Important Disclaimers
232
+
233
+ - This tool is for **educational purposes only**
234
+ - **Not for medical diagnosis** - consult a dermatologist for professional advice
235
+ - Results may vary based on lighting, image quality, and individual skin characteristics
236
+ - The model may have limitations across different skin tones and ethnicities
237
+
238
+ ---
239
+
240
+ **Created with ❀️ using Gradio and PyTorch**
241
+ """)
242
+
243
+ # Launch the app
244
+ if __name__ == "__main__":
245
+ demo.launch()
best_skin_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:311dc1b2cac8025b2e1da09127daa9a21b372c0a06455db5ffeb402c18205b0d
3
+ size 94364655
face_sample1.jpg ADDED
label_maps.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f60fc6fd236a8bf42973f119adf839e7cfb8ab073b3e3a20eb4f56e568820470
3
+ size 77
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio==4.44.1
2
+ torch==1.13.1
3
+ torchvision==0.14.1
4
+ Pillow==10.4.0
5
+ requests==2.32.4