{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tqdm.notebook import tqdm\n\nplt.style.use(\"seaborn-colorblind\")","metadata":{"execution":{"iopub.status.busy":"2023-05-01T11:15:06.780712Z","iopub.execute_input":"2023-05-01T11:15:06.781154Z","iopub.status.idle":"2023-05-01T11:15:06.791001Z","shell.execute_reply.started":"2023-05-01T11:15:06.781115Z","shell.execute_reply":"2023-05-01T11:15:06.789636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install nb_black --quiet\n%load_ext lab_black","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-05-01T11:15:07.591144Z","iopub.execute_input":"2023-05-01T11:15:07.591608Z","iopub.status.idle":"2023-05-01T11:15:19.575820Z","shell.execute_reply.started":"2023-05-01T11:15:07.591565Z","shell.execute_reply":"2023-05-01T11:15:19.574540Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls ../input/asl-signs/ -GFlash --color","metadata":{"execution":{"iopub.status.busy":"2023-05-01T11:15:19.578214Z","iopub.execute_input":"2023-05-01T11:15:19.578585Z","iopub.status.idle":"2023-05-01T11:15:20.708334Z","shell.execute_reply.started":"2023-05-01T11:15:19.578546Z","shell.execute_reply":"2023-05-01T11:15:20.706992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASE_DIR = \"../input/asl-signs/\"\ntrain = pd.read_csv(f\"{BASE_DIR}/train.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-05-01T11:15:20.709951Z","iopub.execute_input":"2023-05-01T11:15:20.710431Z","iopub.status.idle":"2023-05-01T11:15:20.847171Z","shell.execute_reply.started":"2023-05-01T11:15:20.710382Z","shell.execute_reply":"2023-05-01T11:15:20.845651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-01T11:15:20.850031Z","iopub.execute_input":"2023-05-01T11:15:20.850393Z","iopub.status.idle":"2023-05-01T11:15:20.868179Z","shell.execute_reply.started":"2023-05-01T11:15:20.850358Z","shell.execute_reply":"2023-05-01T11:15:20.866731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(figsize=(8, 8))\ntrain[\"sign\"].value_counts().head(50).sort_values(ascending=True).plot(\n    kind=\"barh\", ax=ax, title=\"Top 50 Signs in Training Dataset\"\n)\nax.set_xlabel (\"Number of Training Examples\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-01T11:15:20.870084Z","iopub.execute_input":"2023-05-01T11:15:20.870512Z","iopub.status.idle":"2023-05-01T11:15:21.613210Z","shell.execute_reply.started":"2023-05-01T11:15:20.870474Z","shell.execute_reply":"2023-05-01T11:15:21.611744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(figsize=(8, 8))\ntrain[\"sign\"].value_counts().tail(50).sort_values(ascending=True).plot(\n    kind=\"barh\", ax=ax, title=\"Bottom 50 Signs in Training Dataset\"\n)\nax.set_xlabel(\"Number of Training Examples\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-01T11:15:21.614838Z","iopub.execute_input":"2023-05-01T11:15:21.615213Z","iopub.status.idle":"2023-05-01T11:15:22.522748Z","shell.execute_reply.started":"2023-05-01T11:15:21.615176Z","shell.execute_reply":"2023-05-01T11:15:22.521246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_fn = train.query('sign == \"listen\"')[\"path\"].values[0]\n\nexample_landmark = pd.read_parquet(f\"{BASE_DIR}/{example_fn}\")\nexample_landmark.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-01T11:15:22.524081Z","iopub.execute_input":"2023-05-01T11:15:22.524399Z","iopub.status.idle":"2023-05-01T11:15:22.559959Z","shell.execute_reply.started":"2023-05-01T11:15:22.524367Z","shell.execute_reply":"2023-05-01T11:15:22.558736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"unique_frames = example_landmark[\"frame\"].nunique()\nunique_types = example_landmark[\"type\"].nunique()\ntypes_in_video = example_landmark[\"type\"].unique()\nprint(\n    f\"The file has {unique_frames} unique frames and {unique_types} unique types: {types_in_video}\"\n)","metadata":{"execution":{"iopub.status.busy":"2023-05-01T11:15:22.561247Z","iopub.execute_input":"2023-05-01T11:15:22.561561Z","iopub.status.idle":"2023-05-01T11:15:22.574931Z","shell.execute_reply.started":"2023-05-01T11:15:22.561530Z","shell.execute_reply":"2023-05-01T11:15:22.573387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"listen_files = train.query('sign == \"listen\"')[\"path\"].values\nfor i, f in enumerate(listen_files):\n    example_landmark = pd.read_parquet(f\"{BASE_DIR}/{f}\")\n    unique_frames = example_landmark[\"frame\"].nunique()\n    unique_types = example_landmark[\"type\"].nunique()\n    types_in_video = example_landmark[\"type\"].unique()\n    print(\n        f\"The file has {unique_frames} unique frames and {unique_types} unique types: {types_in_video}\"\n    )\n    if i == 20:\n        break","metadata":{"execution":{"iopub.status.busy":"2023-05-01T11:15:22.577206Z","iopub.execute_input":"2023-05-01T11:15:22.577708Z","iopub.status.idle":"2023-05-01T11:15:22.957861Z","shell.execute_reply.started":"2023-05-01T11:15:22.577636Z","shell.execute_reply":"2023-05-01T11:15:22.956334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"N_PARQUETS_TO_READ = 100_000\n\ncombined_meta = {}\nfor i, d in tqdm(train.iterrows(), total=len(train)):\n    file_path = d[\"path\"]\n    example_landmark = pd.read_parquet(f\"{BASE_DIR}/{file_path}\")\n\n    meta = (\n        example_landmark.dropna(subset=[\"x\", \"y\", \"z\"])[\"type\"].value_counts().to_dict()\n    )\n    meta[\"frames\"] = example_landmark[\"frame\"].nunique()\n    xyz_meta = (\n        example_landmark.agg(\n            {\n                \"x\": [\"min\", \"max\", \"mean\"],\n                \"y\": [\"min\", \"max\", \"mean\"],\n                \"z\": [\"min\", \"max\", \"mean\"],\n            }\n        )\n        .unstack()\n        .to_dict()\n    )\n\n    for key in xyz_meta.keys():\n        new_key = key[0] + \"_\" + key[1]\n        meta[new_key] = xyz_meta[key]\n    combined_meta[file_path] = meta\n    if i >= N_PARQUETS_TO_READ:\n        break","metadata":{"execution":{"iopub.status.busy":"2023-05-01T11:38:06.335154Z","iopub.execute_input":"2023-05-01T11:38:06.335639Z","iopub.status.idle":"2023-05-01T12:39:31.276049Z","shell.execute_reply.started":"2023-05-01T11:38:06.335598Z","shell.execute_reply":"2023-05-01T12:39:31.273061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"2 + 2","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:40:28.684649Z","iopub.execute_input":"2023-05-01T12:40:28.685127Z","iopub.status.idle":"2023-05-01T12:40:28.697268Z","shell.execute_reply.started":"2023-05-01T12:40:28.685083Z","shell.execute_reply":"2023-05-01T12:40:28.696005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_with_meta = train.merge(\n    pd.DataFrame(combined_meta).T.reset_index().rename(columns={\"index\": \"path\"}),\n    how=\"left\",\n)\ntrain_with_meta.to_parquet(\"train_with_meta.parquet\")","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:39:53.546171Z","iopub.execute_input":"2023-05-01T12:39:53.546691Z","iopub.status.idle":"2023-05-01T12:39:57.701694Z","shell.execute_reply.started":"2023-05-01T12:39:53.546637Z","shell.execute_reply":"2023-05-01T12:39:57.700518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_with_meta[[\"face\", \"pose\", \"left_hand\", \"right_hand\"]].sum().sort_values().plot(\n    kind=\"barh\", title=\"Sum of Rows by Landmark Type\"\n)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:39:57.703216Z","iopub.execute_input":"2023-05-01T12:39:57.703556Z","iopub.status.idle":"2023-05-01T12:39:57.975525Z","shell.execute_reply.started":"2023-05-01T12:39:57.703524Z","shell.execute_reply":"2023-05-01T12:39:57.974165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"(\n    train_with_meta.query(\"index < 1000\").fillna(0)[\n        [\"face\", \"pose\", \"left_hand\", \"right_hand\"]\n    ]\n    > 0\n).mean().plot(kind=\"barh\", title=\"Rate of Frame/Keypoints with Data\")","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:39:57.977531Z","iopub.execute_input":"2023-05-01T12:39:57.978034Z","iopub.status.idle":"2023-05-01T12:39:58.354704Z","shell.execute_reply.started":"2023-05-01T12:39:57.977966Z","shell.execute_reply":"2023-05-01T12:39:58.353206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_fn = train_with_meta.dropna().query('sign == \"shhh\"')[\"path\"].values[0]\nexample_landmark = pd.read_parquet(f\"{BASE_DIR}/{example_fn}\")","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:39:58.358884Z","iopub.execute_input":"2023-05-01T12:39:58.359271Z","iopub.status.idle":"2023-05-01T12:39:58.423288Z","shell.execute_reply.started":"2023-05-01T12:39:58.359235Z","shell.execute_reply":"2023-05-01T12:39:58.421750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_landmark.query(\"frame == 25\")[\"type\"].value_counts()","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:39:58.425074Z","iopub.execute_input":"2023-05-01T12:39:58.425576Z","iopub.status.idle":"2023-05-01T12:39:58.444595Z","shell.execute_reply.started":"2023-05-01T12:39:58.425535Z","shell.execute_reply":"2023-05-01T12:39:58.443307Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_landmark[\"no_xyz\"] = example_landmark[\"x\"].isna()","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:39:58.446314Z","iopub.execute_input":"2023-05-01T12:39:58.446893Z","iopub.status.idle":"2023-05-01T12:39:58.455560Z","shell.execute_reply.started":"2023-05-01T12:39:58.446854Z","shell.execute_reply":"2023-05-01T12:39:58.454202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_landmark.groupby(\"frame\")[\"no_xyz\"].sum().plot(\n    title=\"missing xyz per frame\", kind=\"bar\"\n)","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:39:58.457317Z","iopub.execute_input":"2023-05-01T12:39:58.457816Z","iopub.status.idle":"2023-05-01T12:39:58.836934Z","shell.execute_reply.started":"2023-05-01T12:39:58.457761Z","shell.execute_reply":"2023-05-01T12:39:58.835701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import plotly.express as px\n\nexample_frame = example_landmark.query(\"frame == 17\")\npx.scatter_3d(example_frame, x=\"x\", y=\"y\", z=\"z\", color=\"type\")","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:39:58.838629Z","iopub.execute_input":"2023-05-01T12:39:58.839118Z","iopub.status.idle":"2023-05-01T12:40:03.954404Z","shell.execute_reply.started":"2023-05-01T12:39:58.839065Z","shell.execute_reply":"2023-05-01T12:40:03.953043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_landmark[\"y_\"] = example_landmark[\"y\"] * -1\nexample_frame = example_landmark.query(\"frame == 17 and type== 'face'\")\npx.scatter(example_frame, x=\"x\", y=\"y_\", color=\"type\")","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:40:03.958242Z","iopub.execute_input":"2023-05-01T12:40:03.959572Z","iopub.status.idle":"2023-05-01T12:40:04.241567Z","shell.execute_reply.started":"2023-05-01T12:40:03.959513Z","shell.execute_reply":"2023-05-01T12:40:04.239926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install mediapipe --quiet","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:40:04.243105Z","iopub.execute_input":"2023-05-01T12:40:04.243510Z","iopub.status.idle":"2023-05-01T12:40:20.807034Z","shell.execute_reply.started":"2023-05-01T12:40:04.243469Z","shell.execute_reply":"2023-05-01T12:40:20.804932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import mediapipe as mp\n\nmp_hands = mp.solutions.hands\n\n\nexample_landmark[\"y_\"] = example_landmark[\"y\"] * -1\n\nfig, ax = plt.subplots(figsize=(5, 5))\n\nfor hand in [\"left_hand\", \"right_hand\"]:\n    example_hand = example_landmark.query(\"frame == 17 and type == @hand\")\n\n    ax.scatter(example_hand[\"x\"], example_hand[\"y_\"])\n\n    for connection in mp_hands.HAND_CONNECTIONS:\n        point_a = connection[0]\n        point_b = connection[1]\n        x1, y1 = example_hand.query(\"landmark_index == @point_a\")[[\"x\", \"y_\"]].values[0]\n        x2, y2 = example_hand.query(\"landmark_index == @point_b\")[[\"x\", \"y_\"]].values[0]\n        plt.plot([x1, x2], [y1, y2], color=\"purple\")\nax.set_title(\"Shhh - Hands Data\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:40:20.809496Z","iopub.execute_input":"2023-05-01T12:40:20.809994Z","iopub.status.idle":"2023-05-01T12:40:21.944779Z","shell.execute_reply.started":"2023-05-01T12:40:20.809940Z","shell.execute_reply":"2023-05-01T12:40:21.943299Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!wget https://i.ytimg.com/vi/mi9f9zOaqM8/hqdefault.jpg --quiet\n!wget https://previews.123rf.com/images/mimagephotography/mimagephotography1411/mimagephotography141100022/33214722-full-length-portrait-of-a-fashionable-young-man-standing-on-isolated-white-background.jpg --quiet","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:40:21.946487Z","iopub.execute_input":"2023-05-01T12:40:21.946879Z","iopub.status.idle":"2023-05-01T12:40:24.832150Z","shell.execute_reply.started":"2023-05-01T12:40:21.946840Z","shell.execute_reply":"2023-05-01T12:40:24.830220Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport mediapipe as mp\n\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_holistic = mp.solutions.holistic\n\n# For static images:\nIMAGE_FILES = [\n    \"hqdefault.jpg\",\n    \"33214722-full-length-portrait-of-a-fashionable-young-man-standing-on-isolated-white-background.jpg\",\n]\nBG_COLOR = (192, 192, 192)  # gray\nwith mp_holistic.Holistic(\n    static_image_mode=True,\n    model_complexity=2,\n    enable_segmentation=True,\n    refine_face_landmarks=True,\n) as holistic:\n    for idx, file in enumerate(IMAGE_FILES):\n        image = cv2.imread(file)\n        image_height, image_width, _ = image.shape\n        results = holistic.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n\n        if results.pose_landmarks:\n            print(\n                f\"Nose coordinates: (\"\n                f\"{results.pose_landmarks.landmark[mp_holistic.PoseLandmark.NOSE].x * image_width}, \"\n                f\"{results.pose_landmarks.landmark[mp_holistic.PoseLandmark.NOSE].y * image_height})\"\n            )\n\n        annotated_image = image.copy()\n\n        condition = np.stack((results.segmentation_mask,) * 3, axis=-1) > 0.1\n        bg_image = np.zeros(image.shape, dtype=np.uint8)\n        bg_image[:] = BG_COLOR\n        annotated_image = np.where(condition, annotated_image, bg_image)\n        # Draw pose, left and right hands, and face landmarks on the image.\n        mp_drawing.draw_landmarks(\n            annotated_image,\n            results.face_landmarks,\n            mp_holistic.FACEMESH_TESSELATION,\n            landmark_drawing_spec=None,\n            connection_drawing_spec=mp_drawing_styles.get_default_face_mesh_tesselation_style(),\n        )\n        mp_drawing.draw_landmarks(\n            annotated_image,\n            results.pose_landmarks,\n            mp_holistic.POSE_CONNECTIONS,\n            landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style(),\n        )\n        cv2.imwrite(\"/tmp/annotated_image\" + str(idx) + \".png\", annotated_image)","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:40:24.834599Z","iopub.execute_input":"2023-05-01T12:40:24.835103Z","iopub.status.idle":"2023-05-01T12:40:27.405290Z","shell.execute_reply.started":"2023-05-01T12:40:24.835049Z","shell.execute_reply":"2023-05-01T12:40:27.403660Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(plt.imread(\"/tmp/annotated_image\" + str(0) + \".png\"))\nplt.show()\n\nplt.imshow(plt.imread(\"/tmp/annotated_image\" + str(1) + \".png\"))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:40:27.406928Z","iopub.execute_input":"2023-05-01T12:40:27.407368Z","iopub.status.idle":"2023-05-01T12:40:28.151340Z","shell.execute_reply.started":"2023-05-01T12:40:27.407327Z","shell.execute_reply":"2023-05-01T12:40:28.149872Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"background_image = np.zeros([720, 720, 3])\n\nmp_drawing.draw_landmarks(\n    background_image,\n    results.face_landmarks,\n    mp_holistic.FACEMESH_TESSELATION,\n    landmark_drawing_spec=None,\n    connection_drawing_spec=mp_drawing_styles.get_default_face_mesh_tesselation_style(),\n)\nmp_drawing.draw_landmarks(\n    background_image,\n    results.pose_landmarks,\n    mp_holistic.POSE_CONNECTIONS,\n    landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style(),\n)\nplt.imshow(background_image)","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:40:28.153478Z","iopub.execute_input":"2023-05-01T12:40:28.153863Z","iopub.status.idle":"2023-05-01T12:40:28.590987Z","shell.execute_reply.started":"2023-05-01T12:40:28.153824Z","shell.execute_reply":"2023-05-01T12:40:28.589574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"type(results.face_landmarks)\n\nfrom mediapipe.framework.formats import landmark_pb2","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:40:28.592860Z","iopub.execute_input":"2023-05-01T12:40:28.593336Z","iopub.status.idle":"2023-05-01T12:40:28.603374Z","shell.execute_reply.started":"2023-05-01T12:40:28.593283Z","shell.execute_reply":"2023-05-01T12:40:28.602105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_relevant_data_subset(pq_path):\n    data_columns = [\"x\", \"y\", \"z\"]\n    data = pd.read_parquet(pq_path, columns=data_columns)\n    n_frames = int(len(data) / ROWS_PER_FRAME)\n    data = data.values.reshape(n_frames, ROWS_PER_FRAME, len(data_columns))\n    return data.astype(np.float32)","metadata":{"execution":{"iopub.status.busy":"2023-05-01T12:40:28.605331Z","iopub.execute_input":"2023-05-01T12:40:28.605728Z","iopub.status.idle":"2023-05-01T12:40:28.624481Z","shell.execute_reply.started":"2023-05-01T12:40:28.605687Z","shell.execute_reply":"2023-05-01T12:40:28.623458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}