ombhojane commited on
Commit
9b66cdf
Β·
verified Β·
1 Parent(s): 7c5c7b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -68
app.py CHANGED
@@ -123,10 +123,7 @@ def main():
123
  st.title("πŸ• Dog Language Understanding")
124
  st.write("Upload a video of your dog to analyze their behavior and emotions!")
125
 
126
- # Initialize analyzer
127
  analyzer = DogBehaviorAnalyzer()
128
-
129
- # File uploader
130
  video_file = st.file_uploader("Upload Video", type=['mp4', 'avi', 'mov'])
131
 
132
  if video_file is not None:
@@ -134,7 +131,7 @@ def main():
134
  tfile = tempfile.NamedTemporaryFile(delete=False)
135
  tfile.write(video_file.read())
136
 
137
- # Video analysis
138
  cap = cv2.VideoCapture(tfile.name)
139
 
140
  # Create columns for layout
@@ -143,14 +140,6 @@ def main():
143
  with col1:
144
  st.subheader("Video Preview")
145
  video_placeholder = st.empty()
146
-
147
- with col2:
148
- st.subheader("Real-time Analysis")
149
- analysis_placeholder = st.empty()
150
- emotion_placeholder = st.empty()
151
-
152
- # Progress bar
153
- progress_bar = st.progress(0)
154
 
155
  # Analysis results storage
156
  behavior_counts = {behavior: 0 for behavior in analyzer.behaviors.keys()}
@@ -159,6 +148,10 @@ def main():
159
  frame_count = 0
160
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
161
 
 
 
 
 
162
  while cap.isOpened():
163
  ret, frame = cap.read()
164
  if not ret:
@@ -167,71 +160,67 @@ def main():
167
  frame_count += 1
168
  progress = frame_count / total_frames
169
  progress_bar.progress(progress)
 
170
 
171
- # Update video preview
172
- video_placeholder.image(
173
- cv2.cvtColor(frame, cv2.COLOR_BGR2RGB),
174
- channels="RGB",
175
- use_container_width=True # Changed from use_column_width
176
- )
 
177
 
178
  # Analyze frame
179
  detected_behaviors = analyzer.analyze_frame(frame)
180
  for behavior in detected_behaviors:
181
  behavior_counts[behavior] += 1
182
  current_emotions.add(behavior)
183
-
184
- # Update analysis display with enhanced information
185
- analysis_text = "Detected Behaviors & Emotions:\n\n"
186
- for behavior, count in behavior_counts.items():
187
- if count > 0:
188
- behavior_info = analyzer.behaviors[behavior]
189
- analysis_text += f"β€’ {behavior.replace('_', ' ').title()}: {count} times\n"
190
- analysis_text += f" Emotion: {behavior_info['emotion']}\n"
191
- analysis_text += f" {behavior_info['description']}\n\n"
192
-
193
- # Add animation for the behavior
194
- animation_data = analyzer.create_animation(behavior)
195
- st.image(f"data:image/png;base64,{animation_data}",
196
- width=100,
197
- caption=f"{behavior.replace('_', ' ').title()} Animation")
198
-
199
- analysis_placeholder.text_area(
200
- "Analysis Results",
201
- analysis_text,
202
- height=300
203
- )
204
-
205
- # Display training tips
206
- if len(current_emotions) > 0:
207
- st.subheader("Training Tips")
208
- for behavior in current_emotions:
209
- tips = analyzer.behaviors[behavior]['tips']
210
- for tip in tips:
211
- st.info(tip)
212
-
213
- time.sleep(0.1)
214
 
215
  cap.release()
 
216
 
217
- # Final summary with enhanced visualizations
218
- st.subheader("Analysis Summary")
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  # Create emotion timeline
221
- emotions_df = pd.DataFrame(list(current_emotions), columns=['Emotion'])
222
- fig = go.Figure(data=[go.Scatter(x=emotions_df.index,
223
- y=emotions_df['Emotion'],
224
- mode='lines+markers')])
225
- fig.update_layout(title='Emotional Journey',
226
- xaxis_title='Time',
227
- yaxis_title='Emotion')
228
- st.plotly_chart(fig)
 
 
 
 
 
 
229
 
230
- # Final summary
231
  st.subheader("Analysis Summary")
232
- st.write("Overall behavior analysis of your dog:")
233
-
234
- # Create summary metrics
235
  col1, col2, col3 = st.columns(3)
236
 
237
  with col1:
@@ -246,23 +235,23 @@ def main():
246
  behavior_variety = len([b for b in behavior_counts.values() if b > 0])
247
  st.metric("Behavior Variety", f"{behavior_variety} types")
248
 
249
- # Enhanced recommendations
250
- st.subheader("Personalized Recommendations")
251
  if total_behaviors > 0:
 
252
  dominant_behavior = max(behavior_counts.items(), key=lambda x: x[1])[0]
253
  st.write(f"""
254
- Based on the analysis, here are personalized recommendations for {dominant_behavior}:
255
 
256
  {' '.join(analyzer.behaviors[dominant_behavior]['tips'])}
257
 
258
- General recommendations:
259
  - Maintain regular exercise routines
260
  - Provide mental stimulation through toys and training
261
  - Continue positive reinforcement training
262
  - Monitor your dog's body language for better communication
263
  """)
