{"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 numpy as np\nimport pandas as pd\nimport json\nimport plotly.graph_objects as go\nimport plotly.io as pio","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-07-08T10:33:35.403214Z","iopub.execute_input":"2023-07-08T10:33:35.403568Z","iopub.status.idle":"2023-07-08T10:33:35.419462Z","shell.execute_reply.started":"2023-07-08T10:33:35.403535Z","shell.execute_reply":"2023-07-08T10:33:35.418342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Look at the general data set content\nfile_path = \"/kaggle/input/asl-fingerspelling/train.csv\"\ndf_train = pd.read_csv(file_path)\ndf_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-07-08T10:33:35.420877Z","iopub.execute_input":"2023-07-08T10:33:35.422113Z","iopub.status.idle":"2023-07-08T10:33:35.535259Z","shell.execute_reply.started":"2023-07-08T10:33:35.422076Z","shell.execute_reply":"2023-07-08T10:33:35.534107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Apply the desired sequence\nfile_id = 5414471\nsequence_id = 1816909464\nfile_id_path = \"/kaggle/input/asl-fingerspelling/train_landmarks/\"+str(file_id)+\".parquet\"\n\n# Import the data from the desired file id that includes the sequence\ndf = pd.read_parquet(file_id_path)","metadata":{"execution":{"iopub.status.busy":"2023-07-08T10:33:35.536817Z","iopub.execute_input":"2023-07-08T10:33:35.537179Z","iopub.status.idle":"2023-07-08T10:33:39.875122Z","shell.execute_reply.started":"2023-07-08T10:33:35.537147Z","shell.execute_reply":"2023-07-08T10:33:39.874165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Take a look at at the desired sequence landmarks\ndf_sequence = df[df.index == sequence_id]\ndf_sequence","metadata":{"execution":{"iopub.status.busy":"2023-07-08T10:33:39.877772Z","iopub.execute_input":"2023-07-08T10:33:39.878166Z","iopub.status.idle":"2023-07-08T10:33:39.916344Z","shell.execute_reply.started":"2023-07-08T10:33:39.878131Z","shell.execute_reply":"2023-07-08T10:33:39.915252Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def map_new_to_old_style(sequence):\n    types = []\n    landmark_indexes = []\n\n    # Extracting types and landmark indexes from column names\n    for column in list(sequence.columns)[1:544]:\n        parts = column.split(\"_\")\n        if len(parts) == 4:\n            types.append(parts[1] + \"_\" + parts[2])\n        else:\n            types.append(parts[1])\n        landmark_indexes.append(int(parts[-1]))\n\n    data = {\n        \"frame\": [],\n        \"type\": [],\n        \"landmark_index\": [],\n        \"x\": [],\n        \"y\": [],\n        \"z\": []\n    }\n\n    # Constructing the data dictionary\n    for index, row in sequence.iterrows():\n        data[\"frame\"] += [int(row.frame)] * 543\n        data[\"type\"] += types\n        data[\"landmark_index\"] += landmark_indexes\n\n        for _type, landmark_index in zip(types, landmark_indexes):\n            data[\"x\"].append(row[f\"x_{_type}_{landmark_index}\"])\n            data[\"y\"].append(row[f\"y_{_type}_{landmark_index}\"])\n            data[\"z\"].append(row[f\"z_{_type}_{landmark_index}\"])\n\n    return pd.DataFrame.from_dict(data)\n\ndef assign_color(row):\n    # Assigning colors based on the type of landmark\n    if row == 'face':\n        return 'rgb(255, 0, 0)'  # Red\n    elif 'hand' in row:\n        return 'rgb(30, 144, 255)'  # Dodger Blue\n    else:\n        return 'rgb(0, 255, 0)'  # Green\n\ndef assign_order(row):\n    # Assigning plotting order based on the type of landmark\n    if row.type == 'face':\n        return row.landmark_index + 101\n    elif row.type == 'pose':\n        return row.landmark_index + 30\n    elif row.type == 'left_hand':\n        return row.landmark_index + 80\n    else:\n        return row.landmark_index\n\ndef visualise2d_landmarks(parquet_df, title=\"\"):\n    connections = [\n        [0, 1, 2, 3, 4],\n        [0, 5, 6, 7, 8],\n        [0, 9, 10, 11, 12],\n        [0, 13, 14, 15, 16],\n        [0, 17, 18, 19, 20],\n        [38, 36, 35, 34, 30, 31, 32, 33, 37],\n        [40, 39],\n        [52, 46, 50, 48, 46, 44, 42, 41, 43, 45, 47, 49, 45, 51],\n        [42, 54, 56, 58, 60, 62, 58],\n        [41, 53, 55, 57, 59, 61, 57],\n        [54, 53],\n        [80, 81, 82, 83, 84],\n        [80, 85, 86, 87, 88],\n        [80, 89, 90, 91, 92],\n        [80, 93, 94, 95, 96],\n        [80, 97, 98, 99, 100],\n    ]\n\n    parquet_df = map_new_to_old_style(parquet_df)\n    frames = sorted(set(parquet_df.frame))\n    first_frame = min(frames)\n\n    # Adding color and plot_order columns to the DataFrame\n    parquet_df['color'] = parquet_df.type.apply(lambda row: assign_color(row))\n    parquet_df['plot_order'] = parquet_df.apply(lambda row: assign_order(row), axis=1)\n    first_frame_df = parquet_df[parquet_df.frame == first_frame].copy()\n    first_frame_df = first_frame_df.sort_values([\"plot_order\"]).set_index('plot_order')\n\n    frames_l = []\n    for frame in frames:\n        filtered_df = parquet_df[parquet_df.frame == frame].copy()\n        filtered_df = filtered_df.sort_values([\"plot_order\"]).set_index(\"plot_order\")\n        traces = [go.Scatter(\n            x=filtered_df['x'],\n            y=filtered_df['y'],\n            mode='markers',\n            marker=dict(\n                color=filtered_df.color,\n                size=9\n            )\n        )]\n\n        for i, seg in enumerate(connections):\n            trace = go.Scatter(\n                x=filtered_df.loc[seg]['x'],\n                y=filtered_df.loc[seg]['y'],\n                mode='lines'\n            )\n            traces.append(trace)\n        frame_data = go.Frame(data=traces, traces=[i for i in range(17)])\n        frames_l.append(frame_data)\n\n    traces = [go.Scatter(\n        x=first_frame_df['x'],\n        y=first_frame_df['y'],\n        mode='markers',\n        marker=dict(\n            color=first_frame_df.color,\n            size=9\n        )\n    )]\n    for i, seg in enumerate(connections):\n        trace = go.Scatter(\n            x=first_frame_df.loc[seg]['x'],\n            y=first_frame_df.loc[seg]['y'],\n            mode='lines',\n            line=dict(\n                color='black',\n                width=2\n            )\n        )\n        traces.append(trace)\n    fig = go.Figure(\n        data=traces,\n        frames=frames_l\n    )\n\n    fig.update_layout(\n        width=500,\n        height=800,\n        scene={'aspectmode': 'data'},\n        updatemenus=[\n            {\n                \"buttons\": [\n                    {\n                        \"args\": [None, {\n                            \"frame\": {\"duration\": 100, \"redraw\": True},\n                            \"fromcurrent\": True,\n                            \"transition\": {\"duration\": 0}\n                        }],\n                        \"label\": \"&#9654;\",\n                        \"method\": \"animate\",\n                    },\n\n                ],\n                \"direction\": \"left\",\n                \"pad\": {\"r\": 100, \"t\": 100},\n                \"font\": {\"size\": 30},\n                \"type\": \"buttons\",\n                \"x\": 0.1,\n                \"y\": 0,\n            }\n        ],\n    )\n    camera = dict(\n        up=dict(x=0, y=-1, z=0),\n        eye=dict(x=0, y=0, z=2.5)\n    )\n    fig.update_layout(title_text=title, title_x=0.5)\n    fig.update_layout(scene_camera=camera, showlegend=False)\n    fig.update_layout(xaxis=dict(visible=False), yaxis=dict(visible=False))\n    fig.update_yaxes(autorange=\"reversed\")\n\n    fig.show()\n\ndef get_phrase(df, file_id, sequence_id):\n    '''\n    To get a phrase by filtering file_id and sequence_id at the train.csv file\n    Eg. file_id = 5414471, sequence_id = 1816796431 the phrase will be: '3 creekhouse'\n    '''\n    return df.loc[(df.file_id == file_id) & (df.sequence_id == sequence_id), 'phrase'].iloc[0]","metadata":{"execution":{"iopub.status.busy":"2023-07-08T10:33:39.91798Z","iopub.execute_input":"2023-07-08T10:33:39.918573Z","iopub.status.idle":"2023-07-08T10:33:39.95161Z","shell.execute_reply.started":"2023-07-08T10:33:39.918536Z","shell.execute_reply":"2023-07-08T10:33:39.950614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sequence_phrase = get_phrase(df_train, \n                             file_id, \n                             sequence_id)\nsequence_phrase","metadata":{"execution":{"iopub.status.busy":"2023-07-08T10:33:39.953344Z","iopub.execute_input":"2023-07-08T10:33:39.953737Z","iopub.status.idle":"2023-07-08T10:33:39.970235Z","shell.execute_reply.started":"2023-07-08T10:33:39.953706Z","shell.execute_reply":"2023-07-08T10:33:39.969206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"visualise2d_landmarks(df_sequence, \n                      f\"Phrase: {sequence_phrase}\")","metadata":{"execution":{"iopub.status.busy":"2023-07-08T10:33:39.97346Z","iopub.execute_input":"2023-07-08T10:33:39.973849Z","iopub.status.idle":"2023-07-08T10:34:07.898468Z","shell.execute_reply.started":"2023-07-08T10:33:39.973817Z","shell.execute_reply":"2023-07-08T10:34:07.897416Z"},"trusted":true},"execution_count":null,"outputs":[]}]}