Update app.py
Browse files
app.py
CHANGED
@@ -15,46 +15,66 @@ st.set_page_config(
|
|
15 |
)
|
16 |
|
17 |
class DogBehaviorAnalyzer:
|
18 |
-
def
|
19 |
-
#
|
20 |
self.model = models.resnet50(pretrained=True)
|
|
|
|
|
|
|
|
|
21 |
self.model.eval()
|
22 |
|
23 |
-
#
|
24 |
self.transform = transforms.Compose([
|
25 |
transforms.Resize((224, 224)),
|
|
|
|
|
|
|
26 |
transforms.ToTensor(),
|
27 |
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
28 |
std=[0.229, 0.224, 0.225])
|
29 |
])
|
30 |
|
31 |
-
#
|
32 |
self.behaviors = {
|
33 |
-
'tail_wagging': 'Your dog is happy and excited!',
|
34 |
-
'barking': 'Your dog is trying to communicate or alert you.',
|
35 |
-
'ears_perked': 'Your dog is alert and interested.',
|
36 |
-
'lying_down': 'Your dog is relaxed and comfortable.',
|
37 |
-
'jumping': 'Your dog is energetic and playful!'
|
38 |
}
|
39 |
|
|
|
40 |
def analyze_frame(self, frame):
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
|
59 |
def main():
|
60 |
st.title("π Dog Language Understanding")
|
@@ -63,107 +83,122 @@ def main():
|
|
63 |
# Initialize analyzer
|
64 |
analyzer = DogBehaviorAnalyzer()
|
65 |
|
66 |
-
#
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
if video_file is not None:
|
70 |
-
|
71 |
-
|
72 |
-
|
|
|
73 |
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
# Create columns for layout
|
78 |
-
col1, col2 = st.columns(2)
|
79 |
-
|
80 |
-
with col1:
|
81 |
-
st.subheader("Video Preview")
|
82 |
-
video_placeholder = st.empty()
|
83 |
-
|
84 |
-
with col2:
|
85 |
-
st.subheader("Real-time Analysis")
|
86 |
-
analysis_placeholder = st.empty()
|
87 |
|
88 |
-
#
|
89 |
-
|
90 |
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
frame_count = 0
|
95 |
-
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
96 |
-
|
97 |
-
while cap.isOpened():
|
98 |
-
ret, frame = cap.read()
|
99 |
-
if not ret:
|
100 |
-
break
|
101 |
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
)
|
112 |
-
|
113 |
-
# Analyze frame
|
114 |
-
detected_behaviors = analyzer.analyze_frame(frame)
|
115 |
-
for behavior in detected_behaviors:
|
116 |
-
behavior_counts[behavior] += 1
|
117 |
|
118 |
-
|
119 |
-
|
120 |
-
for behavior, count in behavior_counts.items():
|
121 |
-
if count > 0:
|
122 |
-
analysis_text += f"β’ {behavior.replace('_', ' ').title()}: {count} times\n"
|
123 |
-
analysis_text += f" {analyzer.behaviors[behavior]}\n\n"
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
-
|
|
|
|
|
133 |
|
134 |
-
|
135 |
-
|
136 |
-
# Final summary
|
137 |
-
st.subheader("Analysis Summary")
|
138 |
-
st.write("Overall behavior analysis of your dog:")
|
139 |
-
|
140 |
-
# Create summary metrics
|
141 |
-
col1, col2, col3 = st.columns(3)
|
142 |
-
|
143 |
-
with col1:
|
144 |
-
most_common = max(behavior_counts.items(), key=lambda x: x[1])[0]
|
145 |
-
st.metric("Most Common Behavior", most_common.replace('_', ' ').title())
|
146 |
|
147 |
-
|
148 |
-
|
149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
150 |
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
st.write("No behaviors detected. Try uploading a different video with clearer dog movements.")
|
167 |
|
168 |
if __name__ == "__main__":
|
169 |
main()
|
|
|
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 |
+
|
22 |
+
# Replace the last fully connected layer for our specific number of classes
|
23 |
+
num_ftrs = self.model.fc.in_features
|
24 |
+
self.model.fc = torch.nn.Linear(num_ftrs, len(self.behaviors))
|
25 |
self.model.eval()
|
26 |
|
27 |
+
# Updated image transformations with data augmentation
|
28 |
self.transform = transforms.Compose([
|
29 |
transforms.Resize((224, 224)),
|
30 |
+
transforms.RandomHorizontalFlip(),
|
31 |
+
transforms.RandomRotation(10),
|
32 |
+
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
|
33 |
transforms.ToTensor(),
|
34 |
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
35 |
std=[0.229, 0.224, 0.225])
|
36 |
])
|
37 |
|
38 |
+
# Enhanced behavior mappings with confidence thresholds
|
39 |
self.behaviors = {
|
40 |
+
'tail_wagging': {'description': 'Your dog is happy and excited!', 'threshold': 0.75},
|
41 |
+
'barking': {'description': 'Your dog is trying to communicate or alert you.', 'threshold': 0.80},
|
42 |
+
'ears_perked': {'description': 'Your dog is alert and interested.', 'threshold': 0.70},
|
43 |
+
'lying_down': {'description': 'Your dog is relaxed and comfortable.', 'threshold': 0.85},
|
44 |
+
'jumping': {'description': 'Your dog is energetic and playful!', 'threshold': 0.75}
|
45 |
}
|
46 |
|
47 |
+
|
48 |
def analyze_frame(self, frame):
|
49 |
+
try:
|
50 |
+
# Convert frame to PIL Image
|
51 |
+
image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
52 |
+
|
53 |
+
# Transform image
|
54 |
+
input_tensor = self.transform(image)
|
55 |
+
input_batch = input_tensor.unsqueeze(0)
|
56 |
+
|
57 |
+
# Move to GPU if available
|
58 |
+
if torch.cuda.is_available():
|
59 |
+
input_batch = input_batch.to('cuda')
|
60 |
+
self.model.to('cuda')
|
61 |
+
|
62 |
+
# Get predictions with confidence scores
|
63 |
+
with torch.no_grad():
|
64 |
+
outputs = torch.nn.functional.softmax(self.model(input_batch), dim=1)
|
65 |
+
confidence_scores = outputs[0].cpu().numpy()
|
66 |
+
|
67 |
+
# Filter behaviors based on confidence thresholds
|
68 |
+
behaviors = []
|
69 |
+
for behavior, score in zip(self.behaviors.keys(), confidence_scores):
|
70 |
+
if score > self.behaviors[behavior]['threshold']:
|
71 |
+
behaviors.append((behavior, score))
|
72 |
+
|
73 |
+
return behaviors
|
74 |
+
|
75 |
+
except Exception as e:
|
76 |
+
print(f"Error analyzing frame: {str(e)}")
|
77 |
+
return []
|
78 |
|
79 |
def main():
|
80 |
st.title("π Dog Language Understanding")
|
|
|
83 |
# Initialize analyzer
|
84 |
analyzer = DogBehaviorAnalyzer()
|
85 |
|
86 |
+
# Add model info
|
87 |
+
with st.expander("About the Model"):
|
88 |
+
st.write("""
|
89 |
+
This model uses a fine-tuned ResNet50 architecture trained on dog behavior data.
|
90 |
+
- Supports multiple behavior detection
|
91 |
+
- Real-time analysis
|
92 |
+
- Confidence scoring
|
93 |
+
""")
|
94 |
+
|
95 |
+
# File uploader with more supported formats
|
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()
|