Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
import tempfile
|
5 |
+
from pathlib import Path
|
6 |
+
from typing import Union, Optional
|
7 |
+
import torch
|
8 |
+
import logging
|
9 |
+
import sys
|
10 |
+
from Object_Flow_Tracker import YOLOFlowTracker # Import the original tracker class
|
11 |
+
|
12 |
+
# Configure logging
|
13 |
+
logging.basicConfig(
|
14 |
+
level=logging.INFO,
|
15 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
16 |
+
stream=sys.stdout
|
17 |
+
)
|
18 |
+
logger = logging.getLogger(__name__)
|
19 |
+
|
20 |
+
class StreamlitFlowTracker:
|
21 |
+
def __init__(self):
|
22 |
+
"""Initialize the Streamlit Flow Tracker application."""
|
23 |
+
st.set_page_config(page_title="Object Flow Tracker", layout="wide")
|
24 |
+
self.setup_sidebar()
|
25 |
+
self.initialize_session_state()
|
26 |
+
self.tracker = None
|
27 |
+
self.initialize_tracker()
|
28 |
+
|
29 |
+
def setup_sidebar(self):
|
30 |
+
"""Setup the sidebar with configuration options."""
|
31 |
+
st.sidebar.title("Settings")
|
32 |
+
|
33 |
+
# Model settings
|
34 |
+
st.sidebar.header("Model Configuration")
|
35 |
+
self.confidence_threshold = st.sidebar.slider(
|
36 |
+
"Confidence Threshold",
|
37 |
+
min_value=0.0,
|
38 |
+
max_value=1.0,
|
39 |
+
value=0.5,
|
40 |
+
step=0.05
|
41 |
+
)
|
42 |
+
|
43 |
+
# Tracking settings
|
44 |
+
st.sidebar.header("Tracking Configuration")
|
45 |
+
self.grid_size = st.sidebar.slider(
|
46 |
+
"Grid Size (pixels)",
|
47 |
+
min_value=10,
|
48 |
+
max_value=50,
|
49 |
+
value=20,
|
50 |
+
step=5
|
51 |
+
)
|
52 |
+
|
53 |
+
self.window_size = st.sidebar.slider(
|
54 |
+
"Window Size",
|
55 |
+
min_value=7,
|
56 |
+
max_value=31,
|
57 |
+
value=21,
|
58 |
+
step=2
|
59 |
+
)
|
60 |
+
|
61 |
+
# Display settings
|
62 |
+
st.sidebar.header("Display Settings")
|
63 |
+
self.display_fps = st.sidebar.checkbox("Show FPS", value=True)
|
64 |
+
self.display_grid = st.sidebar.checkbox("Show Flow Grid", value=True)
|
65 |
+
|
66 |
+
def initialize_session_state(self):
|
67 |
+
"""Initialize session state variables."""
|
68 |
+
if 'processing' not in st.session_state:
|
69 |
+
st.session_state.processing = False
|
70 |
+
if 'camera_active' not in st.session_state:
|
71 |
+
st.session_state.camera_active = False
|
72 |
+
if 'frame_count' not in st.session_state:
|
73 |
+
st.session_state.frame_count = 0
|
74 |
+
|
75 |
+
def initialize_tracker(self):
|
76 |
+
"""Initialize the YOLO Flow Tracker with current settings."""
|
77 |
+
try:
|
78 |
+
model_path = "yolov8n.pt" # Ensure this path is correct
|
79 |
+
self.tracker = YOLOFlowTracker(
|
80 |
+
yolo_model_path=model_path,
|
81 |
+
confidence_threshold=self.confidence_threshold,
|
82 |
+
window_size=self.window_size,
|
83 |
+
grid_size=self.grid_size
|
84 |
+
)
|
85 |
+
logger.info("Tracker initialized successfully")
|
86 |
+
except Exception as e:
|
87 |
+
st.error(f"Error initializing tracker: {str(e)}")
|
88 |
+
logger.error(f"Tracker initialization failed: {str(e)}")
|
89 |
+
|
90 |
+
def process_frame(self, frame: np.ndarray) -> np.ndarray:
|
91 |
+
"""Process a single frame using the tracker."""
|
92 |
+
if self.tracker is None:
|
93 |
+
return frame
|
94 |
+
|
95 |
+
try:
|
96 |
+
processed_frame = self.tracker.process_frame(frame)
|
97 |
+
return processed_frame if processed_frame is not None else frame
|
98 |
+
except Exception as e:
|
99 |
+
logger.error(f"Error processing frame: {str(e)}")
|
100 |
+
return frame
|
101 |
+
|
102 |
+
def handle_video_upload(self) -> Optional[str]:
|
103 |
+
"""Handle video file upload and return the path."""
|
104 |
+
uploaded_file = st.file_uploader("Choose a video file", type=['mp4', 'avi', 'mov'])
|
105 |
+
if uploaded_file is not None:
|
106 |
+
try:
|
107 |
+
# Create a temporary file to store the uploaded video
|
108 |
+
tfile = tempfile.NamedTemporaryFile(delete=False)
|
109 |
+
tfile.write(uploaded_file.read())
|
110 |
+
return tfile.name
|
111 |
+
except Exception as e:
|
112 |
+
st.error(f"Error handling uploaded file: {str(e)}")
|
113 |
+
return None
|
114 |
+
return None
|
115 |
+
|
116 |
+
def run_video_processing(self, video_path: str):
|
117 |
+
"""Process a video file and display results."""
|
118 |
+
try:
|
119 |
+
cap = cv2.VideoCapture(video_path)
|
120 |
+
stframe = st.empty()
|
121 |
+
stop_button = st.button("Stop Processing")
|
122 |
+
|
123 |
+
while cap.isOpened() and not stop_button:
|
124 |
+
ret, frame = cap.read()
|
125 |
+
if not ret:
|
126 |
+
break
|
127 |
+
|
128 |
+
processed_frame = self.process_frame(frame)
|
129 |
+
processed_frame = cv2.cvtColor(processed_frame, cv2.COLOR_BGR2RGB)
|
130 |
+
stframe.image(processed_frame, channels="RGB", use_column_width=True)
|
131 |
+
|
132 |
+
if st.session_state.get('stop_processing', False):
|
133 |
+
break
|
134 |
+
|
135 |
+
cap.release()
|
136 |
+
|
137 |
+
except Exception as e:
|
138 |
+
st.error(f"Error processing video: {str(e)}")
|
139 |
+
logger.error(f"Video processing error: {str(e)}")
|
140 |
+
|
141 |
+
def run_camera_stream(self):
|
142 |
+
"""Handle live camera stream processing."""
|
143 |
+
try:
|
144 |
+
cap = cv2.VideoCapture(0)
|
145 |
+
stframe = st.empty()
|
146 |
+
stop_button = st.button("Stop Camera")
|
147 |
+
|
148 |
+
while cap.isOpened() and not stop_button:
|
149 |
+
ret, frame = cap.read()
|
150 |
+
if not ret:
|
151 |
+
break
|
152 |
+
|
153 |
+
processed_frame = self.process_frame(frame)
|
154 |
+
processed_frame = cv2.cvtColor(processed_frame, cv2.COLOR_BGR2RGB)
|
155 |
+
stframe.image(processed_frame, channels="RGB", use_column_width=True)
|
156 |
+
|
157 |
+
if st.session_state.get('stop_processing', False):
|
158 |
+
break
|
159 |
+
|
160 |
+
cap.release()
|
161 |
+
|
162 |
+
except Exception as e:
|
163 |
+
st.error(f"Error accessing camera: {str(e)}")
|
164 |
+
logger.error(f"Camera stream error: {str(e)}")
|
165 |
+
|
166 |
+
def run(self):
|
167 |
+
"""Main application loop."""
|
168 |
+
st.title("Object Flow Tracker")
|
169 |
+
|
170 |
+
# Input source selection
|
171 |
+
source_type = st.radio("Select Input Source", ["Camera", "Video File"])
|
172 |
+
|
173 |
+
if source_type == "Video File":
|
174 |
+
video_path = self.handle_video_upload()
|
175 |
+
if video_path and st.button("Process Video"):
|
176 |
+
st.session_state.processing = True
|
177 |
+
self.run_video_processing(video_path)
|
178 |
+
|
179 |
+
else: # Camera option
|
180 |
+
if st.button("Start Camera"):
|
181 |
+
st.session_state.camera_active = True
|
182 |
+
self.run_camera_stream()
|
183 |
+
|
184 |
+
# Display device information
|
185 |
+
device = "GPU (CUDA)" if torch.cuda.is_available() else "CPU"
|
186 |
+
st.sidebar.info(f"Running on: {device}")
|
187 |
+
|
188 |
+
def main():
|
189 |
+
app = StreamlitFlowTracker()
|
190 |
+
app.run()
|
191 |
+
|
192 |
+
if __name__ == "__main__":
|
193 |
+
main()
|