LBW / app.py
dschandra's picture
Update app.py
e67714a verified
raw
history blame
6.96 kB
from flask import Flask, render_template, request, jsonify
import numpy as np
from sklearn.linear_model import LogisticRegression
import cv2
import os
from werkzeug.utils import secure_filename
from scipy.interpolate import splprep, splev
app = Flask(__name__)
UPLOAD_FOLDER = '/tmp/uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {'mp4', 'avi', 'mov'}
def train_dummy_model():
X = np.array([
[0.5, 0.0, 0.4, 0.5, 30, 0],
[0.5, 0.5, 0.5, 0.5, 35, 2],
[0.6, 0.2, 0.5, 0.6, 32, 1],
[0.5, 0.4, 0.5, 0.4, 34, 0],
])
y = np.array([0, 1, 0, 1])
model = LogisticRegression()
model.fit(X, y)
return model
model = train_dummy_model()
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def smooth_trajectory(points):
if len(points) < 3:
return points
x = [p["x"] for p in points]
y = [p["y"] for p in points]
tck, u = splprep([x, y], s=0)
u_new = np.linspace(0, 1, 50)
x_new, y_new = splev(u_new, tck)
return [{"x": x, "y": y} for x, y in zip(x_new, y_new)]
def process_video(video_path):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return None, None, "Failed to open video"
actual_path = []
frame_count = 0
spin = 0
last_point = None
pitching_detected = False
impact_detected = False
y_positions = []
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (0, 120, 70), (10, 255, 255))
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
c = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(c)
center_x = x + w / 2
center_y = y + h / 2
norm_x = center_x / 1280
norm_y = center_y / 720
current_point = (norm_x, norm_y)
if last_point != current_point:
actual_path.append({"x": norm_x, "y": norm_y})
y_positions.append(norm_y)
last_point = current_point
if len(y_positions) > 2 and not pitching_detected:
if y_positions[-1] < y_positions[-2] and y_positions[-2] < y_positions[-3]:
pitching_detected = True
pitching_x = actual_path[-2]["x"]
pitching_y = actual_path[-2]["y"]
if len(actual_path) > 2 and not impact_detected:
speed_current = abs(y_positions[-1] - y_positions[-2])
speed_prev = abs(y_positions[-2] - y_positions[-3])
if speed_current < speed_prev * 0.3:
impact_detected = True
impact_x = actual_path[-1]["x"]
impact_y = actual_path[-1]["y"]
frame_count += 1
if frame_count > 50:
break
cap.release()
if not actual_path:
return None, None, "No ball detected in video"
if not pitching_detected:
pitching_x = actual_path[len(actual_path)//2]["x"]
pitching_y = actual_path[len(actual_path)//2]["y"]
if not impact_detected:
impact_x = actual_path[-1]["x"]
impact_y = actual_path[-1]["y"]
fps = cap.get(cv2.CAP_PROP_FPS) or 30
speed = (len(actual_path) / (frame_count / fps)) * 0.5
actual_path = smooth_trajectory(actual_path)
projected_path = [
{"x": impact_x, "y": impact_y},
{"x": impact_x + spin * 0.1, "y": 1.0}
]
pitching_status = "Inline" if 0.4 <= pitching_x <= 0.6 else "Outside Leg" if pitching_x < 0.4 else "Outside Off"
impact_status = "Inline" if 0.4 <= impact_x <= 0.6 else "Outside"
wicket_status = "Hitting" if 0.4 <= projected_path[-1]["x"] <= 0.6 else "Missing"
return actual_path, projected_path, pitching_x, pitching_y, impact_x, impact_y, speed, spin, pitching_status, impact_status, wicket_status
@app.route('/')
def index():
return render_template('index.html')
@app.route('/analyze', methods=['POST'])
def analyze():
if 'video' not in request.files:
return jsonify({'error': 'No video uploaded'}), 400
file = request.files['video']
if file.filename == '' or not allowed_file(file.filename):
return jsonify({'error': 'Invalid file'}), 400
filename = secure_filename(file.filename)
video_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(video_path)
result = process_video(video_path)
if result[0] is None:
os.remove(video_path)
return jsonify({'error': result[2]}), 400
actual_path, projected_path, pitching_x, pitching_y, impact_x, impact_y, speed, spin, pitching_status, impact_status, wicket_status = result
features = np.array([[pitching_x, pitching_y, impact_x, impact_y, speed, spin]])
prediction = model.predict(features)[0]
confidence = min(model.predict_proba(features)[0][prediction], 0.99)
decision = "Out" if prediction == 1 else "Not Out"
os.remove(video_path)
return jsonify({
'actual_path': actual_path,
'projected_path': projected_path,
'decision': decision,
'confidence': round(confidence, 2),
'pitching': {'x': pitching_x, 'y': pitching_y, 'status': pitching_status},
'impact': {'x': impact_x, 'y': impact_y, 'status': impact_status},
'wicket': wicket_status
})
@app.route('/analyze_data', methods=['POST'])
def analyze_data():
data = request.get_json()
actual_path = data['actual_path']
projected_path = data['projected_path']
pitching = data['pitching']
impact = data['impact']
speed = data['speed']
spin = data['spin']
pitching_x = pitching['x']
pitching_y = pitching['y']
impact_x = impact['x']
impact_y = impact['y']
pitching_status = "Inline" if 0.4 <= pitching_x <= 0.6 else "Outside Leg" if pitching_x < 0.4 else "Outside Off"
impact_status = "Inline" if 0.4 <= impact_x <= 0.6 else "Outside"
wicket_status = "Hitting" if 0.4 <= projected_path[-1]["x"] <= 0.6 else "Missing"
features = np.array([[pitching_x, pitching_y, impact_x, impact_y, speed, spin]])
prediction = model.predict(features)[0]
confidence = min(model.predict_proba(features)[0][prediction], 0.99)
decision = "Out" if prediction == 1 else "Not Out"
return jsonify({
'actual_path': actual_path,
'projected_path': projected_path,
'decision': decision,
'confidence': round(confidence, 2),
'pitching': {'x': pitching_x, 'y': pitching_y, 'status': pitching_status},
'impact': {'x': impact_x, 'y': impact_y, 'status': impact_status},
'wicket': wicket_status
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True)