264
  else:
265
- st.write("No behaviors detected. Try uploading a different video with clearer dog movements.")
266
 
267
  if __name__ == "__main__":
268
  main()
 
123
  st.title("πŸ• Dog Language Understanding")
124
  st.write("Upload a video of your dog to analyze their behavior and emotions!")
125
 
 
126
  analyzer = DogBehaviorAnalyzer()
 
 
127
  video_file = st.file_uploader("Upload Video", type=['mp4', 'avi', 'mov'])
128
 
129
  if video_file is not None:
 
131
  tfile = tempfile.NamedTemporaryFile(delete=False)
132
  tfile.write(video_file.read())
133
 
134
+ # Video processing
135
  cap = cv2.VideoCapture(tfile.name)
136
 
137
  # Create columns for layout
 
140
  with col1:
141
  st.subheader("Video Preview")
142
  video_placeholder = st.empty()
 
 
 
 
 
 
 
 
143
 
144
  # Analysis results storage
145
  behavior_counts = {behavior: 0 for behavior in analyzer.behaviors.keys()}
 
148
  frame_count = 0
149
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
150
 
151
+ # Progress bar
152
+ progress_bar = st.progress(0)
153
+ progress_text = st.empty()
154
+
155
  while cap.isOpened():
156
  ret, frame = cap.read()
157
  if not ret:
 
160
  frame_count += 1
161
  progress = frame_count / total_frames
162
  progress_bar.progress(progress)
163
+ progress_text.text(f"Analyzing video: {int(progress * 100)}%")
164
 
165
+ # Update video preview periodically (every 5th frame)
166
+ if frame_count % 5 == 0:
167
+ video_placeholder.image(
168
+ cv2.cvtColor(frame, cv2.COLOR_BGR2RGB),
169
+ channels="RGB",
170
+ use_container_width=True
171
+ )
172
 
173
  # Analyze frame
174
  detected_behaviors = analyzer.analyze_frame(frame)
175
  for behavior in detected_behaviors:
176
  behavior_counts[behavior] += 1
177
  current_emotions.add(behavior)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
  cap.release()
180
+ progress_text.empty()
181
 
182
+ # Display final analysis
183
+ st.subheader("Behavior Analysis Results")
184
 
185
+ # Display detected behaviors and their interpretations
186
+ for behavior, count in behavior_counts.items():
187
+ if count > 0:
188
+ with st.expander(f"{behavior.replace('_', ' ').title()} - Detected {count} times"):
189
+ behavior_info = analyzer.behaviors[behavior]
190
+ st.write(f"**Emotion:** {behavior_info['emotion']}")
191
+ st.write(f"**Description:** {behavior_info['description']}")
192
+
193
+ # Display behavior animation
194
+ animation_data = analyzer.create_animation(behavior)
195
+ st.image(
196
+ f"data:image/png;base64,{animation_data}",
197
+ width=100,
198
+ caption=f"{behavior.replace('_', ' ').title()} Visual"
199
+ )
200
+
201
+ # Display training tips
202
+ st.subheader("Training Tips:")
203
+ for tip in behavior_info['tips']:
204
+ st.info(tip)
205
+
206
  # Create emotion timeline
207
+ if current_emotions:
208
+ st.subheader("Emotional Journey")
209
+ emotions_df = pd.DataFrame(list(current_emotions), columns=['Emotion'])
210
+ fig = go.Figure(data=[go.Scatter(
211
+ x=emotions_df.index,
212
+ y=emotions_df['Emotion'],
213
+ mode='lines+markers'
214
+ )])
215
+ fig.update_layout(
216
+ xaxis_title='Time',
217
+ yaxis_title='Emotion',
218
+ height=400
219
+ )
220
+ st.plotly_chart(fig, use_container_width=True)
221
 
222
+ # Summary metrics
223
  st.subheader("Analysis Summary")
 
 
 
224
  col1, col2, col3 = st.columns(3)
225
 
226
  with col1:
 
235
  behavior_variety = len([b for b in behavior_counts.values() if b > 0])
236
  st.metric("Behavior Variety", f"{behavior_variety} types")
237
 
238
+ # Final recommendations
 
239
  if total_behaviors > 0:
240
+ st.subheader("Personalized Recommendations")
241
  dominant_behavior = max(behavior_counts.items(), key=lambda x: x[1])[0]
242
  st.write(f"""
243
+ Based on the analysis, here are personalized recommendations for your dog's dominant behavior ({dominant_behavior.replace('_', ' ')}):
244
 
245
  {' '.join(analyzer.behaviors[dominant_behavior]['tips'])}
246
 
247
+ **General recommendations:**
248
  - Maintain regular exercise routines
249
  - Provide mental stimulation through toys and training
250
  - Continue positive reinforcement training
251
  - Monitor your dog's body language for better communication
252
  """)
253
  else:
254
+ st.warning("No behaviors detected. Try uploading a different video with clearer dog movements.")
255
 
256
  if __name__ == "__main__":
257
  main()