Spaces:
Sleeping
Sleeping
Upload 9 files
Browse files- app.py +51 -0
- gully_drs_core/ball_detection.py +91 -0
- gully_drs_core/init__.py +1 -0
- gully_drs_core/model_utils.py +17 -0
- gully_drs_core/replay_utils.py +61 -0
- gully_drs_core/video_utils.py +21 -0
- pages/live_match.py +5 -0
- pages/upload_analysis.py +5 -0
- requirements.txt +6 -0
app.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
import logging
|
4 |
+
from gully_drs_core.ball_detection import process_video
|
5 |
+
|
6 |
+
# Set up logging
|
7 |
+
logging.basicConfig(level=logging.INFO)
|
8 |
+
logger = logging.getLogger(__name__)
|
9 |
+
|
10 |
+
# Streamlit configuration
|
11 |
+
st.set_page_config(page_title="GullyDRS", layout="wide")
|
12 |
+
st.title("GullyDRS - AI-Powered Decision Review System")
|
13 |
+
|
14 |
+
# Directories for uploads and outputs
|
15 |
+
UPLOAD_DIR = "uploads"
|
16 |
+
OUTPUT_DIR = "outputs"
|
17 |
+
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
18 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
19 |
+
|
20 |
+
def main():
|
21 |
+
st.header("Upload Match Video for DRS Analysis")
|
22 |
+
uploaded_file = st.file_uploader("Choose a video file (MP4, AVI)", type=["mp4", "avi"])
|
23 |
+
|
24 |
+
if uploaded_file is not None:
|
25 |
+
try:
|
26 |
+
# Save uploaded video
|
27 |
+
video_path = os.path.join(UPLOAD_DIR, uploaded_file.name)
|
28 |
+
with open(video_path, "wb") as f:
|
29 |
+
f.write(uploaded_file.getbuffer())
|
30 |
+
st.success(f"Video '{uploaded_file.name}' uploaded successfully!")
|
31 |
+
|
32 |
+
# Process video
|
33 |
+
with st.spinner("Processing video for DRS analysis..."):
|
34 |
+
result = process_video(video_path)
|
35 |
+
if result["status"] == "success":
|
36 |
+
# Display replay video (live preview)
|
37 |
+
st.subheader("Replay Video")
|
38 |
+
st.video(result["replay_path"])
|
39 |
+
st.write(f"**LBW Decision**: {result['decision']}")
|
40 |
+
st.write(f"**Ball Speed**: {result['speed_kmh']:.2f} km/h")
|
41 |
+
# External test frame (local file access for testing)
|
42 |
+
st.subheader("External Replay (Test Frame)")
|
43 |
+
st.markdown(f'<video width="640" height="360" controls><source src="file://{result["replay_path"]}" type="video/mp4"></video>', unsafe_allow_html=True)
|
44 |
+
else:
|
45 |
+
st.error(f"Error: {result['error']}")
|
46 |
+
except Exception as e:
|
47 |
+
logger.error(f"Error processing video: {str(e)}")
|
48 |
+
st.error(f"Failed to process video: {str(e)}")
|
49 |
+
|
50 |
+
if __name__ == "__main__":
|
51 |
+
main()
|
gully_drs_core/ball_detection.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
import logging
|
5 |
+
import os
|
6 |
+
from gully_drs_core.replay_utils import generate_replay
|
7 |
+
from gully_drs_core.video_utils import get_video_properties
|
8 |
+
from gully_drs_core.model_utils import load_yolo_model
|
9 |
+
|
10 |
+
# Set up logging
|
11 |
+
logging.basicConfig(level=logging.INFO)
|
12 |
+
logger = logging.getLogger(__name__)
|
13 |
+
|
14 |
+
# Load YOLOv5 model
|
15 |
+
model = load_yolo_model()
|
16 |
+
|
17 |
+
# Stump zone coordinates (example, adjust based on video resolution)
|
18 |
+
STUMP_ZONE = [(200, 400), (300, 400), (300, 600), (200, 600)] # [x1,y1, x2,y2, x3,y3, x4,y4]
|
19 |
+
|
20 |
+
def process_video(video_path):
|
21 |
+
try:
|
22 |
+
# Validate video file
|
23 |
+
if not os.path.exists(video_path):
|
24 |
+
return {"status": "error", "error": "Video file not found"}
|
25 |
+
|
26 |
+
# Get video properties
|
27 |
+
fps, width, height = get_video_properties(video_path)
|
28 |
+
if fps == 0:
|
29 |
+
return {"status": "error", "error": "Invalid video file"}
|
30 |
+
|
31 |
+
# Initialize video capture
|
32 |
+
cap = cv2.VideoCapture(video_path)
|
33 |
+
ball_positions = []
|
34 |
+
bounce_point = None
|
35 |
+
frame_count = 0
|
36 |
+
|
37 |
+
while cap.isOpened():
|
38 |
+
ret, frame = cap.read()
|
39 |
+
if not ret:
|
40 |
+
break
|
41 |
+
|
42 |
+
# Detect ball using YOLOv5
|
43 |
+
results = model(frame)
|
44 |
+
detections = results.xyxy[0].cpu().numpy() # [x1, y1, x2, y2, conf, class]
|
45 |
+
|
46 |
+
ball_center = None
|
47 |
+
for det in detections:
|
48 |
+
if det[5] == 0: # Assuming class 0 is the ball
|
49 |
+
x1, y1, x2, y2 = map(int, det[:4])
|
50 |
+
ball_center = ((x1 + x2) // 2, (y1 + y2) // 2)
|
51 |
+
ball_positions.append(ball_center)
|
52 |
+
# Detect bounce point (simplified: assume bounce near ground)
|
53 |
+
if y1 > height * 0.8 and bounce_point is None:
|
54 |
+
bounce_point = ball_center
|
55 |
+
break
|
56 |
+
|
57 |
+
frame_count += 1
|
58 |
+
|
59 |
+
cap.release()
|
60 |
+
|
61 |
+
# Check LBW decision
|
62 |
+
decision = "Not Out"
|
63 |
+
for pos in ball_positions:
|
64 |
+
if is_ball_in_stump_zone(pos):
|
65 |
+
decision = "Out"
|
66 |
+
break
|
67 |
+
|
68 |
+
# Calculate speed (pixels per frame to km/h)
|
69 |
+
speed_kmh = 0
|
70 |
+
if len(ball_positions) >= 2:
|
71 |
+
pixel_dist = np.sqrt((ball_positions[-1][0] - ball_positions[-2][0])**2 +
|
72 |
+
(ball_positions[-1][1] - ball_positions[-2][1])**2)
|
73 |
+
speed_kmh = (pixel_dist / (1/fps)) * 0.036 # Simplified conversion, adjust scale factor
|
74 |
+
|
75 |
+
# Generate replay video
|
76 |
+
replay_path = generate_replay(video_path, ball_positions, STUMP_ZONE, decision, speed_kmh, bounce_point)
|
77 |
+
|
78 |
+
return {
|
79 |
+
"status": "success",
|
80 |
+
"decision": decision,
|
81 |
+
"speed_kmh": speed_kmh,
|
82 |
+
"replay_path": replay_path
|
83 |
+
}
|
84 |
+
except Exception as e:
|
85 |
+
logger.error(f"Error processing video: {str(e)}")
|
86 |
+
return {"status": "error", "error": str(e)}
|
87 |
+
|
88 |
+
def is_ball_in_stump_zone(ball_center):
|
89 |
+
x, y = ball_center
|
90 |
+
x1, y1, x2, y2, x3, y3, x4, y4 = STUMP_ZONE[0] + STUMP_ZONE[1] + STUMP_ZONE[2] + STUMP_ZONE[3]
|
91 |
+
return (x1 <= x <= x2) and (y1 <= y <= y3)
|
gully_drs_core/init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
# Package initialization for gully_drs_core
|
gully_drs_core/model_utils.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import logging
|
3 |
+
|
4 |
+
# Set up logging
|
5 |
+
logging.basicConfig(level=logging.INFO)
|
6 |
+
logger = logging.getLogger(__name__)
|
7 |
+
|
8 |
+
def load_yolo_model():
|
9 |
+
try:
|
10 |
+
# Load YOLOv5s model (use pre-trained or fine-tuned weights)
|
11 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
|
12 |
+
model.eval()
|
13 |
+
logger.info("YOLOv5 model loaded successfully")
|
14 |
+
return model
|
15 |
+
except Exception as e:
|
16 |
+
logger.error(f"Error loading YOLOv5 model: {str(e)}")
|
17 |
+
raise
|
gully_drs_core/replay_utils.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
from scipy.interpolate import CubicSpline
|
4 |
+
import os
|
5 |
+
from gully_drs_core.video_utils import get_video_properties
|
6 |
+
|
7 |
+
def generate_replay(video_path, ball_positions, stump_zone, decision, speed_kmh, bounce_point):
|
8 |
+
try:
|
9 |
+
# Get video properties
|
10 |
+
fps, width, height = get_video_properties(video_path)
|
11 |
+
|
12 |
+
# Initialize video capture and output
|
13 |
+
cap = cv2.VideoCapture(video_path)
|
14 |
+
output_path = os.path.join("outputs", f"replay_{os.path.basename(video_path)}")
|
15 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
16 |
+
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
|
17 |
+
|
18 |
+
frame_idx = 0
|
19 |
+
|
20 |
+
while cap.isOpened():
|
21 |
+
ret, frame = cap.read()
|
22 |
+
if not ret:
|
23 |
+
break
|
24 |
+
|
25 |
+
# Draw stump zone
|
26 |
+
cv2.polylines(frame, [np.array(stump_zone)], isClosed=True, color=(0, 0, 255), thickness=2)
|
27 |
+
|
28 |
+
# Draw ball position
|
29 |
+
if frame_idx < len(ball_positions):
|
30 |
+
x, y = ball_positions[frame_idx]
|
31 |
+
cv2.circle(frame, (x, y), 5, (0, 255, 0), -1)
|
32 |
+
|
33 |
+
# Draw bounce point
|
34 |
+
if bounce_point and frame_idx >= len(ball_positions) // 2:
|
35 |
+
cv2.circle(frame, bounce_point, 8, (255, 255, 0), -1)
|
36 |
+
|
37 |
+
# Draw Bezier curve trajectory
|
38 |
+
if len(ball_positions) > 3 and frame_idx < len(ball_positions):
|
39 |
+
points = np.array(ball_positions[:frame_idx + 1])
|
40 |
+
if len(points) > 3:
|
41 |
+
t = np.linspace(0, 1, len(points))
|
42 |
+
cs_x = CubicSpline(t, points[:, 0])
|
43 |
+
cs_y = CubicSpline(t, points[:, 1])
|
44 |
+
t_fine = np.linspace(0, 1, min(100, len(points) * 10))
|
45 |
+
curve_x = cs_x(t_fine).astype(int)
|
46 |
+
curve_y = cs_y(t_fine).astype(int)
|
47 |
+
for i in range(1, len(curve_x)):
|
48 |
+
cv2.line(frame, (curve_x[i-1], curve_y[i-1]), (curve_x[i], curve_y[i]), (255, 0, 0), 2)
|
49 |
+
|
50 |
+
# Add text overlays
|
51 |
+
cv2.putText(frame, f"Decision: {decision}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
|
52 |
+
cv2.putText(frame, f"Speed: {speed_kmh:.2f} km/h", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
|
53 |
+
|
54 |
+
out.write(frame)
|
55 |
+
frame_idx += 1
|
56 |
+
|
57 |
+
cap.release()
|
58 |
+
out.release()
|
59 |
+
return output_path
|
60 |
+
except Exception as e:
|
61 |
+
raise Exception(f"Error generating replay: {str(e)}")
|
gully_drs_core/video_utils.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import logging
|
3 |
+
|
4 |
+
# Set up logging
|
5 |
+
logging.basicConfig(level=logging.INFO)
|
6 |
+
logger = logging.getLogger(__name__)
|
7 |
+
|
8 |
+
def get_video_properties(video_path):
|
9 |
+
try:
|
10 |
+
cap = cv2.VideoCapture(video_path)
|
11 |
+
if not cap.isOpened():
|
12 |
+
logger.error("Failed to open video file")
|
13 |
+
return 0, 0, 0
|
14 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
15 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
16 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
17 |
+
cap.release()
|
18 |
+
return fps, width, height
|
19 |
+
except Exception as e:
|
20 |
+
logger.error(f"Error getting video properties: {str(e)}")
|
21 |
+
return 0, 0, 0
|
pages/live_match.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
|
3 |
+
st.set_page_config(page_title="GullyDRS - Live Match")
|
4 |
+
st.title("GullyDRS - Live Match")
|
5 |
+
st.write("Live match analysis is planned for future phases.")
|
pages/upload_analysis.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
|
3 |
+
st.set_page_config(page_title="GullyDRS - Upload Analysis")
|
4 |
+
st.title("GullyDRS - Upload Analysis")
|
5 |
+
st.write("Upload a match video for DRS analysis. Navigate to the Home page to process videos.")
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit==1.35.0
|
2 |
+
opencv-python==4.10.0
|
3 |
+
torch==2.0.1
|
4 |
+
yolov5==7.0.12
|
5 |
+
numpy==1.26.4
|
6 |
+
scipy==1.13.1
|