{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":46105,"databundleVersionId":5087314,"sourceType":"competition"}],"dockerImageVersionId":31041,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\ncounter = 0\nprint(counter)\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        counter = counter + 1\n        if counter == 6:\n            break\n    if counter == 6:\n        break\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-06-14T16:09:11.510629Z","iopub.execute_input":"2025-06-14T16:09:11.510986Z","iopub.status.idle":"2025-06-14T16:09:16.312198Z","shell.execute_reply.started":"2025-06-14T16:09:11.510960Z","shell.execute_reply":"2025-06-14T16:09:16.311499Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"/kaggle/input/asl-signs/sign_to_prediction_index_map.json\n/kaggle/input/asl-signs/train.csv\n/kaggle/input/asl-signs/train_landmark_files/36257/3762317508.parquet\n/kaggle/input/asl-signs/train_landmark_files/36257/1613088982.parquet","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import LSTM, Dense, Dropout, BatchNormalization\nfrom tensorflow.keras.callbacks import EarlyStopping, TensorBoard\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-13T06:39:59.930766Z","iopub.execute_input":"2025-06-13T06:39:59.931026Z","iopub.status.idle":"2025-06-13T06:39:59.935244Z","shell.execute_reply.started":"2025-06-13T06:39:59.931011Z","shell.execute_reply":"2025-06-13T06:39:59.934415Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install mediapipe","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-13T04:51:57.555670Z","iopub.execute_input":"2025-06-13T04:51:57.556383Z","iopub.status.idle":"2025-06-13T04:52:16.760596Z","shell.execute_reply.started":"2025-06-13T04:51:57.556359Z","shell.execute_reply":"2025-06-13T04:52:16.759900Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Mediapipe for real-time inference\nimport cv2\nimport mediapipe as mp\nfrom collections import deque","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-13T06:40:03.337759Z","iopub.execute_input":"2025-06-13T06:40:03.338293Z","iopub.status.idle":"2025-06-13T06:40:03.341677Z","shell.execute_reply.started":"2025-06-13T06:40:03.338269Z","shell.execute_reply":"2025-06-13T06:40:03.341004Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"DATA_DIR = '/kaggle/input/asl-signs/train_landmark_files'\nCSV_PATH = '/kaggle/input/asl-signs/train.csv'\nSEQUENCE_LENGTH = 30\nFEATURE_DIM = (33 + 468 + 21 + 21) * 3  # x, y, z for pose, face, left & right hand\nEPOCHS = 50\nBATCH_SIZE = 64\nTEST_SIZE = 0.1\nRANDOM_STATE = 42\n# /kaggle/input/asl-signs/sign_to_prediction_index_map.json\n# /kaggle/input/asl-signs/train.csv\n# /kaggle/input/asl-signs/train_landmark_files/36257/3762317508.parquet","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-13T06:40:05.952671Z","iopub.execute_input":"2025-06-13T06:40:05.953221Z","iopub.status.idle":"2025-06-13T06:40:05.956946Z","shell.execute_reply.started":"2025-06-13T06:40:05.953199Z","shell.execute_reply":"2025-06-13T06:40:05.956231Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#%% [markdown]\n# 2. Load Metadata and Prepare Label Encoder\n#%%\n\nmetadata = pd.read_csv(CSV_PATH)\nle = LabelEncoder()\nmetadata['label'] = le.fit_transform(metadata['sign'])\nnum_classes = metadata['label'].nunique()\nprint(f\"Loaded {len(metadata)} sequences across {num_classes} signs.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-13T06:40:08.470204Z","iopub.execute_input":"2025-06-13T06:40:08.470721Z","iopub.status.idle":"2025-06-13T06:40:08.579400Z","shell.execute_reply.started":"2025-06-13T06:40:08.470702Z","shell.execute_reply":"2025-06-13T06:40:08.578741Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#%% [markdown]\n# 3. Feature Extraction Helpers\n#%%\n\ndef extract_sequence_from_parquet(path, seq_len=SEQUENCE_LENGTH, feat_dim=FEATURE_DIM):\n    df = pd.read_parquet(path)\n    seq = []\n    grouped = df.groupby('frame')\n    for frame_no, group in grouped:\n        arr = np.zeros((feat_dim,), dtype=np.float32)\n        idx = 0\n        for t, count in [('pose', 33), ('face', 468), ('left_hand', 21), ('right_hand', 21)]:\n            subset = group[group['type'] == t]\n            coords = subset.sort_values('landmark_index')[['x','y','z']].to_numpy()\n            flat = coords.flatten() if len(coords) == count else np.zeros((count*3,),)\n            arr[idx:idx+count*3] = flat\n            idx += count*3\n        seq.append(arr)\n    if len(seq) >= seq_len:\n        seq = seq[:seq_len]\n    else:\n        for _ in range(seq_len - len(seq)):\n            seq.append(np.zeros((feat_dim,),))\n    return np.stack(seq)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-13T06:40:11.105045Z","iopub.execute_input":"2025-06-13T06:40:11.105634Z","iopub.status.idle":"2025-06-13T06:40:11.111616Z","shell.execute_reply.started":"2025-06-13T06:40:11.105615Z","shell.execute_reply":"2025-06-13T06:40:11.110879Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#%% [markdown]\n# 4. Build Dataset Arrays\n#%%\n\n# X = []\n# Y = []\n# for _, row in tqdm(metadata.iterrows(), total=len(metadata)):\n#     p = row['participant_id']\n#     s = row['sequence_id']\n#     path = os.path.join(DATA_DIR, str(p), f\"{s}.parquet\")\n#     if os.path.exists(path):\n#         seq_arr = extract_sequence_from_parquet(path)\n#         X.append(seq_arr)\n#         Y.append(row['label'])\n#     else:\n#         print(f\"Missing file: {path}\")\n# X = np.array(X)\n# Y = tf.keras.utils.to_categorical(Y, num_classes=num_classes)\n# print(\"X shape:\", X.shape, \"Y shape:\", Y.shape)\n\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef process_row(row):\n    p = row['participant_id']\n    s = row['sequence_id']\n    path = os.path.join(DATA_DIR, str(p), f\"{s}.parquet\")\n    if os.path.exists(path):\n        try:\n            arr = extract_sequence_from_parquet(path)\n            return arr, row['label']\n        except Exception as e:\n            print(f\"Failed reading {path}: {e}\")\n            return None\n    return None\n\ndef process_chunk(chunk_df):\n    with ThreadPoolExecutor(max_workers=8) as executor:\n        results = list(tqdm(executor.map(process_row, [row for _, row in chunk_df.iterrows()]), total=len(chunk_df)))\n    results = [r for r in results if r is not None]\n    if results:\n        X_chunk, Y_chunk = zip(*results)\n        return np.array(X_chunk), tf.keras.utils.to_categorical(Y_chunk, num_classes=num_classes)\n    else:\n        return np.empty((0, SEQ_LEN, NUM_FEATURES)), np.empty((0, num_classes))  # Adjust shape as needed\n\n# Split metadata into N chunks\nchunk_size = 500  # Try small chunks first\nchunks = [metadata.iloc[i:i + chunk_size] for i in range(0, len(metadata), chunk_size)]\n\nX_parts, Y_parts = [], []\n\nfor i, chunk in enumerate(chunks):\n    print(f\"\\nProcessing chunk {i+1}/{len(chunks)}...\")\n    X_chunk, Y_chunk = process_chunk(chunk)\n    X_parts.append(X_chunk)\n    Y_parts.append(Y_chunk)\n\n# Merge all processed chunks\nX = np.concatenate(X_parts, axis=0)\nY = np.concatenate(Y_parts, axis=0)\n\nprint(\"Final X shape:\", X.shape)\nprint(\"Final Y shape:\", Y.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-13T06:40:15.130105Z","iopub.execute_input":"2025-06-13T06:40:15.130825Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(Y_parts)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-13T04:53:00.857190Z","iopub.status.idle":"2025-06-13T04:53:00.857446Z","shell.execute_reply.started":"2025-06-13T04:53:00.857331Z","shell.execute_reply":"2025-06-13T04:53:00.857343Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data = np.load('cached_asl_data.npz')\nX, Y = data['X'], data['Y']\n# df = pd.DataFrame(np.array(X, Y))\n# print(df)\nlabels = np.argmax(Y, axis=1)\ndf = pd.DataFrame({\"label\": labels})\nprint(df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-10T18:39:15.495516Z","iopub.execute_input":"2025-06-10T18:39:15.495765Z","iopub.status.idle":"2025-06-10T18:39:19.346727Z","shell.execute_reply.started":"2025-06-10T18:39:15.495749Z","shell.execute_reply":"2025-06-10T18:39:19.346006Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#%% [markdown]\n# 5. Train/Test Split\n#%%\n\nX_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=0.2, random_state=RANDOM_STATE, stratify=Y)\nprint(\"Train:\", X_train.shape, Y_train.shape)\nprint(\"Val:\", X_val.shape, Y_val.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-10T18:41:05.290121Z","iopub.execute_input":"2025-06-10T18:41:05.290892Z","iopub.status.idle":"2025-06-10T18:41:06.320888Z","shell.execute_reply.started":"2025-06-10T18:41:05.290864Z","shell.execute_reply":"2025-06-10T18:41:06.320157Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#%% [markdown]\n# 6. Model Definition\n#%%\n\nmodel = Sequential([\n    LSTM(128, return_sequences=True, input_shape=(SEQUENCE_LENGTH, FEATURE_DIM)),\n    BatchNormalization(),\n    Dropout(0.3),\n    LSTM(64),\n    BatchNormalization(),\n    Dropout(0.3),\n    Dense(64, activation='relu'),\n    Dropout(0.3),\n    Dense(num_classes, activation='softmax')\n])\nmodel.compile(\n    optimizer='adam',\n    loss='categorical_crossentropy',\n    metrics=['accuracy']\n)\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-10T18:41:13.570897Z","iopub.execute_input":"2025-06-10T18:41:13.571477Z","iopub.status.idle":"2025-06-10T18:41:16.148788Z","shell.execute_reply.started":"2025-06-10T18:41:13.571455Z","shell.execute_reply":"2025-06-10T18:41:16.148075Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#%% [markdown]\n# 7. Training\n#%%\n\ncallbacks = [\n    EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True),\n    TensorBoard(log_dir='./logs')\n]\nhistory = model.fit(\n    X_train, Y_train,\n    validation_data=(X_val, Y_val),\n    epochs=EPOCHS,\n    batch_size=BATCH_SIZE,\n    callbacks=callbacks\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-10T18:41:22.291940Z","iopub.execute_input":"2025-06-10T18:41:22.292436Z","iopub.status.idle":"2025-06-10T18:41:37.914067Z","shell.execute_reply.started":"2025-06-10T18:41:22.292403Z","shell.execute_reply":"2025-06-10T18:41:37.913273Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save trained model\nmodel.save('asl_lstm_parquet.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-10T18:41:49.329197Z","iopub.execute_input":"2025-06-10T18:41:49.329506Z","iopub.status.idle":"2025-06-10T18:41:49.406776Z","shell.execute_reply.started":"2025-06-10T18:41:49.329487Z","shell.execute_reply":"2025-06-10T18:41:49.406172Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.predict(X_val)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-10T19:04:05.944998Z","iopub.execute_input":"2025-06-10T19:04:05.945603Z","iopub.status.idle":"2025-06-10T19:04:06.242069Z","shell.execute_reply.started":"2025-06-10T19:04:05.945577Z","shell.execute_reply":"2025-06-10T19:04:06.241501Z"}},"outputs":[],"execution_count":null}]}