Update app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,8 @@ import streamlit as st
|
|
2 |
import cv2
|
3 |
import numpy as np
|
4 |
from deepface import DeepFace
|
5 |
-
import
|
|
|
6 |
|
7 |
st.set_page_config(
|
8 |
page_title="✨ Age & Gender Predictor",
|
@@ -14,153 +15,79 @@ st.title("✨ Age & Gender Predictor")
|
|
14 |
st.write(
|
15 |
"""
|
16 |
Welcome to the future of facial analysis!
|
17 |
-
**
|
18 |
|
19 |
**No data is stored**.
|
20 |
"""
|
21 |
)
|
22 |
|
23 |
-
# Initialize session state
|
24 |
-
if '
|
25 |
-
st.session_state.
|
26 |
-
if '
|
27 |
-
st.session_state.
|
28 |
-
if '
|
29 |
-
st.session_state.
|
30 |
|
31 |
-
#
|
32 |
-
|
33 |
-
st.session_state.camera_on = True
|
34 |
-
st.session_state.analyzed = False
|
35 |
|
36 |
-
#
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
def reset_app():
|
43 |
-
st.session_state.camera_on = False
|
44 |
-
st.session_state.captured_image = None
|
45 |
-
st.session_state.analyzed = False
|
46 |
-
|
47 |
-
# Create placeholders for webcam and captured image
|
48 |
-
webcam_placeholder = st.empty()
|
49 |
-
captured_image_placeholder = st.empty()
|
50 |
-
|
51 |
-
# Create columns for buttons
|
52 |
-
col1, col2 = st.columns(2)
|
53 |
-
|
54 |
-
# Results area
|
55 |
-
results_area = st.container()
|
56 |
-
|
57 |
-
# Main app logic
|
58 |
-
if not st.session_state.camera_on and st.session_state.captured_image is None:
|
59 |
-
# Initial state - just show the start button
|
60 |
-
if col1.button("Start Webcam"):
|
61 |
-
start_webcam()
|
62 |
-
st.rerun()
|
63 |
-
|
64 |
-
elif st.session_state.camera_on:
|
65 |
-
# Webcam is on - show the capture and stop buttons
|
66 |
-
if col1.button("Stop Webcam"):
|
67 |
-
st.session_state.camera_on = False
|
68 |
-
st.rerun()
|
69 |
-
|
70 |
-
if col2.button("Capture Image"):
|
71 |
-
capture_image()
|
72 |
-
st.rerun()
|
73 |
-
|
74 |
-
# Display webcam feed
|
75 |
-
cap = cv2.VideoCapture(0)
|
76 |
-
|
77 |
-
if not cap.isOpened():
|
78 |
-
st.error("Could not open webcam. Please check your camera connection.")
|
79 |
-
else:
|
80 |
-
# Get a frame
|
81 |
-
ret, frame = cap.read()
|
82 |
-
if ret:
|
83 |
-
# Convert to RGB for display
|
84 |
-
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
85 |
-
# Display the frame
|
86 |
-
webcam_placeholder.image(frame_rgb, channels="RGB", caption="Webcam Feed", use_column_width=True)
|
87 |
-
# Store the current frame
|
88 |
-
st.session_state.captured_image = frame.copy()
|
89 |
-
else:
|
90 |
-
st.error("Failed to capture image from webcam.")
|
91 |
-
|
92 |
-
# Release the camera
|
93 |
-
cap.release()
|
94 |
-
|
95 |
-
# Force a rerun to get another frame (creates a video effect)
|
96 |
-
if st.session_state.camera_on:
|
97 |
-
time.sleep(0.1)
|
98 |
-
st.rerun()
|
99 |
-
|
100 |
-
elif st.session_state.captured_image is not None:
|
101 |
-
# We have a captured image - show it and analyze
|
102 |
-
if col1.button("Restart Webcam"):
|
103 |
-
start_webcam()
|
104 |
-
st.rerun()
|
105 |
-
|
106 |
-
if col2.button("Reset"):
|
107 |
-
reset_app()
|
108 |
-
st.rerun()
|
109 |
-
|
110 |
-
# Get the captured image
|
111 |
-
image = st.session_state.captured_image
|
112 |
-
|
113 |
-
# Convert to RGB for display
|
114 |
-
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
115 |
-
|
116 |
-
# Show the captured image
|
117 |
-
captured_image_placeholder.image(image_rgb, caption="Captured Image", use_column_width=True)
|
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 |
st.markdown("---")
|
166 |
st.markdown(
|
|
|
2 |
import cv2
|
3 |
import numpy as np
|
4 |
from deepface import DeepFace
|
5 |
+
from PIL import Image
|
6 |
+
import io
|
7 |
|
8 |
st.set_page_config(
|
9 |
page_title="✨ Age & Gender Predictor",
|
|
|
15 |
st.write(
|
16 |
"""
|
17 |
Welcome to the future of facial analysis!
|
18 |
+
**Take a snapshot with your webcam** and let our cutting-edge AI reveal your age and gender with impressive precision.
|
19 |
|
20 |
**No data is stored**.
|
21 |
"""
|
22 |
)
|
23 |
|
24 |
+
# Initialize session state for analysis results
|
25 |
+
if 'age' not in st.session_state:
|
26 |
+
st.session_state.age = None
|
27 |
+
if 'gender' not in st.session_state:
|
28 |
+
st.session_state.gender = None
|
29 |
+
if 'gender_confidence' not in st.session_state:
|
30 |
+
st.session_state.gender_confidence = None
|
31 |
|
32 |
+
# Streamlit's built-in webcam capture
|
33 |
+
img_file_buffer = st.camera_input("Take a picture with your webcam")
|
|
|
|
|
34 |
|
35 |
+
# If an image was captured
|
36 |
+
if img_file_buffer is not None:
|
37 |
+
# Convert the image buffer to a CV2 image
|
38 |
+
bytes_data = img_file_buffer.getvalue()
|
39 |
+
img_array = np.frombuffer(bytes_data, np.uint8)
|
40 |
+
img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
+
# Display a spinner while analyzing
|
43 |
+
with st.spinner("Analyzing your image with advanced AI models..."):
|
44 |
+
try:
|
45 |
+
# Analyze the image using DeepFace
|
46 |
+
results = DeepFace.analyze(
|
47 |
+
img,
|
48 |
+
actions=['age', 'gender'],
|
49 |
+
detector_backend='retinaface',
|
50 |
+
enforce_detection=True,
|
51 |
+
align=True
|
52 |
+
)
|
53 |
+
|
54 |
+
# Process results
|
55 |
+
if isinstance(results, list) and len(results) > 0:
|
56 |
+
results = sorted(results, key=lambda x: x.get('face_confidence', 0), reverse=True)
|
57 |
+
main_result = results[0]
|
58 |
+
else:
|
59 |
+
main_result = results
|
60 |
+
|
61 |
+
# Store results in session state
|
62 |
+
st.session_state.age = main_result['age']
|
63 |
+
st.session_state.gender = main_result['gender']
|
64 |
+
|
65 |
+
# Handle gender confidence if available
|
66 |
+
if isinstance(main_result['gender'], dict):
|
67 |
+
dominant_gender = max(main_result['gender'], key=main_result['gender'].get)
|
68 |
+
st.session_state.gender = dominant_gender
|
69 |
+
st.session_state.gender_confidence = main_result['gender'][dominant_gender]
|
70 |
+
|
71 |
+
# Display success message
|
72 |
+
st.success("Analysis complete! Here's what we found:")
|
73 |
+
|
74 |
+
# Display detailed results
|
75 |
+
st.write("## Detailed Results")
|
76 |
+
st.write(f"**Predicted Age:** {st.session_state.age} years")
|
77 |
+
|
78 |
+
if st.session_state.gender_confidence:
|
79 |
+
st.write(f"**Predicted Gender:** {st.session_state.gender} ({st.session_state.gender_confidence:.2f}% confidence)")
|
80 |
+
else:
|
81 |
+
st.write(f"**Predicted Gender:** {st.session_state.gender}")
|
82 |
+
|
83 |
+
except Exception as e:
|
84 |
+
st.error(f"Analysis failed: {str(e)}")
|
85 |
+
st.info(
|
86 |
+
"For best results, please try the following tips:\n"
|
87 |
+
"- Ensure good lighting conditions\n"
|
88 |
+
"- Position your face clearly in the frame\n"
|
89 |
+
"- Move closer to the camera if needed"
|
90 |
+
)
|
91 |
|
92 |
st.markdown("---")
|
93 |
st.markdown(
|