lokesh341 commited on
Commit
eb7bd4e
·
verified ·
1 Parent(s): 7ebb1aa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -0
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import gradio as gr
4
+ from ultralytics import YOLO
5
+ from typing import List, Dict
6
+
7
+ # Load models (automatically downloads on first run)
8
+ BALL_MODEL = YOLO('models/yolov8n.pt') # For ball tracking
9
+ STUMP_MODEL = YOLO('models/yolov8m.pt') # For LBW detection
10
+
11
+ def process_video(video_path: str) -> Dict:
12
+ """Process video with YOLO models"""
13
+ cap = cv2.VideoCapture(video_path)
14
+ fps = cap.get(cv2.CAP_PROP_FPS)
15
+ frames = []
16
+ analytics = {
17
+ "max_speed": 0,
18
+ "events": [],
19
+ "ball_positions": []
20
+ }
21
+
22
+ prev_pos = None
23
+
24
+ while cap.isOpened():
25
+ ret, frame = cap.read()
26
+ if not ret:
27
+ break
28
+
29
+ # Resize for consistent processing
30
+ frame = cv2.resize(frame, (1280, 720))
31
+
32
+ # Ball detection
33
+ ball_results = BALL_MODEL(frame, classes=32) # Class 32 = sports ball
34
+ ball_boxes = ball_results[0].boxes.xyxy.cpu().numpy()
35
+
36
+ if len(ball_boxes) > 0:
37
+ x1, y1, x2, y2 = map(int, ball_boxes[0])
38
+ x, y = (x1 + x2) // 2, (y1 + y2) // 2 # Center point
39
+
40
+ # Speed calculation
41
+ if prev_pos:
42
+ speed = np.sqrt((x - prev_pos[0])**2 + (y - prev_pos[1])**2) * fps * 3.6 / 100 # km/h
43
+ analytics["max_speed"] = max(analytics["max_speed"], speed)
44
+
45
+ # Draw tracking
46
+ cv2.circle(frame, (x, y), 10, (0, 255, 0), -1)
47
+ cv2.putText(frame, f"{speed:.1f} km/h", (x+15, y),
48
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 2)
49
+
50
+ prev_pos = (x, y)
51
+ analytics["ball_positions"].append((x, y))
52
+
53
+ # LBW detection (every 10 frames)
54
+ if len(analytics["ball_positions"]) % 10 == 0:
55
+ stump_results = STUMP_MODEL(frame, classes=33) # Class 33 = sports equipment
56
+ # Add LBW logic here
57
+
58
+ frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
59
+
60
+ cap.release()
61
+ return {"frames": frames, "analytics": analytics}
62
+
63
+ # Gradio UI
64
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
65
+ gr.Markdown("# 🏏 AI Cricket Analyzer")
66
+ with gr.Row():
67
+ input_video = gr.Video(label="Input Video", format="mp4")
68
+ output_video = gr.Video(label="AI Analysis")
69
+ with gr.Accordion("Advanced Settings", open=False):
70
+ model_size = gr.Dropdown(["Nano", "Small", "Medium"], value="Nano")
71
+ analyze_btn = gr.Button("Analyze", variant="primary")
72
+
73
+ analyze_btn.click(
74
+ fn=process_video,
75
+ inputs=input_video,
76
+ outputs=output_video
77
+ )
78
+
79
+ demo.launch()