Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172from flask import Flask, request, jsonifyfrom flask_cors import CORSimport joblib, os, traceback, requests, numpy as npfrom PIL import Imagefrom moviepy.editor import VideoFileClipfrom keras.applications.resnet50 import ResNet50, preprocess_inputfrom keras.preprocessing import imageapp = Flask(__name__)CORS(app)# Load models once at startupclassification_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 framesdef 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('/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'}), 400temp_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)}), 500if __name__ == '__main__':app.run(host='0.0.0.0', port=7860)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677from flask import Flask, request, jsonifyfrom flask_cors import CORSimport joblib, os, traceback, requests, numpy as npfrom PIL import Imagefrom moviepy.editor import VideoFileClipfrom keras.applications.resnet50 import ResNet50, preprocess_inputfrom keras.preprocessing import imageapp = Flask(__name__)CORS(app)# Load models once at startupclassification_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 framesdef 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'}), 400temp_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)}), 500if __name__ == '__main__':app.run(host='0.0.0.0', port=7860)
app.py+77-72