{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "video-action-recognition-header" }, "source": [ "# šŸŽ¬ Video Action Recognition with TimeSformer\n", "\n", "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/u-justine/VideoActionRecognition/blob/main/VideoActionRecognition_Colab.ipynb)\n", "[![GitHub](https://img.shields.io/badge/GitHub-Repository-blue?logo=github)](https://github.com/u-justine/VideoActionRecognition)\n", "\n", "This notebook provides a complete implementation of video action recognition using Facebook's TimeSformer model. Upload your own videos and get real-time predictions of human actions!\n", "\n", "## Features\n", "- 🧠 **AI-Powered**: Uses Facebook's TimeSformer model fine-tuned on Kinetics-400\n", "- ⚔ **GPU Accelerated**: Runs efficiently on Colab's free GPU\n", "- šŸ“ **Easy Upload**: Drag and drop videos directly in the browser\n", "- šŸ“Š **Detailed Results**: Get top-k predictions with confidence scores\n", "- šŸŽÆ **400+ Actions**: Recognizes sports, daily activities, and more\n", "\n", "## How to Use\n", "1. **Enable GPU**: Go to `Runtime` → `Change runtime type` → Select `GPU`\n", "2. **Run Setup**: Execute the setup cells below\n", "3. **Upload Video**: Use the file upload widget\n", "4. **Get Predictions**: View action recognition results\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": { "id": "setup-section" }, "source": [ "## šŸ“¦ Installation and Setup\n", "\n", "First, let's install all required dependencies and check GPU availability." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "install-dependencies" }, "outputs": [], "source": [ "# Check GPU availability\n", "import torch\n", "print(f\"šŸš€ PyTorch version: {torch.__version__}\")\n", "print(f\"šŸ”„ CUDA available: {torch.cuda.is_available()}\")\n", "if torch.cuda.is_available():\n", " print(f\"šŸŽÆ GPU device: {torch.cuda.get_device_name(0)}\")\n", " print(f\"šŸ’¾ GPU memory: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB\")\n", "else:\n", " print(\"āš ļø GPU not available, using CPU (will be slower)\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "install-packages" }, "outputs": [], "source": [ "# Install required packages\n", "!pip install -q transformers[torch]\n", "!pip install -q decord\n", "!pip install -q opencv-python\n", "!pip install -q pillow\n", "!pip install -q numpy\n", "!pip install -q ipywidgets\n", "\n", "print \"āœ… All packages installed successfully!\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "import-libraries" }, "outputs": [], "source": [ "# Import required libraries\n", "import os\n", "import json\n", "import warnings\n", "from pathlib import Path\n", "from typing import List, Tuple, Optional\n", "import time\n", "\n", "import numpy as np\n", "import torch\n", "from transformers import TimesformerImageProcessor, TimesformerForVideoClassification\n", "from PIL import Image\n", "import cv2\n", "from IPython.display import display, HTML, Video\n", "from google.colab import files\n", "import ipywidgets as widgets\n", "from IPython.display import clear_output\n", "\n", "# Suppress warnings\n", "warnings.filterwarnings('ignore')\n", "torch.set_grad_enabled(False)\n", "\n", "print(\"šŸ“š Libraries imported successfully!\")" ] }, { "cell_type": "markdown", "metadata": { "id": "model-setup" }, "source": [ "## šŸ¤– Model Setup\n", "\n", "Loading the TimeSformer model and processor. This may take a few minutes on first run." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "load-model" }, "outputs": [], "source": [ "# Model configuration\n", "MODEL_NAME = \"facebook/timesformer-base-finetuned-k400\"\n", "FRAMES_PER_VIDEO = 32 # TimeSformer expects 32 frames\n", "TARGET_FPS = 8 # Sample frames at this rate\n", "\n", "print(f\"šŸ”„ Loading TimeSformer model: {MODEL_NAME}\")\n", "print(\"ā³ This may take a few minutes on first run...\")\n", "\n", "# Load model and processor\n", "try:\n", " device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", " \n", " # Load processor\n", " processor = TimesformerImageProcessor.from_pretrained(MODEL_NAME)\n", " print(\"āœ… Processor loaded\")\n", " \n", " # Load model\n", " model = TimesformerForVideoClassification.from_pretrained(MODEL_NAME)\n", " model = model.to(device)\n", " model.eval()\n", " print(f\"āœ… Model loaded on {device}\")\n", " \n", " # Get label mapping\n", " id2label = model.config.id2label\n", " print(f\"šŸ“Š Model can recognize {len(id2label)} different actions\")\n", " \n", "except Exception as e:\n", " print(f\"āŒ Error loading model: {e}\")\n", " raise e\n", "\n", "print(\"šŸŽ‰ Model setup complete!\")" ] }, { "cell_type": "markdown", "metadata": { "id": "helper-functions" }, "source": [ "## šŸ› ļø Helper Functions\n", "\n", "Define functions for video processing and prediction." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "video-processing-functions" }, "outputs": [], "source": [ "def extract_frames_cv2(video_path: str, target_frames: int = FRAMES_PER_VIDEO) -> np.ndarray:\n", " \"\"\"\n", " Extract uniformly sampled frames from video using OpenCV.\n", " \n", " Args:\n", " video_path: Path to the video file\n", " target_frames: Number of frames to extract\n", " \n", " Returns:\n", " numpy array of shape (target_frames, height, width, 3)\n", " \"\"\"\n", " cap = cv2.VideoCapture(video_path)\n", " \n", " if not cap.isOpened():\n", " raise ValueError(f\"Cannot open video: {video_path}\")\n", " \n", " # Get video properties\n", " total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n", " fps = cap.get(cv2.CAP_PROP_FPS)\n", " duration = total_frames / fps\n", " \n", " print(f\"šŸ“¹ Video info: {total_frames} frames, {fps:.1f} FPS, {duration:.1f}s duration\")\n", " \n", " # Calculate frame indices to sample\n", " if total_frames <= target_frames:\n", " frame_indices = list(range(total_frames))\n", " # Pad with last frame if needed\n", " frame_indices.extend([total_frames - 1] * (target_frames - total_frames))\n", " else:\n", " frame_indices = np.linspace(0, total_frames - 1, target_frames, dtype=int)\n", " \n", " frames = []\n", " for i, frame_idx in enumerate(frame_indices):\n", " cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)\n", " ret, frame = cap.read()\n", " \n", " if ret:\n", " # Convert BGR to RGB\n", " frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n", " frames.append(frame)\n", " else:\n", " # Use last valid frame if read fails\n", " if frames:\n", " frames.append(frames[-1])\n", " else:\n", " raise ValueError(f\"Cannot read frame {frame_idx}\")\n", " \n", " cap.release()\n", " \n", " frames_array = np.array(frames)\n", " print(f\"šŸŽ¬ Extracted {len(frames)} frames, shape: {frames_array.shape}\")\n", " \n", " return frames_array\n", "\n", "def predict_actions(video_path: str, top_k: int = 5) -> List[Tuple[str, float]]:\n", " \"\"\"\n", " Predict actions in a video.\n", " \n", " Args:\n", " video_path: Path to the video file\n", " top_k: Number of top predictions to return\n", " \n", " Returns:\n", " List of (action_name, confidence) tuples\n", " \"\"\"\n", " try:\n", " print(f\"šŸŽÆ Analyzing video: {Path(video_path).name}\")\n", " \n", " # Extract frames\n", " start_time = time.time()\n", " frames = extract_frames_cv2(video_path)\n", " extract_time = time.time() - start_time\n", " print(f\"ā±ļø Frame extraction: {extract_time:.2f}s\")\n", " \n", " # Process frames\n", " start_time = time.time()\n", " inputs = processor(list(frames), return_tensors=\"pt\")\n", " \n", " # Move to device\n", " pixel_values = inputs['pixel_values'].to(device)\n", " process_time = time.time() - start_time\n", " print(f\"ā±ļø Frame processing: {process_time:.2f}s\")\n", " print(f\"šŸ“Š Input tensor shape: {pixel_values.shape}\")\n", " \n", " # Predict\n", " start_time = time.time()\n", " with torch.no_grad():\n", " outputs = model(pixel_values)\n", " logits = outputs.logits\n", " \n", " # Get probabilities\n", " probabilities = torch.nn.functional.softmax(logits, dim=-1)\n", " predict_time = time.time() - start_time\n", " print(f\"ā±ļø Model inference: {predict_time:.2f}s\")\n", " \n", " # Get top-k predictions\n", " top_k_values, top_k_indices = torch.topk(probabilities, top_k, dim=-1)\n", " \n", " predictions = []\n", " for i in range(top_k):\n", " idx = top_k_indices[0][i].item()\n", " confidence = top_k_values[0][i].item()\n", " action = id2label[idx]\n", " predictions.append((action, confidence))\n", " \n", " total_time = extract_time + process_time + predict_time\n", " print(f\"āœ… Total processing time: {total_time:.2f}s\")\n", " \n", " return predictions\n", " \n", " except Exception as e:\n", " print(f\"āŒ Error during prediction: {e}\")\n", " raise e\n", "\n", "def display_predictions(predictions: List[Tuple[str, float]], video_path: str = None):\n", " \"\"\"\n", " Display prediction results in a nice format.\n", " \"\"\"\n", " print(\"\\n\" + \"=\"*50)\n", " print(\"šŸŽ¬ VIDEO ACTION RECOGNITION RESULTS\")\n", " print(\"=\"*50)\n", " \n", " if video_path:\n", " print(f\"šŸ“¹ Video: {Path(video_path).name}\\n\")\n", " \n", " for i, (action, confidence) in enumerate(predictions, 1):\n", " bar_length = int(confidence * 30)\n", " bar = \"ā–ˆ\" * bar_length + \"ā–‘\" * (30 - bar_length)\n", " print(f\"{i:2d}. {action:<35} {confidence:6.1%} │{bar}│\")\n", " \n", " print(\"\\n\" + \"=\"*50)\n", " print(f\"šŸ† Top prediction: {predictions[0][0]} ({predictions[0][1]:.1%} confidence)\")\n", " print(\"=\"*50)\n", "\n", "print(\"šŸ› ļø Helper functions defined!\")" ] }, { "cell_type": "markdown", "metadata": { "id": "upload-section" }, "source": [ "## šŸ“¤ Upload Your Video\n", "\n", "Upload a video file to analyze. Supported formats: MP4, MOV, AVI, MKV" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "upload-widget" }, "outputs": [], "source": [ "# Create upload widget\n", "upload_widget = widgets.FileUpload(\n", " accept='.mp4,.mov,.avi,.mkv',\n", " multiple=False,\n", " description='Choose Video',\n", " disabled=False,\n", " button_style='info',\n", " icon='upload'\n", ")\n", "\n", "# Create predict button\n", "predict_button = widgets.Button(\n", " description='šŸŽÆ Analyze Video',\n", " disabled=True,\n", " button_style='success',\n", " icon='play'\n", ")\n", "\n", "# Create output widget\n", "output_widget = widgets.Output()\n", "\n", "# Global variable to store uploaded file path\n", "uploaded_file_path = None\n", "\n", "def on_upload_change(change):\n", " global uploaded_file_path\n", " if upload_widget.value:\n", " # Save uploaded file\n", " filename = list(upload_widget.value.keys())[0]\n", " content = upload_widget.value[filename]['content']\n", " \n", " # Create uploads directory if it doesn't exist\n", " os.makedirs('/content/uploads', exist_ok=True)\n", " uploaded_file_path = f'/content/uploads/{filename}'\n", " \n", " with open(uploaded_file_path, 'wb') as f:\n", " f.write(content)\n", " \n", " predict_button.disabled = False\n", " with output_widget:\n", " clear_output()\n", " print(f\"āœ… Video uploaded successfully: {filename}\")\n", " print(f\"šŸ“ File size: {len(content) / (1024*1024):.1f} MB\")\n", " \n", " # Display video preview\n", " display(Video(uploaded_file_path, width=400, height=300))\n", "\n", "def on_predict_click(button):\n", " global uploaded_file_path\n", " if uploaded_file_path and os.path.exists(uploaded_file_path):\n", " with output_widget:\n", " clear_output(wait=True)\n", " print(\"šŸš€ Starting video analysis...\")\n", " print(\"ā³ This may take a few moments...\\n\")\n", " \n", " try:\n", " # Make predictions\n", " predictions = predict_actions(uploaded_file_path, top_k=10)\n", " \n", " # Display results\n", " display_predictions(predictions, uploaded_file_path)\n", " \n", " # Show video again\n", " print(\"\\nšŸ“¹ Analyzed Video:\")\n", " display(Video(uploaded_file_path, width=400, height=300))\n", " \n", " except Exception as e:\n", " print(f\"āŒ Error analyzing video: {e}\")\n", " print(\"\\nšŸ’” Tips:\")\n", " print(\"- Make sure your video file is not corrupted\")\n", " print(\"- Try a different video format (MP4 recommended)\")\n", " print(\"- Ensure the video contains clear human actions\")\n", "\n", "# Connect event handlers\n", "upload_widget.observe(on_upload_change, names='value')\n", "predict_button.on_click(on_predict_click)\n", "\n", "# Display widgets\n", "print(\"šŸ“¤ Upload your video file below:\")\n", "display(upload_widget)\n", "display(predict_button)\n", "display(output_widget)" ] }, { "cell_type": "markdown", "metadata": { "id": "examples-section" }, "source": [ "## šŸŽ¬ Test with Sample Videos\n", "\n", "Don't have a video? Try these sample videos from the web:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "sample-videos" }, "outputs": [], "source": [ "# Sample video URLs (you can replace with your own)\n", "sample_videos = {\n", " \"Basketball\": \"https://sample-videos.com/zip/10/mp4/SampleVideo_720x480_1mb.mp4\",\n", " \"Dancing\": \"https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4\",\n", " \"Cooking\": \"https://file-examples.com/storage/fef68c5d7aa9a5c23b0/2017/10/file_example_MP4_480_1_5MG.mp4\"\n", "}\n", "\n", "def download_and_analyze(video_name, video_url):\n", " \"\"\"\n", " Download a sample video and analyze it.\n", " \"\"\"\n", " try:\n", " print(f\"šŸ“„ Downloading {video_name} video...\")\n", " \n", " # Download video\n", " import urllib.request\n", " os.makedirs('/content/samples', exist_ok=True)\n", " video_path = f'/content/samples/{video_name.lower()}.mp4'\n", " \n", " urllib.request.urlretrieve(video_url, video_path)\n", " print(f\"āœ… Downloaded: {video_name}\")\n", " \n", " # Analyze video\n", " predictions = predict_actions(video_path, top_k=5)\n", " display_predictions(predictions, video_path)\n", " \n", " # Show video\n", " print(f\"\\nšŸ“¹ Sample Video - {video_name}:\")\n", " display(Video(video_path, width=400, height=300))\n", " \n", " except Exception as e:\n", " print(f\"āŒ Error with sample video {video_name}: {e}\")\n", " print(\"šŸ’” You can still upload your own video above!\")\n", "\n", "# Create buttons for sample videos\n", "sample_buttons = []\n", "for name, url in sample_videos.items():\n", " button = widgets.Button(\n", " description=f\"Try {name}\",\n", " button_style='info',\n", " icon='play'\n", " )\n", " button.on_click(lambda b, n=name, u=url: download_and_analyze(n, u))\n", " sample_buttons.append(button)\n", "\n", "print(\"šŸŽ¬ Click a button below to test with sample videos:\")\n", "sample_output = widgets.Output()\n", "\n", "display(widgets.HBox(sample_buttons))\n", "display(sample_output)" ] }, { "cell_type": "markdown", "metadata": { "id": "model-info" }, "source": [ "## šŸ“Š Model Information\n", "\n", "Learn more about the TimeSformer model and what actions it can recognize." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "show-model-info" }, "outputs": [], "source": [ "# Display model information\n", "print(\"šŸ¤– TimeSformer Model Information\")\n", "print(\"=\" * 50)\n", "print(f\"Model Name: {MODEL_NAME}\")\n", "print(f\"Total Actions: {len(id2label)}\")\n", "print(f\"Input Frames: {FRAMES_PER_VIDEO}\")\n", "print(f\"Model Parameters: {sum(p.numel() for p in model.parameters()):,}\")\n", "print(f\"Device: {device}\")\n", "print(f\"Model Size: ~{sum(p.numel() * 4 for p in model.parameters()) / (1024**2):.1f} MB\")\n", "\n", "print(\"\\nšŸ·ļø Sample Action Categories:\")\n", "print(\"=\" * 50)\n", "\n", "# Show some sample actions\n", "sample_actions = [\n", " \"playing basketball\", \"cooking\", \"dancing\", \"swimming\", \"running\",\n", " \"playing guitar\", \"yoga\", \"boxing\", \"cycling\", \"reading\",\n", " \"writing\", \"typing\", \"singing\", \"painting\", \"exercising\"\n", "]\n", "\n", "# Find matching actions in the model's vocabulary\n", "found_actions = []\n", "for action in sample_actions:\n", " for label in id2label.values():\n", " if action.lower() in label.lower() or any(word in label.lower() for word in action.split()):\n", " found_actions.append(label)\n", " break\n", "\n", "# Display found actions in columns\n", "for i, action in enumerate(found_actions[:15], 1):\n", " print(f\"{i:2d}. {action}\")\n", "\n", "if len(id2label) > 15:\n", " print(f\"... and {len(id2label) - 15} more actions!\")\n", "\n", "print(\"\\nšŸ“š References:\")\n", "print(\"=\" * 50)\n", "print(\"šŸ”— Model: https://huggingface.co/facebook/timesformer-base-finetuned-k400\")\n", "print(\"šŸ“„ Paper: https://arxiv.org/abs/2102.05095\")\n", "print(\"šŸ’¾ Dataset: Kinetics-400\")\n", "print(\"šŸ¢ Developed by: Facebook AI Research\")" ] }, { "cell_type": "markdown", "metadata": { "id": "tips-section" }, "source": [ "## šŸ’” Tips for Better Results\n", "\n", "To get the best action recognition results:\n", "\n", "### šŸ“¹ Video Quality\n", "- Use clear, well-lit videos\n", "- Ensure the action is clearly visible\n", "- Avoid overly shaky or blurry footage\n", "- Keep video duration between 2-10 seconds for best results\n", "\n", "### šŸŽÆ Action Types\n", "- The model works best with distinct, recognizable actions\n", "- Sports activities tend to have high accuracy\n", "- Daily activities like cooking, reading, exercising work well\n", "- Subtle or very specific actions may not be recognized\n", "\n", "### āš™ļø Technical Tips\n", "- MP4 format is recommended\n", "- Videos under 50MB process faster\n", "- GPU acceleration significantly speeds up processing\n", "- The model samples 32 frames uniformly from your video\n", "\n", "### šŸ” Understanding Results\n", "- Confidence scores above 50% are generally reliable\n", "- Check multiple top predictions for similar actions\n", "- Some actions may have similar names but different meanings\n", "- The model may detect related actions (e.g., \"exercising\" vs \"doing aerobics\")\n" ] }, { "cell_type": "markdown", "metadata": { "id": "troubleshooting" }, "source": [ "## šŸ”§ Troubleshooting\n", "\n", "If you encounter issues, try these solutions:\n", "\n", "### Common Issues:\n", "\n", "1. **\"Cannot read video file\"**\n", " - Check if the video file is corrupted\n", " - Try converting to MP4 format\n", " - Ensure file size is reasonable (<200MB)\n", "\n", "2. **\"CUDA out of memory\"**\n", " - Restart the runtime and try again\n", " - Use smaller video files\n", " - The model will fall back to CPU if needed\n", "\n", "3. **\"Model loading failed\"**\n", " - Check internet connection\n", " - Restart the runtime\n", " - Re-run the model setup cell\n", "\n", "4. **\"Poor predictions\"**\n", " - Try videos with clearer actions\n", " - Ensure good lighting and video quality\n", " - Check if the action is in the model's training data (Kinetics-400)\n", "\n", "### Need Help?\n", "- šŸ› Report issues: [GitHub Issues](https://github.com/u-justine/VideoActionRecognition/issues)\n", "- šŸ“§ Contact: Create an issue on GitHub\n", "- šŸ“š Documentation: Check the repository README\n" ] }, { "cell_type": "markdown", "metadata": { "id": "conclusion" }, "source": [ "## šŸŽ‰ Conclusion\n", "\n", "You've successfully set up and used the Video Action Recognition system! Here's what you've accomplished:\n", "\n", "### āœ… What You've Done\n", "- Loaded Facebook's TimeSformer model with 400+ action classes\n", "- Processed videos using GPU acceleration (when available)\n", "- Extracted and analyzed video frames for action recognition\n", "- Got detailed predictions with confidence scores\n", "\n", "### šŸš€ Next Steps\n", "- Try different types of videos to explore the model's capabilities\n", "- Experiment with various action categories (sports, daily activities, etc.)\n", "- Consider fine-tuning the model for your specific use case\n", "- Deploy this as a web application using Streamlit or Gradio\n", "\n", "### šŸ“± Deploy Your Own\n", "Want to create your own video action recognition app?\n", "\n", "1. **Local Setup**: Clone the repository and run locally\n", " ```bash\n", " git clone https://github.com/u-justine/VideoActionRecognition.git\n", " cd VideoActionRecognition\n", " ./run_app.sh\n", " ```\n", "\n", "2. **Cloud Deployment**: Deploy on platforms like:\n", " - Hugging Face Spaces\n", " - Streamlit Cloud \n", " - Google Cloud Run\n", " - AWS or Azure\n", "\n", "3. **Customization**: Modify the code to:\n", " - Add your own action categories\n", " - Implement batch processing\n", " - Create REST API endpoints\n", " - Add real-time video processing\n", "\n", "### 🌟 Share Your Results\n", "- Star the repository if you found it useful: [⭐ GitHub Repo](https://github.com/u-justine/VideoActionRecognition)\n", "- Share your interesting results or improvements\n", "- Contribute to the project with bug fixes or new features\n", "\n", "### šŸ“š Learn More\n", "- **TimeSformer Paper**: [Is Space-Time Attention All You Need for Video Understanding?](https://arxiv.org/abs/2102.05095)\n", "- **Kinetics Dataset**: [A Large-Scale Video Dataset](https://deepmind.com/research/open-source/kinetics)\n", "- **Transformers Library**: [Hugging Face Documentation](https://huggingface.co/docs/transformers)\n", "\n", "---\n", "\n", "**Happy Video Analysis! šŸŽ¬āœØ**\n", "\n", "If you have questions or want to contribute, check out the [GitHub repository](https://github.com/u-justine/VideoActionRecognition) or open an issue.\n"