{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceType":"competition","sourceId":97984,"databundleVersionId":14096757,"isSourceIdPinned":false},{"sourceType":"datasetVersion","sourceId":15659946,"datasetId":10026266,"databundleVersionId":16596481}],"dockerImageVersionId":31328,"isInternetEnabled":false,"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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nprint(\"==== INPUT ROOT ====\")\nprint(os.listdir('/kaggle/input'))\n\nprint(\"\\n==== CHECK YOUR MODEL FOLDER ====\")\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    if \"transformer\" in dirname.lower():\n        print(dirname)\n        for f in filenames:\n            print(\"   \", f)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-11T05:35:13.664877Z","iopub.execute_input":"2026-04-11T05:35:13.665257Z","iopub.status.idle":"2026-04-11T05:35:36.729772Z","shell.execute_reply.started":"2026-04-11T05:35:13.665221Z","shell.execute_reply":"2026-04-11T05:35:36.728850Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    if 'physionet' in dirname.lower():\n        print(dirname)\n        for f in filenames[:5]:\n            print(\"   \", f)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-11T05:40:02.545650Z","iopub.execute_input":"2026-04-11T05:40:02.545980Z","iopub.status.idle":"2026-04-11T05:40:05.111575Z","shell.execute_reply.started":"2026-04-11T05:40:02.545951Z","shell.execute_reply":"2026-04-11T05:40:05.110432Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ===============================\n# Submission Notebook (FINAL)\n# ===============================\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport torch\nimport torch.nn as nn\n\n# ===== 1. Paths =====\nMODEL_PATH = '/kaggle/input/datasets/gclling/transformer-ecg-model/transformer_ecg.pth'\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# ===== 2. Model  =====\nclass PatchEmbedding(nn.Module):\n    def __init__(self, img_size=512, patch_size=16, embed_dim=256):\n        super().__init__()\n        self.proj = nn.Conv2d(3, embed_dim, patch_size, patch_size)\n\n    def forward(self, x):\n        x = self.proj(x)\n        x = x.flatten(2).transpose(1, 2)\n        return x\n\nclass SimpleViT(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.patch = PatchEmbedding()\n\n        num_patches = (512 // 16) ** 2\n        self.pos = nn.Parameter(torch.randn(1, num_patches, 256))\n\n        encoder_layer = nn.TransformerEncoderLayer(\n            d_model=256, nhead=8, batch_first=True\n        )\n        self.transformer = nn.TransformerEncoder(encoder_layer, 4)\n\n        self.decoder = nn.ConvTranspose2d(256, 1, 16, 16)\n\n    def forward(self, x):\n        x = self.patch(x)\n        x = x + self.pos\n        x = self.transformer(x)\n\n        B, N, C = x.shape\n        H = W = int(N ** 0.5)\n\n        x = x.permute(0, 2, 1).contiguous().view(B, C, H, W)\n        x = self.decoder(x)\n        return x\n\n# ===== 3. Load model =====\nmodel = SimpleViT().to(device)\nmodel.load_state_dict(torch.load(MODEL_PATH, map_location=device))\nmodel.eval()\n\nprint(\"Model loaded\")\n\n# ===== 4. Load test metadata =====\nBASE_PATH = '/kaggle/input/competitions/physionet-ecg-image-digitization'\n\ntest_df = pd.read_csv(f'{BASE_PATH}/test.csv')\nTEST_DIR = f'{BASE_PATH}/test'\n\n# sanity check\nprint(test_df.head())\nprint(\"Num test samples:\", len(test_df))\n\n# ===== 5. Dummy reconstruction=====\n# baseline\n\nsubmission = []\n\nfor _, row in test_df.iterrows():\n    base_id = row['id']\n    lead = row['lead']\n    num_rows = row['number_of_rows']\n\n    # ===== inference =====\n    img_path = f\"{TEST_DIR}/{base_id}.png\"\n\n    img = cv2.imread(img_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = cv2.resize(img, (512, 512))\n    img = img.astype(np.float32) / 255.0\n    img = np.transpose(img, (2,0,1))\n\n    img = torch.tensor(img).unsqueeze(0).to(device)\n\n    with torch.no_grad():\n        pred = model(img)\n        pred = torch.sigmoid(pred).cpu().numpy()[0,0]\n\n    # ===== dummy signal（ensure submission format）=====\n    signal = np.zeros(num_rows)\n\n    for i in range(num_rows):\n        submission.append({\n            \"id\": f\"{base_id}_{i}_{lead}\",\n            \"value\": signal[i]\n        })\n\nsubmission_df = pd.DataFrame(submission)\nsubmission_df.to_csv('/kaggle/working/submission.csv', index=False)\n\nprint(\"submission.csv generated\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-11T05:43:34.660540Z","iopub.execute_input":"2026-04-11T05:43:34.661272Z","iopub.status.idle":"2026-04-11T05:43:43.714095Z","shell.execute_reply.started":"2026-04-11T05:43:34.661234Z","shell.execute_reply":"2026-04-11T05:43:43.713189Z"}},"outputs":[],"execution_count":null}]}