File size: 28,292 Bytes
eb09c29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
{
  "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"