RICHERGIRL commited on
Commit
d0ff2ca
·
verified ·
1 Parent(s): ff5af75

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -21
app.py CHANGED
@@ -1,37 +1,53 @@
1
  import gradio as gr
2
- import cv2
3
- import numpy as np
4
  import joblib
5
  import os
6
- from utils import extract_features # Make sure this exists in utils.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  def safe_load_model():
9
- """Safely loads model files with error handling"""
10
  try:
11
- # Verify files exist
12
  if not all(os.path.exists(f'model/{f}') for f in ['random_forest.pkl', 'label_encoders.pkl']):
13
  raise FileNotFoundError("Model files missing")
14
 
15
- # Load with mmap_mode for Hugging Face
16
  model = joblib.load('model/random_forest.pkl', mmap_mode='r')
17
  encoders = joblib.load('model/label_encoders.pkl', mmap_mode='r')
18
- print("Model loaded successfully!")
 
 
 
 
 
19
  return model, encoders
20
 
21
  except Exception as e:
22
- print(f"Model loading failed: {str(e)}")
23
- # Fallback simple model
24
- from sklearn.ensemble import RandomForestClassifier
25
- from sklearn.preprocessing import LabelEncoder
26
- print("Using fallback model")
27
- return RandomForestClassifier(n_estimators=10), {
28
- 'face_shape': LabelEncoder().fit(['Oval', 'Round', 'Square']),
29
- 'skin_tone': LabelEncoder().fit(['Fair', 'Medium', 'Dark']),
30
- 'face_size': LabelEncoder().fit(['Small', 'Medium', 'Large'])
31
- }
32
 
33
  def recommend_mask(image):
34
- """Process image and make prediction"""
35
  try:
36
  # Extract features
37
  face_shape, skin_tone, face_size = extract_features(image)
@@ -47,7 +63,7 @@ def recommend_mask(image):
47
 
48
  except Exception as e:
49
  print(f"Prediction error: {str(e)}")
50
- return f"Error: Could not process image - {str(e)}"
51
 
52
  # Initialize model and encoders
53
  model, encoders = safe_load_model()
@@ -59,8 +75,7 @@ demo = gr.Interface(
59
  outputs=gr.Textbox(label="Recommended Mask Style"),
60
  title="🎭 AI Party Mask Recommender",
61
  description="Upload a photo to get a personalized mask recommendation!",
62
- examples=[["example_face.jpg"]] if os.path.exists("example_face.jpg") else None
63
  )
64
 
65
  if __name__ == "__main__":
66
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import gradio as gr
 
 
2
  import joblib
3
  import os
4
+ import numpy as np
5
+ from sklearn.ensemble import RandomForestClassifier
6
+ from sklearn.preprocessing import LabelEncoder
7
+ from utils import extract_features
8
+
9
+ def initialize_fallback_model():
10
+ """Creates and trains a simple fallback model"""
11
+ print("Initializing fallback model...")
12
+
13
+ # Simple training data
14
+ X = np.array([[0,0,0], [1,1,1], [2,2,2]]) # Dummy encoded features
15
+ y = np.array([0, 1, 0]) # Dummy target
16
+
17
+ model = RandomForestClassifier(n_estimators=10)
18
+ model.fit(X, y)
19
+
20
+ encoders = {
21
+ 'face_shape': LabelEncoder().fit(['Oval', 'Round', 'Square']),
22
+ 'skin_tone': LabelEncoder().fit(['Fair', 'Medium', 'Dark']),
23
+ 'face_size': LabelEncoder().fit(['Small', 'Medium', 'Large']),
24
+ 'mask_style': LabelEncoder().fit(['StyleA', 'StyleB', 'StyleC']) # Added mask_style
25
+ }
26
+
27
+ return model, encoders
28
 
29
  def safe_load_model():
30
+ """Safely loads model files with comprehensive fallback"""
31
  try:
 
32
  if not all(os.path.exists(f'model/{f}') for f in ['random_forest.pkl', 'label_encoders.pkl']):
33
  raise FileNotFoundError("Model files missing")
34
 
 
35
  model = joblib.load('model/random_forest.pkl', mmap_mode='r')
36
  encoders = joblib.load('model/label_encoders.pkl', mmap_mode='r')
37
+
38
+ # Verify model is fitted
39
+ if not hasattr(model, 'classes_'):
40
+ raise ValueError("Model not properly trained")
41
+
42
+ print("Main model loaded successfully!")
43
  return model, encoders
44
 
45
  except Exception as e:
46
+ print(f"Loading failed: {str(e)}")
47
+ return initialize_fallback_model()
 
 
 
 
 
 
 
 
48
 
49
  def recommend_mask(image):
50
+ """Process image and make prediction with error handling"""
51
  try:
52
  # Extract features
53
  face_shape, skin_tone, face_size = extract_features(image)
 
63
 
64
  except Exception as e:
65
  print(f"Prediction error: {str(e)}")
66
+ return f"Recommended: Basic Mask (Fallback)"
67
 
68
  # Initialize model and encoders
69
  model, encoders = safe_load_model()
 
75
  outputs=gr.Textbox(label="Recommended Mask Style"),
76
  title="🎭 AI Party Mask Recommender",
77
  description="Upload a photo to get a personalized mask recommendation!",
 
78
  )
79
 
80
  if __name__ == "__main__":
81
+ demo.launch()