{"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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-04-16T09:14:57.421962Z","iopub.execute_input":"2023-04-16T09:14:57.423083Z","iopub.status.idle":"2023-04-16T09:14:58.617656Z","shell.execute_reply.started":"2023-04-16T09:14:57.423039Z","shell.execute_reply":"2023-04-16T09:14:58.616715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install nb_black --quiet\n%load_ext lab_black","metadata":{"execution":{"iopub.status.busy":"2023-04-16T09:14:58.619633Z","iopub.execute_input":"2023-04-16T09:14:58.620415Z","iopub.status.idle":"2023-04-16T09:15:14.271077Z","shell.execute_reply.started":"2023-04-16T09:14:58.620375Z","shell.execute_reply":"2023-04-16T09:15:14.269858Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls ../input/asl-signs/ -GFlash --color","metadata":{"execution":{"iopub.status.busy":"2023-04-16T09:15:14.272535Z","iopub.execute_input":"2023-04-16T09:15:14.273511Z","iopub.status.idle":"2023-04-16T09:15:15.370116Z","shell.execute_reply.started":"2023-04-16T09:15:14.273467Z","shell.execute_reply":"2023-04-16T09:15:15.368746Z"},"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-04-16T09:15:15.375004Z","iopub.execute_input":"2023-04-16T09:15:15.375419Z","iopub.status.idle":"2023-04-16T09:15:15.585917Z","shell.execute_reply.started":"2023-04-16T09:15:15.375374Z","shell.execute_reply":"2023-04-16T09:15:15.584790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2023-04-16T09:15:15.587408Z","iopub.execute_input":"2023-04-16T09:15:15.587775Z","iopub.status.idle":"2023-04-16T09:15:15.619911Z","shell.execute_reply.started":"2023-04-16T09:15:15.587739Z","shell.execute_reply":"2023-04-16T09:15:15.618914Z"},"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-04-16T09:15:15.621248Z","iopub.execute_input":"2023-04-16T09:15:15.621762Z","iopub.status.idle":"2023-04-16T09:15:16.426105Z","shell.execute_reply.started":"2023-04-16T09:15:15.621728Z","shell.execute_reply":"2023-04-16T09:15:16.425158Z"},"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-04-16T09:15:16.427112Z","iopub.execute_input":"2023-04-16T09:15:16.427462Z","iopub.status.idle":"2023-04-16T09:15:17.155670Z","shell.execute_reply.started":"2023-04-16T09:15:16.427430Z","shell.execute_reply":"2023-04-16T09:15:17.154294Z"},"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-04-16T09:15:17.157188Z","iopub.execute_input":"2023-04-16T09:15:17.157520Z","iopub.status.idle":"2023-04-16T09:15:17.304002Z","shell.execute_reply.started":"2023-04-16T09:15:17.157486Z","shell.execute_reply":"2023-04-16T09:15:17.303093Z"},"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-04-16T09:15:17.306425Z","iopub.execute_input":"2023-04-16T09:15:17.307526Z","iopub.status.idle":"2023-04-16T09:15:17.318897Z","shell.execute_reply.started":"2023-04-16T09:15:17.307486Z","shell.execute_reply":"2023-04-16T09:15:17.317763Z"},"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-04-16T09:15:17.323310Z","iopub.execute_input":"2023-04-16T09:15:17.323907Z","iopub.status.idle":"2023-04-16T09:15:17.927712Z","shell.execute_reply.started":"2023-04-16T09:15:17.323871Z","shell.execute_reply":"2023-04-16T09:15:17.926506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"N_PARQUETS_TO_READ = 1000  # So we don't have to load all 95k\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    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-04-16T09:15:17.928993Z","iopub.execute_input":"2023-04-16T09:15:17.929316Z","iopub.status.idle":"2023-04-16T09:15:56.086380Z","shell.execute_reply.started":"2023-04-16T09:15:17.929285Z","shell.execute_reply":"2023-04-16T09:15:56.085118Z"},"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-04-16T09:15:56.087634Z","iopub.execute_input":"2023-04-16T09:15:56.087957Z","iopub.status.idle":"2023-04-16T09:15:56.298786Z","shell.execute_reply.started":"2023-04-16T09:15:56.087926Z","shell.execute_reply":"2023-04-16T09:15:56.297417Z"},"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-04-16T09:15:56.301072Z","iopub.execute_input":"2023-04-16T09:15:56.301576Z","iopub.status.idle":"2023-04-16T09:15:56.465095Z","shell.execute_reply.started":"2023-04-16T09:15:56.301525Z","shell.execute_reply":"2023-04-16T09:15:56.463678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# checking to see if the number of landmarks for this type is zero\n(\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-04-16T09:15:56.467115Z","iopub.execute_input":"2023-04-16T09:15:56.468022Z","iopub.status.idle":"2023-04-16T09:15:56.641627Z","shell.execute_reply.started":"2023-04-16T09:15:56.467973Z","shell.execute_reply":"2023-04-16T09:15:56.640695Z"},"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-04-16T09:15:56.643671Z","iopub.execute_input":"2023-04-16T09:15:56.644563Z","iopub.status.idle":"2023-04-16T09:15:56.685812Z","shell.execute_reply.started":"2023-04-16T09:15:56.644512Z","shell.execute_reply":"2023-04-16T09:15:56.684748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_landmark.query(\"frame == 25\")[\"type\"].value_counts()","metadata":{"execution":{"iopub.status.busy":"2023-04-16T09:15:56.687016Z","iopub.execute_input":"2023-04-16T09:15:56.687369Z","iopub.status.idle":"2023-04-16T09:15:56.702319Z","shell.execute_reply.started":"2023-04-16T09:15:56.687335Z","shell.execute_reply":"2023-04-16T09:15:56.700835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_landmark[\"no_xyz\"] = example_landmark[\"x\"].isna()","metadata":{"execution":{"iopub.status.busy":"2023-04-16T09:15:56.704325Z","iopub.execute_input":"2023-04-16T09:15:56.704808Z","iopub.status.idle":"2023-04-16T09:15:56.714491Z","shell.execute_reply.started":"2023-04-16T09:15:56.704756Z","shell.execute_reply":"2023-04-16T09:15:56.713338Z"},"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-04-16T09:15:56.715772Z","iopub.execute_input":"2023-04-16T09:15:56.716086Z","iopub.status.idle":"2023-04-16T09:15:57.009917Z","shell.execute_reply.started":"2023-04-16T09:15:56.716056Z","shell.execute_reply":"2023-04-16T09:15:57.008840Z"},"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-04-16T09:15:57.011231Z","iopub.execute_input":"2023-04-16T09:15:57.011630Z","iopub.status.idle":"2023-04-16T09:16:00.518001Z","shell.execute_reply.started":"2023-04-16T09:15:57.011597Z","shell.execute_reply":"2023-04-16T09:16:00.516666Z"},"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-04-16T09:16:00.519547Z","iopub.execute_input":"2023-04-16T09:16:00.519885Z","iopub.status.idle":"2023-04-16T09:16:00.618838Z","shell.execute_reply.started":"2023-04-16T09:16:00.519852Z","shell.execute_reply":"2023-04-16T09:16:00.617840Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install mediapipe --quiet","metadata":{"execution":{"iopub.status.busy":"2023-04-16T09:16:00.620311Z","iopub.execute_input":"2023-04-16T09:16:00.620645Z","iopub.status.idle":"2023-04-16T09:16:13.986111Z","shell.execute_reply.started":"2023-04-16T09:16:00.620614Z","shell.execute_reply":"2023-04-16T09:16:13.984878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import mediapipe as mp\n\nmp_hands = mp.solutions.hands\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-04-16T09:16:13.988338Z","iopub.execute_input":"2023-04-16T09:16:13.988713Z","iopub.status.idle":"2023-04-16T09:16:14.994459Z","shell.execute_reply.started":"2023-04-16T09:16:13.988671Z","shell.execute_reply":"2023-04-16T09:16:14.993510Z"},"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-04-16T09:16:14.995611Z","iopub.execute_input":"2023-04-16T09:16:14.996500Z","iopub.status.idle":"2023-04-16T09:16:18.002819Z","shell.execute_reply.started":"2023-04-16T09:16:14.996462Z","shell.execute_reply":"2023-04-16T09:16:18.001497Z"},"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        # Convert the BGR image to RGB before processing.\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        # Draw segmentation on the image.\n        # To improve segmentation around boundaries, consider applying a joint\n        # bilateral filter to \"results.segmentation_mask\" with \"image\".\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)\n        # Plot pose world landmarks.\n#         mp_drawing.plot_landmarks(\n#             results.pose_world_landmarks, mp_holistic.POSE_CONNECTIONS\n#         )","metadata":{"execution":{"iopub.status.busy":"2023-04-16T09:16:18.004451Z","iopub.execute_input":"2023-04-16T09:16:18.004829Z","iopub.status.idle":"2023-04-16T09:16:20.444220Z","shell.execute_reply.started":"2023-04-16T09:16:18.004787Z","shell.execute_reply":"2023-04-16T09:16:20.442881Z"},"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-04-16T09:16:20.445525Z","iopub.execute_input":"2023-04-16T09:16:20.446492Z","iopub.status.idle":"2023-04-16T09:16:21.158979Z","shell.execute_reply.started":"2023-04-16T09:16:20.446445Z","shell.execute_reply":"2023-04-16T09:16:21.157766Z"},"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-04-16T09:16:21.160219Z","iopub.execute_input":"2023-04-16T09:16:21.160524Z","iopub.status.idle":"2023-04-16T09:16:21.587781Z","shell.execute_reply.started":"2023-04-16T09:16:21.160493Z","shell.execute_reply":"2023-04-16T09:16:21.586219Z"},"trusted":true},"execution_count":null,"outputs":[]}]}