ombhojane commited on
Commit
b1326c8
·
verified ·
1 Parent(s): 1637263

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -69
app.py CHANGED
@@ -15,7 +15,15 @@ st.set_page_config(
15
  )
16
 
17
  class DogBehaviorAnalyzer:
18
- def _init_(self):
 
 
 
 
 
 
 
 
19
  # Use a more sophisticated pre-trained model (ResNet50 with ImageNet weights)
20
  self.model = models.resnet50(pretrained=True)
21
 
@@ -96,109 +104,105 @@ def main():
96
  video_file = st.file_uploader("Upload Video", type=['mp4', 'avi', 'mov', 'mkv'])
97
 
98
  if video_file is not None:
99
- try:
100
- # Save uploaded file temporarily
101
- tfile = tempfile.NamedTemporaryFile(delete=False)
102
- tfile.write(video_file.read())
103
 
104
- # Video analysis
105
- cap = cv2.VideoCapture(tfile.name)
106
 
107
- # Create columns for layout
108
- col1, col2 = st.columns(2)
109
 
110
- with col1:
111
  st.subheader("Video Preview")
112
- video_placeholder = st.empty()
113
-
114
- with col2:
115
- st.subheader("Real-time Analysis")
116
- analysis_placeholder = st.empty()
117
 
118
- # Progress bar
119
- progress_bar = st.progress(0)
120
 
121
- # Analysis results storage
122
- behavior_counts = {behavior: 0 for behavior in analyzer.behaviors.keys()}
123
 
124
- frame_count = 0
125
- total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
126
 
127
- while cap.isOpened():
128
- ret, frame = cap.read()
129
- if not ret:
130
- break
131
 
132
- frame_count += 1
133
- progress = frame_count / total_frames
134
- progress_bar.progress(progress)
135
 
136
- # Update video preview
137
- video_placeholder.image(
138
- cv2.cvtColor(frame, cv2.COLOR_BGR2RGB),
139
- channels="RGB",
140
- use_container_width=True # Changed from use_column_width
141
  )
142
 
143
- # Analyze frame
144
- detected_behaviors = analyzer.analyze_frame(frame)
145
- for behavior in detected_behaviors:
146
- behavior_counts[behavior] += 1
147
 
148
  # Update analysis display
149
- analysis_text = "Detected Behaviors:\n\n"
150
- for behavior, count in behavior_counts.items():
151
- if count > 0:
152
- confidence = sum(behavior_scores[behavior]) / count
153
- analysis_text += (f"• {behavior.replace('_', ' ').title()}: "
154
- f"{count} times (Confidence: {confidence:.2%})\n"
155
  f" {analyzer.behaviors[behavior]['description']}\n\n")
156
 
157
- analysis_placeholder.text_area(
158
  "Analysis Results",
159
  analysis_text,
160
  height=300,
161
  key=f"analysis_{frame_count}"
162
  )
163
 
164
- time.sleep(0.1) # Add small delay for visualization
165
 
166
- cap.release()
167
 
168
- # Final summary
169
- st.subheader("Analysis Summary")
170
- st.write("Overall behavior analysis of your dog:")
171
 
172
- # Create summary metrics
173
- col1, col2, col3 = st.columns(3)
174
 
175
- with col1:
176
- most_common = max(behavior_counts.items(), key=lambda x: x[1])[0]
177
- st.metric("Most Common Behavior", most_common.replace('_', ' ').title())
178
 
179
- with col2:
180
- total_behaviors = sum(behavior_counts.values())
181
- st.metric("Total Behaviors Detected", total_behaviors)
182
 
183
- with col3:
184
- behavior_variety = len([b for b in behavior_counts.values() if b > 0])
185
- st.metric("Behavior Variety", f"{behavior_variety} types")
186
 
187
- # Recommendations
188
- st.subheader("Recommendations")
189
- if total_behaviors > 0:
190
- st.write("""
191
  Based on the analysis, here are some recommendations:
192
  - Maintain regular exercise routines
193
  - Provide mental stimulation through toys and training
194
  - Continue positive reinforcement training
195
  - Monitor your dog's body language for better communication
196
  """)
197
- else:
198
- st.write("No behaviors detected. Try uploading a different video with clearer dog movements.")
199
-
200
- except Exception as e:
201
- st.error(f"An error occurred: {str(e)}")
202
 
203
  if __name__ == "__main__":
204
  main()
 
15
  )
16
 
17
  class DogBehaviorAnalyzer:
