Spaces:
Sleeping
Sleeping
Download app.py from Selva1103/testing_classify: direct link, hf CLI and curl.
- Browser
- Download file 2.49 kB
-
https://huggingface.co/spaces/Selva1103/testing_classify/resolve/main/app.py
- Command line
-
hf download hf://spaces/Selva1103/testing_classify/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Selva1103/testing_classify/resolve/main/app.py
2.49 kB
| 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) | |
| def home(): | |
| return "Flask app running successfully!" | |
| 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) | |