-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
194 lines (162 loc) Β· 6.95 KB
/
app.py
File metadata and controls
194 lines (162 loc) Β· 6.95 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!pip install streamlit
import os
import pickle
import cv2
import numpy as np
import streamlit as st
from PIL import Image
from keras_vggface.utils import preprocess_input
from keras_vggface.vggface import VGGFace
from sklearn.metrics.pairwise import cosine_similarity
from mtcnn import MTCNN
# Page config
st.set_page_config(page_title="Celebrity Look-Alike Finder", page_icon="π¬", layout="wide")
# Load models with caching
@st.cache_resource
def load_models():
"""Load face detector and feature extractor models"""
try:
detector = MTCNN()
model = VGGFace(model='resnet50', include_top=False, input_shape=(224, 224, 3), pooling='avg')
return detector, model
except Exception as e:
st.error(f"Error loading models: {e}")
st.stop()
# Load embeddings with caching
@st.cache_data
def load_embeddings():
"""Load pre-computed embeddings"""
try:
if not os.path.exists('embedding.pkl') or not os.path.exists('filenames.pkl'):
st.error("β Embedding files not found!")
st.stop()
with open('embedding.pkl', 'rb') as f:
feature_list = pickle.load(f)
with open('filenames.pkl', 'rb') as f:
filenames = pickle.load(f)
return feature_list, filenames
except Exception as e:
st.error(f"Error loading embeddings: {e}")
st.stop()
# Initialize models
detector, model = load_models()
feature_list, filenames = load_embeddings()
def save_uploaded_image(uploaded_image):
"""Save uploaded image"""
try:
os.makedirs('uploads', exist_ok=True)
filepath = os.path.join('uploads', uploaded_image.name)
with open(filepath, 'wb') as f:
f.write(uploaded_image.getbuffer())
return filepath
except Exception as e:
st.error(f"Error saving image: {e}")
return None
def extract_features(img_path, model, detector):
"""Extract facial features"""
try:
img = cv2.imread(img_path)
if img is None:
return None
# Convert BGR to RGB
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
results = detector.detect_faces(img_rgb)
if len(results) == 0:
return None
# Get face with highest confidence
best_face = max(results, key=lambda x: x['confidence'])
x, y, width, height = best_face['box']
# Add padding for better extraction
padding = 20
x = max(0, x - padding)
y = max(0, y - padding)
width = min(img_rgb.shape[1] - x, width + 2 * padding)
height = min(img_rgb.shape[0] - y, height + 2 * padding)
face = img_rgb[y:y + height, x:x + width]
if face.size == 0:
return None
# extract its features
image = Image.fromarray(face)
image = image.resize((224, 224))
face_array = np.asarray(image, dtype='float32')
expanded_img = np.expand_dims(face_array, axis=0)
preprocessed_img = preprocess_input(expanded_img)
result = model.predict(preprocessed_img, verbose=0).flatten()
return result
except Exception as e:
st.error(f"Error extracting features: {e}")
return None
def get_top_matches(feature_list, features, top_n=5):
"""Get top N celebrity matches with confidence scores"""
try:
similarities = []
for i in range(len(feature_list)):
sim = cosine_similarity(features.reshape(1, -1), feature_list[i].reshape(1, -1))[0][0]
similarities.append(sim)
top_indices = sorted(list(enumerate(similarities)), reverse=True, key=lambda x: x[1])[:top_n]
return top_indices
except Exception as e:
st.error(f"Error finding matches: {e}")
return []
def extract_celebrity_name(filepath):
"""Extract celebrity name from filepath"""
try:
parts = filepath.replace('\\', '/').split('/')
for part in reversed(parts):
if part and not part.lower().endswith(('.jpg', '.jpeg', '.png')):
return part.replace('_', ' ')
return "Unknown Celebrity"
except:
return "Unknown Celebrity"
# UI
st.title('π¬ Which Bollywood Celebrity Are You? π')
st.markdown("Upload your photo and discover which celebrity you resemble!")
uploaded_image = st.file_uploader('πΈ Choose a clear photo with your face', type=['jpg', 'jpeg', 'png'])
if uploaded_image is not None:
# save the image in a directory
img_path = save_uploaded_image(uploaded_image)
if img_path:
# load the image
display_image = Image.open(uploaded_image)
with st.spinner('π Analyzing your face...'):
# extract the features
features = extract_features(img_path, model, detector)
if features is None:
st.error('β No face detected in the image. Please upload a clear photo with a visible face.')
else:
# Get top matches
top_matches = get_top_matches(feature_list, features, top_n=5)
if top_matches:
st.success('β
Analysis complete!')
# Best match
best_index, best_score = top_matches[0]
celebrity_name = extract_celebrity_name(filenames[best_index])
# display
col1, col2 = st.columns(2)
with col1:
st.header('Your Photo')
st.image(display_image, use_container_width=True)
with col2:
st.header(f"You look like {celebrity_name}! π")
st.metric("Match Confidence", f"{best_score*100:.1f}%")
try:
celeb_img = Image.open(filenames[best_index])
st.image(celeb_img, use_container_width=True)
except:
st.info("Celebrity image not available")
# Show other matches
if len(top_matches) > 1:
st.markdown("---")
st.subheader("Other Similar Celebrities:")
cols = st.columns(4)
for i, (idx, score) in enumerate(top_matches[1:], 1):
if i <= 4:
celeb_name = extract_celebrity_name(filenames[idx])
with cols[i-1]:
try:
celeb_img = Image.open(filenames[idx])
st.image(celeb_img, caption=f"{celeb_name} ({score*100:.1f}%)")
except:
st.text(f"{celeb_name} ({score*100:.1f}%)")
else:
st.info('π Upload a photo to get started!')