suhail0318 commited on
Commit
c3b7a65
·
verified ·
1 Parent(s): cf2d9dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -74
app.py CHANGED
@@ -20,45 +20,56 @@ st.write(
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)
@@ -78,21 +89,23 @@ if st.session_state.camera_on:
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
@@ -103,50 +116,51 @@ elif st.session_state.captured_image is not None:
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(
 
20
  """
21
  )
22
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  # Initialize session state variables if they don't exist
24
  if 'camera_on' not in st.session_state:
25
  st.session_state.camera_on = False
26
  if 'captured_image' not in st.session_state:
27
  st.session_state.captured_image = None
28
+ if 'analyzed' not in st.session_state:
29
+ st.session_state.analyzed = False
30
 
31
  # Function to start webcam
32
  def start_webcam():
33
  st.session_state.camera_on = True
34
+ st.session_state.analyzed = False
35
 
36
  # Function to capture image
37
  def capture_image():
38
  st.session_state.camera_on = False
39
+ st.session_state.analyzed = False
40
+
41
+ # Function to reset
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)
 
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
 
116
  # Show the captured image
117
  captured_image_placeholder.image(image_rgb, caption="Captured Image", use_column_width=True)
118
 
119
+ # Analyze the image if not already analyzed
120
+ if not st.session_state.analyzed:
121
+ with results_area:
122
+ with st.spinner("Analyzing your image with advanced AI models..."):
123
+ try:
124
+ results = DeepFace.analyze(
125
+ image,
126
+ actions=['age', 'gender'],
127
+ detector_backend='retinaface',
128
+ enforce_detection=True,
129
+ align=True
130
+ )
131
+
132
+ if isinstance(results, list):
133
+ results = sorted(results, key=lambda x: x.get('face_confidence', 0), reverse=True)
134
+ main_result = results[0]
135
+ else:
136
+ main_result = results
137
+
138
+ st.success("Analysis complete! Here's what we found:")
139
+ st.write("## Detailed Results")
140
+
141
+ age = main_result['age']
142
+ st.write(f"**Predicted Age:** {age} years")
143
+
144
+ gender = main_result['gender']
145
+ dominant_gender = gender if isinstance(gender, str) else max(gender, key=gender.get)
146
+ confidence = gender[dominant_gender] if isinstance(gender, dict) else None
147
+
148
+ if confidence:
149
+ st.write(f"**Predicted Gender:** {dominant_gender} ({confidence:.2f}% confidence)")
150
+ else:
151
+ st.write(f"**Predicted Gender:** {dominant_gender}")
152
+
153
+ # Set analyzed flag to avoid re-analyzing on reruns
154
+ st.session_state.analyzed = True
155
 
156
+ except Exception as e:
157
+ st.error(f"Analysis failed: {str(e)}")
158
+ st.info(
159
+ "For best results, please try the following tips:\n"
160
+ "- Ensure good lighting conditions\n"
161
+ "- Position your face clearly in the frame\n"
162
+ "- Move closer to the camera if needed"
163
+ )
 
 
 
 
 
 
 
 
164
 
165
  st.markdown("---")
166
  st.markdown(