Spaces:
Sleeping

File size: 2,487 Bytes
b275c1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from flask import Flask, request, jsonify
from flask_cors import CORS
import joblib, os, traceback, requests, numpy as np
from PIL import Image
from moviepy.editor import VideoFileClip
from keras.applications.resnet50 import ResNet50, preprocess_input
from keras.preprocessing import image

app = Flask(__name__)
CORS(app)

# Load models once at startup
classification_model = joblib.load('classification_visual_only.pkl')
resnet_model = ResNet50(weights='imagenet', include_top=False, pooling='avg')

def download_video(video_url, temp_path):
    """Download video from Cloudinary."""
    response = requests.get(video_url, stream=True)
    with open(temp_path, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)

def extract_video_frames(video_path, interval=5):
    """Extract frames at every `interval` seconds."""
    video_clip = VideoFileClip(video_path)
    frames = []
    for t in range(0, int(video_clip.duration), interval):
        frame = video_clip.get_frame(t)
        frame_image = Image.fromarray(frame)
        frames.append(frame_image)
    video_clip.close()
    return frames

def extract_visual_features(video_path):
    """Extract average ResNet features from video frames."""
    frames = extract_video_frames(video_path)
    frame_features = []

    for frame in frames:
        frame = frame.resize((224, 224))
        img_array = image.img_to_array(frame)
        img_array = np.expand_dims(img_array, axis=0)
        img_array = preprocess_input(img_array)
        features = resnet_model.predict(img_array)
        frame_features.append(features.flatten())

    return np.mean(frame_features, axis=0)
    
@app.route('/')
def home():
    return "Flask app running successfully!"


@app.route('/classify', methods=['POST'])
def classify_video():
    try:
        data = request.get_json()
        video_url = data.get('video_url')

        if not video_url:
            return jsonify({'error': 'video_url is required'}), 400

        temp_path = 'temp_video.mp4'
        download_video(video_url, temp_path)

        visual_features = extract_visual_features(temp_path)
        prediction = classification_model.predict([visual_features])[0]
        os.remove(temp_path)

        return jsonify({'prediction': int(prediction)})

    except Exception as e:
        print(traceback.format_exc())
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)