Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,6 +2,7 @@ import streamlit as st
|
|
2 |
import cv2
|
3 |
import numpy as np
|
4 |
from deepface import DeepFace
|
|
|
5 |
|
6 |
st.set_page_config(
|
7 |
page_title="✨ Age & Gender Predictor",
|
@@ -13,61 +14,139 @@ st.title("✨ Age & Gender Predictor")
|
|
13 |
st.write(
|
14 |
"""
|
15 |
Welcome to the future of facial analysis!
|
16 |
-
**
|
17 |
|
18 |
**No data is stored**.
|
19 |
"""
|
20 |
)
|
21 |
|
22 |
-
|
|
|
|
|
23 |
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
|
|
28 |
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
29 |
|
30 |
-
|
|
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
results = sorted(results, key=lambda x: x['face_confidence'], reverse=True)
|
44 |
-
main_result = results[0]
|
45 |
-
else:
|
46 |
-
main_result = results
|
47 |
-
|
48 |
-
st.success("Analysis complete! Here's what we found:")
|
49 |
-
st.write("## Detailed Results")
|
50 |
-
|
51 |
-
age = main_result['age']
|
52 |
-
st.write(f"**Predicted Age:** {age} years")
|
53 |
-
|
54 |
-
gender = main_result['gender']
|
55 |
-
dominant_gender = gender if isinstance(gender, str) else max(gender, key=gender.get)
|
56 |
-
confidence = gender[dominant_gender] if isinstance(gender, dict) else None
|
57 |
-
|
58 |
-
if confidence:
|
59 |
-
st.write(f"**Predicted Gender:** {dominant_gender} ({confidence:.2f}% confidence)")
|
60 |
-
else:
|
61 |
-
st.write(f"**Predicted Gender:** {dominant_gender}")
|
62 |
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
"
|
70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
st.markdown("---")
|
73 |
st.markdown(
|
|
|
2 |
import cv2
|
3 |
import numpy as np
|
4 |
from deepface import DeepFace
|
5 |
+
import time
|
6 |
|
7 |
st.set_page_config(
|
8 |
page_title="✨ Age & Gender Predictor",
|
|
|
14 |
st.write(
|
15 |
"""
|
16 |
Welcome to the future of facial analysis!
|
17 |
+
**Enable your webcam** and let our cutting-edge AI reveal your age and gender with impressive precision.
|
18 |
|
19 |
**No data is stored**.
|
20 |
"""
|
21 |
)
|
22 |
|
23 |
+
# Create placeholders for webcam and captured image
|
24 |
+
webcam_placeholder = st.empty()
|
25 |
+
captured_image_placeholder = st.empty()
|
26 |
|
27 |
+
# Create columns for buttons
|
28 |
+
col1, col2 = st.columns(2)
|
29 |
+
start_button = col1.button("Start Webcam")
|
30 |
+
capture_button = col2.button("Capture Image", disabled=True)
|
31 |
+
|
32 |
+
# Results area
|
33 |
+
results_area = st.container()
|
34 |
+
|
35 |
+
# Initialize session state variables if they don't exist
|
36 |
+
if 'camera_on' not in st.session_state:
|
37 |
+
st.session_state.camera_on = False
|
38 |
+
if 'captured_image' not in st.session_state:
|
39 |
+
st.session_state.captured_image = None
|
40 |
+
|
41 |
+
# Function to start webcam
|
42 |
+
def start_webcam():
|
43 |
+
st.session_state.camera_on = True
|
44 |
+
st.experimental_rerun()
|
45 |
+
|
46 |
+
# Function to capture image
|
47 |
+
def capture_image():
|
48 |
+
st.session_state.camera_on = False
|
49 |
+
st.experimental_rerun()
|
50 |
+
|
51 |
+
# Set button callbacks
|
52 |
+
if start_button:
|
53 |
+
start_webcam()
|
54 |
+
if capture_button:
|
55 |
+
capture_image()
|
56 |
+
|
57 |
+
# Main webcam logic
|
58 |
+
if st.session_state.camera_on:
|
59 |
+
# Update the UI to show the webcam is active
|
60 |
+
capture_button = col2.button("Capture Image", key='capture_active', on_click=capture_image)
|
61 |
+
stop_button = col1.button("Stop Webcam", key='stop_webcam', on_click=lambda: setattr(st.session_state, 'camera_on', False))
|
62 |
+
|
63 |
+
# Display webcam feed
|
64 |
+
cap = cv2.VideoCapture(0)
|
65 |
+
|
66 |
+
if not cap.isOpened():
|
67 |
+
st.error("Could not open webcam. Please check your camera connection.")
|
68 |
+
else:
|
69 |
+
# Get a frame
|
70 |
+
ret, frame = cap.read()
|
71 |
+
if ret:
|
72 |
+
# Convert to RGB for display
|
73 |
+
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
74 |
+
# Display the frame
|
75 |
+
webcam_placeholder.image(frame_rgb, channels="RGB", caption="Webcam Feed", use_column_width=True)
|
76 |
+
# Store the current frame
|
77 |
+
st.session_state.captured_image = frame.copy()
|
78 |
+
else:
|
79 |
+
st.error("Failed to capture image from webcam.")
|
80 |
+
|
81 |
+
# Small delay to allow UI updates
|
82 |
+
time.sleep(0.1)
|
83 |
+
|
84 |
+
# Release the camera
|
85 |
+
cap.release()
|
86 |
+
|
87 |
+
# Force a rerun to get another frame (creates a video effect)
|
88 |
+
if st.session_state.camera_on:
|
89 |
+
time.sleep(0.1)
|
90 |
+
st.experimental_rerun()
|
91 |
+
|
92 |
+
# If we have a captured image, display and analyze it
|
93 |
+
elif st.session_state.captured_image is not None:
|
94 |
+
# Re-enable the start webcam button with a new key
|
95 |
+
start_again_button = col1.button("Restart Webcam", key='restart_webcam', on_click=start_webcam)
|
96 |
+
|
97 |
+
# Get the captured image
|
98 |
+
image = st.session_state.captured_image
|
99 |
|
100 |
+
# Convert to RGB for display
|
101 |
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
102 |
|
103 |
+
# Show the captured image
|
104 |
+
captured_image_placeholder.image(image_rgb, caption="Captured Image", use_column_width=True)
|
105 |
|
106 |
+
# Analyze the image
|
107 |
+
with results_area:
|
108 |
+
with st.spinner("Analyzing your image with advanced AI models..."):
|
109 |
+
try:
|
110 |
+
results = DeepFace.analyze(
|
111 |
+
image,
|
112 |
+
actions=['age', 'gender'],
|
113 |
+
detector_backend='retinaface',
|
114 |
+
enforce_detection=True,
|
115 |
+
align=True
|
116 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
|
118 |
+
if isinstance(results, list):
|
119 |
+
results = sorted(results, key=lambda x: x.get('face_confidence', 0), reverse=True)
|
120 |
+
main_result = results[0]
|
121 |
+
else:
|
122 |
+
main_result = results
|
123 |
+
|
124 |
+
st.success("Analysis complete! Here's what we found:")
|
125 |
+
st.write("## Detailed Results")
|
126 |
+
|
127 |
+
age = main_result['age']
|
128 |
+
st.write(f"**Predicted Age:** {age} years")
|
129 |
+
|
130 |
+
gender = main_result['gender']
|
131 |
+
dominant_gender = gender if isinstance(gender, str) else max(gender, key=gender.get)
|
132 |
+
confidence = gender[dominant_gender] if isinstance(gender, dict) else None
|
133 |
+
|
134 |
+
if confidence:
|
135 |
+
st.write(f"**Predicted Gender:** {dominant_gender} ({confidence:.2f}% confidence)")
|
136 |
+
else:
|
137 |
+
st.write(f"**Predicted Gender:** {dominant_gender}")
|
138 |
+
|
139 |
+
except Exception as e:
|
140 |
+
st.error(f"Analysis failed: {str(e)}")
|
141 |
+
st.info(
|
142 |
+
"For best results, please try the following tips:\n"
|
143 |
+
"- Ensure good lighting conditions\n"
|
144 |
+
"- Position your face clearly in the frame\n"
|
145 |
+
"- Move closer to the camera if needed"
|
146 |
+
)
|
147 |
+
else:
|
148 |
+
# Initial state, just display start webcam button
|
149 |
+
st.info("Click 'Start Webcam' to begin")
|
150 |
|
151 |
st.markdown("---")
|
152 |
st.markdown(
|