{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":5048,"databundleVersionId":868335,"sourceType":"competition"}],"dockerImageVersionId":31153,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-10-07T05:40:48.973488Z","iopub.execute_input":"2025-10-07T05:40:48.973900Z","iopub.status.idle":"2025-10-07T05:41:26.726001Z","shell.execute_reply.started":"2025-10-07T05:40:48.973860Z","shell.execute_reply":"2025-10-07T05:41:26.724109Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install torch torchvision opencv-python-headless numpy\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T07:24:10.305729Z","iopub.execute_input":"2025-10-07T07:24:10.307799Z","iopub.status.idle":"2025-10-07T07:24:14.493240Z","shell.execute_reply.started":"2025-10-07T07:24:10.307742Z","shell.execute_reply":"2025-10-07T07:24:14.491799Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport torch\nimport torch.nn as nn\nimport torchvision\nfrom torchvision.datasets import ImageFolder\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport cv2\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T07:24:44.440092Z","iopub.execute_input":"2025-10-07T07:24:44.440614Z","iopub.status.idle":"2025-10-07T07:24:44.447204Z","shell.execute_reply.started":"2025-10-07T07:24:44.440573Z","shell.execute_reply":"2025-10-07T07:24:44.445766Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\ndataset_path = \"/kaggle/input/state-farm-distracted-driver-detection/imgs\"\nprint(\"Folders in imgs directory:\", os.listdir(dataset_path))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T07:27:59.528265Z","iopub.execute_input":"2025-10-07T07:27:59.528575Z","iopub.status.idle":"2025-10-07T07:27:59.535414Z","shell.execute_reply.started":"2025-10-07T07:27:59.528553Z","shell.execute_reply":"2025-10-07T07:27:59.534430Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import random_split\n\n# Load train dataset only\ntrain_dir = os.path.join(dataset_path, 'train')\ntransform = transforms.Compose([\n    transforms.Resize((224, 224)),\n    transforms.ToTensor(),\n])\nfull_dataset = ImageFolder(train_dir, transform=transform)\n\n# Split dataset into train and validation\ntrain_size = int(0.8 * len(full_dataset))\nval_size = len(full_dataset) - train_size\ntrain_dataset, val_dataset = random_split(full_dataset, [train_size, val_size])\n\n# Data loaders\ntrain_loader = DataLoader(train_dataset, batch_size=8, shuffle=True, num_workers=2)\nval_loader = DataLoader(val_dataset, batch_size=8, shuffle=False, num_workers=2)\n\nprint(f\"Training samples: {len(train_dataset)}\")\nprint(f\"Validation samples: {len(val_dataset)}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T07:28:34.162756Z","iopub.execute_input":"2025-10-07T07:28:34.163142Z","iopub.status.idle":"2025-10-07T07:28:42.778849Z","shell.execute_reply.started":"2025-10-07T07:28:34.163117Z","shell.execute_reply":"2025-10-07T07:28:42.777665Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Dummy model simulating DWPose keypoint extractor output\nclass DummyPoseModel(nn.Module):\n    def __init__(self):\n        super(DummyPoseModel, self).__init__()\n    \n    def forward(self, x):\n        batch_size = x.size(0)\n        num_keypoints = 17  # hypothetical number of keypoints\n        keypoints = torch.rand(batch_size, num_keypoints, 2) * 224  # scale to input image size\n        return keypoints\n7\npose_model = DummyPoseModel()\npose_model.eval()\n\n# Function to extract keypoints from a batch of images\ndef extract_keypoints(images, model):\n    with torch.no_grad():\n        keypoints = model(images)\n    return keypoints.cpu().numpy()\n\n# Demo extraction on one batch from training loader\nfor imgs, labels in train_loader:\n    keypoints = extract_keypoints(imgs, pose_model)\n    print(\"Keypoints output shape:\", keypoints.shape)\n    break\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T08:10:49.711803Z","iopub.execute_input":"2025-10-07T08:10:49.712260Z","iopub.status.idle":"2025-10-07T08:10:50.110267Z","shell.execute_reply.started":"2025-10-07T08:10:49.712228Z","shell.execute_reply":"2025-10-07T08:10:50.108733Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class SimpleKalmanFilter:\n    def __init__(self):\n        self.x = None\n        self.P = np.eye(2) * 1000  # Covariance matrix\n        self.A = np.eye(2)          # State transition matrix\n        self.Q = np.eye(2)          # Process noise covariance\n        self.R = np.eye(2) * 0.1    # Measurement noise covariance\n    \n    def update(self, measurement):\n        if self.x is None:\n            self.x = measurement\n            return self.x\n        \n        # Predict\n        x_pred = self.A @ self.x\n        P_pred = self.A @ self.P @ self.A.T + self.Q\n        \n        # Kalman Gain\n        K = P_pred @ np.linalg.inv(P_pred + self.R)\n        \n        # Update\n        self.x = x_pred + K @ (measurement - x_pred)\n        self.P = (np.eye(2) - K) @ P_pred\n        \n        return self.x\n\n# Example usage on keypoints of one frame\nkf_list = [SimpleKalmanFilter() for _ in range(17)]  # One Kalman Filter per keypoint\n\ndef kalman_smooth(keypoints):\n    smoothed = []\n    for i, point in enumerate(keypoints):\n        smoothed_point = kf_list[i].update(point)\n        smoothed.append(smoothed_point)\n    return np.array(smoothed)\n\n# Demo smoothing on first image keypoints\nsmoothed_points = kalman_smooth(keypoints[0])\nprint(\"Smoothed keypoints shape:\", smoothed_points.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T07:38:47.380824Z","iopub.execute_input":"2025-10-07T07:38:47.381261Z","iopub.status.idle":"2025-10-07T07:38:47.393578Z","shell.execute_reply.started":"2025-10-07T07:38:47.381234Z","shell.execute_reply":"2025-10-07T07:38:47.392098Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}