18
+
19
+ behaviors = {
20
+ 'tail_wagging': {'description': 'Your dog is happy and excited!', 'threshold': 0.75},
21
+ 'barking': {'description': 'Your dog is trying to communicate or alert you.', 'threshold': 0.80},
22
+ 'ears_perked': {'description': 'Your dog is alert and interested.', 'threshold': 0.70},
23
+ 'lying_down': {'description': 'Your dog is relaxed and comfortable.', 'threshold': 0.85},
24
+ 'jumping': {'description': 'Your dog is energetic and playful!', 'threshold': 0.75}
25
+ }
26
+ def __init__(self):
27
  # Use a more sophisticated pre-trained model (ResNet50 with ImageNet weights)
28
  self.model = models.resnet50(pretrained=True)
29
 
 
104
  video_file = st.file_uploader("Upload Video", type=['mp4', 'avi', 'mov', 'mkv'])
105
 
106
  if video_file is not None:
107
+ # Save uploaded file temporarily
108
+ tfile = tempfile.NamedTemporaryFile(delete=False)
109
+ tfile.write(video_file.read())
 
110
 
111
+ # Video analysis
112
+ cap = cv2.VideoCapture(tfile.name)
113
 
114
+ # Create columns for layout
115
+ col1, col2 = st.columns(2)
116
 
117
+ with col1:
118
  st.subheader("Video Preview")
119
+ video_placeholder = st.empty()
120
+
121
+ with col2:
122
+ st.subheader("Real-time Analysis")
123
+ analysis_placeholder = st.empty()
124
 
125
+ # Progress bar
126
+ progress_bar = st.progress(0)
127
 
128
+ # Analysis results storage
129
+ behavior_counts = {behavior: 0 for behavior in analyzer.behaviors.keys()}
130
 
131
+ frame_count = 0
132
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
133
 
134
+ while cap.isOpened():
135
+ ret, frame = cap.read()
136
+ if not ret:
137
+ break
138
 
139
+ frame_count += 1
140
+ progress = frame_count / total_frames
141
+ progress_bar.progress(progress)
142
 
143
+ # Update video preview
144
+ video_placeholder.image(
145
+ cv2.cvtColor(frame, cv2.COLOR_BGR2RGB),
146
+ channels="RGB",
147
+ use_container_width=True # Changed from use_column_width
148
  )
149
 
150
+ # Analyze frame
151
+ detected_behaviors = analyzer.analyze_frame(frame)
152
+ for behavior in detected_behaviors:
153
+ behavior_counts[behavior] += 1
154
 
155
  # Update analysis display
156
+ analysis_text = "Detected Behaviors:\n\n"
157
+ for behavior, count in behavior_counts.items():
158
+ if count > 0:
159
+ confidence = sum(behavior_scores[behavior]) / count
160
+ analysis_text += (f"• {behavior.replace('_', ' ').title()}: "
161
+ f"{count} times (Confidence: {confidence:.2%})\n"
162
  f" {analyzer.behaviors[behavior]['description']}\n\n")
163
 
164
+ analysis_placeholder.text_area(
165
  "Analysis Results",
166
  analysis_text,
167
  height=300,
168
  key=f"analysis_{frame_count}"
169
  )
170
 
171
+ time.sleep(0.1) # Add small delay for visualization
172
 
173
+ cap.release()
174
 
175
+ # Final summary
176
+ st.subheader("Analysis Summary")
177
+ st.write("Overall behavior analysis of your dog:")
178
 
179
+ # Create summary metrics
180
+ col1, col2, col3 = st.columns(3)
181
 
182
+ with col1:
183
+ most_common = max(behavior_counts.items(), key=lambda x: x[1])[0]
184
+ st.metric("Most Common Behavior", most_common.replace('_', ' ').title())
185
 
186
+ with col2:
187
+ total_behaviors = sum(behavior_counts.values())
188
+ st.metric("Total Behaviors Detected", total_behaviors)
189
 
190
+ with col3:
191
+ behavior_variety = len([b for b in behavior_counts.values() if b > 0])
192
+ st.metric("Behavior Variety", f"{behavior_variety} types")
193
 
194
+ # Recommendations
195
+ st.subheader("Recommendations")
196
+ if total_behaviors > 0:
197
+ st.write("""
198
  Based on the analysis, here are some recommendations:
199
  - Maintain regular exercise routines
200
  - Provide mental stimulation through toys and training
201
  - Continue positive reinforcement training
202
  - Monitor your dog's body language for better communication
203
  """)
204
+ else:
205
+ st.write("No behaviors detected. Try uploading a different video with clearer dog movements.")
 
 
 
206
 
207
  if __name__ == "__main__":
208
  main()