File size: 15,172 Bytes
034deef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0fsKoLM5sjn_"
      },
      "outputs": [],
      "source": [
        "# Colab Setup Cell\n",
        "# Install necessary packages\n",
        "!pip -q install -U datasets==3.1.0 pillow pyarrow matplotlib tqdm huggingface_hub\n",
        "\n",
        "from pathlib import Path\n",
        "from datasets import load_dataset, Image\n",
        "import matplotlib.pyplot as plt\n",
        "import matplotlib.patches as patches\n",
        "from PIL import Image as PILImage\n",
        "from tqdm.auto import tqdm\n",
        "from huggingface_hub import hf_hub_url, notebook_login, hf_hub_download # Use hf_hub_download\n",
        "import os # Necessary for creating folders\n",
        "\n",
        "# --- HUGGING FACE AUTHENTICATION (Keep this) ---\n",
        "print(\"--- Authenticating with Hugging Face ---\")\n",
        "notebook_login()\n",
        "\n",
        "# --- Configuration ---\n",
        "DATASET_ID = \"c-i-ber/Nova\"\n",
        "SPLIT_NAME = \"train\"\n",
        "PARQUET_FILE_URL = f\"hf://datasets/{DATASET_ID}/data/nova-v1.parquet\"\n",
        "\n",
        "# --- LOCAL FOLDER CONSTANT ---\n",
        "LOCAL_IMAGE_DIR = \"images\" # The folder where images will be saved\n",
        "\n",
        "MAX_BOXES_TO_DRAW = 5\n",
        "\n",
        "# --- Visualization Style Constants (Unchanged) ---\n",
        "BOX_COLOR = 'cyan'\n",
        "TEXT_COLOR = 'black'\n",
        "BOX_LABEL_BG_COLOR = 'white'\n",
        "TITLE_FONT_SIZE = 12\n",
        "METADATA_SECTION_TITLE_SIZE = 12\n",
        "METADATA_TEXT_SIZE = 10"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# --- HUGGING FACE AUTHENTICATION FIX ---\n",
        "from huggingface_hub import notebook_login\n",
        "import os\n",
        "\n",
        "# 1. Log in to Hugging Face\n",
        "print(\"--- Authenticating with Hugging Face ---\")\n",
        "# This command will open an interactive prompt where you paste your token.\n",
        "# You can get a token from: https://huggingface.co/settings/tokens\n",
        "notebook_login()"
      ],
      "metadata": {
        "id": "yRAVEjw-28yU"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def load_and_prepare_dataset(parquet_url: str) -> \"datasets.Dataset\":\n",
        "    \"\"\"\n",
        "    Loads the dataset structure (metadata) directly from the remote Parquet file.\n",
        "    \"\"\"\n",
        "    print(f\"Loading metadata structure from: {parquet_url}\")\n",
        "    try:\n",
        "        ds = load_dataset(\"parquet\", data_files=parquet_url, split=SPLIT_NAME)\n",
        "    except Exception as e:\n",
        "        print(f\"\\n🚨 Fatal Error: Could not load Parquet file from URL. Details: {e}\")\n",
        "        return None\n",
        "\n",
        "    print(f\"\\nDataset loaded successfully. Total examples: {len(ds)}\")\n",
        "    if \"bboxes\" in ds.column_names:\n",
        "        print(\"✅ SUCCESS: All metadata columns loaded correctly.\")\n",
        "    else:\n",
        "        print(\"🚨 CRITICAL ERROR: 'bboxes' column is missing.\")\n",
        "\n",
        "    return ds\n",
        "\n",
        "\n",
        "def cache_all_images(dataset: \"datasets.Dataset\", dataset_id: str):\n",
        "    \"\"\"\n",
        "    Downloads all images from the HF Hub to the local folder and saves them as JPEGs.\n",
        "    \"\"\"\n",
        "    Path(LOCAL_IMAGE_DIR).mkdir(exist_ok=True)\n",
        "    print(f\"\\n--- Downloading and Caching All Images to: {LOCAL_IMAGE_DIR}/ ---\")\n",
        "\n",
        "    for example in tqdm(dataset, desc=\"Downloading and saving images\", unit=\"img\"):\n",
        "        try:\n",
        "            # 1. Get the image's remote path and local target path\n",
        "            image_url_path = example['image_path']\n",
        "\n",
        "            # The filename is the part after the last slash\n",
        "            filename = Path(image_url_path).name\n",
        "            local_save_path = Path(LOCAL_IMAGE_DIR) / filename\n",
        "\n",
        "            # Skip if the file already exists locally\n",
        "            if local_save_path.exists():\n",
        "                continue\n",
        "\n",
        "            # 2. Download the file's absolute path from HF cache\n",
        "            # This uses the correct function and full internal path\n",
        "            repo_file_path = image_url_path\n",
        "            cached_file_path = hf_hub_download(\n",
        "                repo_id=dataset_id,\n",
        "                filename=repo_file_path,\n",
        "                repo_type=\"dataset\"\n",
        "            )\n",
        "\n",
        "            # 3. Open the downloaded file from the cache and save it to the local folder\n",
        "            img = PILImage.open(cached_file_path)\n",
        "            img.save(local_save_path)\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"\\nWarning: Could not process image {example.get('filename')}. Error: {e}\")\n",
        "\n",
        "    print(\"Caching complete. Demo examples will load instantly from the local folder.\")\n",
        "\n",
        "\n",
        "def load_local_image(filename: str) -> PILImage.Image:\n",
        "    \"\"\"Loads an image from the local directory using its simple filename.\"\"\"\n",
        "    local_path = Path(LOCAL_IMAGE_DIR) / filename\n",
        "    return PILImage.open(local_path)\n",
        "\n",
        "\n",
        "# --- Example Selector Functions (Unchanged) ---\n",
        "# ... (has_boxes, get_example_by_filename, find_first_example_with_boxes are here) ...\n",
        "\n",
        "def has_boxes(example: dict) -> bool:\n",
        "    bboxes = example.get(\"bboxes\", None)\n",
        "    return isinstance(bboxes, list) and len(bboxes) > 0\n",
        "\n",
        "def get_example_by_filename(dataset: \"datasets.Dataset\", filename: str) -> dict:\n",
        "    \"\"\"Retrieves an example from the dataset by its 'filename'.\"\"\"\n",
        "    for i, ex in tqdm(\n",
        "        enumerate(dataset),\n",
        "        total=len(dataset),\n",
        "        desc=f\"Searching for '{filename}'\",\n",
        "        unit=\"ex\",\n",
        "        leave=False\n",
        "    ):\n",
        "        if ex.get(\"filename\") == filename:\n",
        "            return dataset[i]\n",
        "    raise ValueError(f\"Example with filename '{filename}' not found.\")\n",
        "\n",
        "def find_first_example_with_boxes(dataset: \"datasets.Dataset\") -> dict:\n",
        "    \"\"\"Finds the first example in the dataset that contains bounding boxes.\"\"\"\n",
        "    print(\"Searching for first example with bounding boxes...\")\n",
        "    for ex in tqdm(dataset, desc=\"Finding example with boxes\", unit=\"ex\"):\n",
        "        if has_boxes(ex):\n",
        "            return ex\n",
        "\n",
        "    print(\"Warning: No example with bounding boxes found. Displaying index 0 instead.\")\n",
        "    return dataset[0]"
      ],
      "metadata": {
        "id": "5u2Ezk2YFh3o"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Execute the loading\n",
        "ds = load_and_prepare_dataset(PARQUET_FILE_URL)\n",
        "\n",
        "if ds is None:\n",
        "    raise RuntimeError(\"Dataset loading failed. Cannot proceed with demo.\")\n",
        "\n",
        "# --- STEP 2: CACHE ALL IMAGES ---\n",
        "cache_all_images(ds, DATASET_ID)"
      ],
      "metadata": {
        "id": "hPB6_pzXIBup"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def display_nova_example(dataset: \"datasets.Dataset\", selector: str | int = None):\n",
        "    # --- Selection Logic (Unchanged) ---\n",
        "    example = None\n",
        "    try:\n",
        "        if isinstance(selector, int):\n",
        "            if 0 <= selector < len(dataset):\n",
        "                example = dataset[selector]\n",
        "            else:\n",
        "                raise IndexError(f\"Index {selector} out of bounds for dataset of size {len(dataset)}.\")\n",
        "        elif isinstance(selector, str):\n",
        "            example = get_example_by_filename(dataset, selector)\n",
        "        elif selector is None:\n",
        "            example = find_first_example_with_boxes(dataset)\n",
        "        else:\n",
        "            raise TypeError(f\"Selector must be an integer index or a string filename, got {type(selector)}.\")\n",
        "\n",
        "        if example is None: return\n",
        "\n",
        "        filename = example.get('filename', 'N/A')\n",
        "        total_boxes = len(example.get('bboxes', []))\n",
        "        print(f\"\\n--- Displaying File: {filename} | Total Boxes: {total_boxes} ---\")\n",
        "\n",
        "    except (ValueError, IndexError, TypeError) as e:\n",
        "        print(f\"Error selecting example: {e}\")\n",
        "        return\n",
        "\n",
        "    # --- IMAGE LOADING (FAST, LOCAL) ---\n",
        "    try:\n",
        "        # Load the image using its filename from the local folder\n",
        "        img = load_local_image(filename)\n",
        "\n",
        "    except Exception as e:\n",
        "        print(f\"\\n🛑 Fatal Error: Image for file {filename} could not be loaded from local path. Error: {e}\")\n",
        "        return\n",
        "\n",
        "    # --- Visualization Setup (Plotting - Unchanged) ---\n",
        "    fig, (ax_img, ax_meta) = plt.subplots(1, 2, figsize=(14, 7), gridspec_kw={'width_ratios': [1, 1]})\n",
        "\n",
        "    # Left Subplot: Image and Bounding Boxes\n",
        "    ax_img.imshow(img)\n",
        "    bboxes = example.get(\"bboxes\", [])\n",
        "\n",
        "    img_title = f\"Image: {filename} ({total_boxes} Boxes)\"\n",
        "    ax_img.set_title(img_title, fontsize=TITLE_FONT_SIZE, fontweight='bold')\n",
        "\n",
        "    # Draw Bounding Boxes\n",
        "    for i, b in enumerate(bboxes[:MAX_BOXES_TO_DRAW]):\n",
        "        x, y, w, h = b[\"x\"], b[\"y\"], b[\"width\"], b[\"height\"]\n",
        "        source = b.get(\"source\", \"N/A\")\n",
        "\n",
        "        rect = patches.Rectangle((x, y), w, h,\n",
        "                                 linewidth=2,\n",
        "                                 edgecolor=BOX_COLOR,\n",
        "                                 linestyle='-',\n",
        "                                 fill=False)\n",
        "        ax_img.add_patch(rect)\n",
        "\n",
        "        ax_img.text(x, y - 5, f\"Source: {source}\",\n",
        "                fontsize=8,\n",
        "                color=TEXT_COLOR,\n",
        "                bbox=dict(facecolor=BOX_LABEL_BG_COLOR, alpha=0.8, edgecolor='none', pad=2))\n",
        "\n",
        "    ax_img.axis(\"off\")\n",
        "\n",
        "    # Right Subplot: Structured Metadata\n",
        "    ax_meta.set_axis_off()\n",
        "    ax_meta.set_xlim(0, 1)\n",
        "    ax_meta.set_ylim(0, 1)\n",
        "\n",
        "    y_pos = 0.95\n",
        "    x_pos = 0.05\n",
        "    line_height = 0.08\n",
        "\n",
        "    ax_meta.text(x_pos, y_pos, \"Metadata Details\", fontsize=METADATA_SECTION_TITLE_SIZE + 2,\n",
        "                 fontweight='bold', transform=ax_meta.transAxes)\n",
        "    y_pos -= line_height * 1.5\n",
        "\n",
        "    # Caption\n",
        "    caption = example.get(\"caption_text\", \"N/A (No caption available)\")\n",
        "    ax_meta.text(x_pos, y_pos, \"Caption:\", fontsize=METADATA_SECTION_TITLE_SIZE,\n",
        "                 fontweight='bold', transform=ax_meta.transAxes)\n",
        "    y_pos -= line_height\n",
        "\n",
        "    wrapped_caption = \"\\n\".join([caption[i:i+60] for i in range(0, len(caption), 60)])\n",
        "    ax_meta.text(x_pos, y_pos, wrapped_caption, fontsize=METADATA_TEXT_SIZE, transform=ax_meta.transAxes,\n",
        "                 verticalalignment='top')\n",
        "    y_pos -= line_height * (wrapped_caption.count('\\n') + 2)\n",
        "\n",
        "    # Clinical and Publication Details\n",
        "    meta = example.get(\"meta\", {})\n",
        "    ax_meta.text(x_pos, y_pos, \"Clinical & Publication:\", fontsize=METADATA_SECTION_TITLE_SIZE,\n",
        "                 fontweight='bold', transform=ax_meta.transAxes)\n",
        "    y_pos -= line_height\n",
        "\n",
        "    details = [\n",
        "        (\"Final Diagnosis:\", meta.get('final_diagnosis', 'N/A')),\n",
        "        (\"Title:\", meta.get('title', 'N/A')),\n",
        "        (\"Publication Date:\", meta.get('publication_date', 'N/A')),\n",
        "        (\"Link:\", meta.get('link', 'N/A'))\n",
        "    ]\n",
        "\n",
        "    for label, value in details:\n",
        "        ax_meta.text(x_pos, y_pos, f\"{label:<18} {value}\", fontsize=METADATA_TEXT_SIZE, transform=ax_meta.transAxes)\n",
        "        y_pos -= line_height\n",
        "\n",
        "    plt.tight_layout()\n",
        "    plt.show()"
      ],
      "metadata": {
        "id": "-QzYNu9dFtG9"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# --- Demo Examples (Instant after initial caching) ---\n",
        "\n",
        "# 1. Default Example: Find the first entry that has bounding boxes\n",
        "print(\"--- DEMO 1: Displaying first example with boxes ---\")\n",
        "display_nova_example(ds)\n",
        "\n",
        "# 2. Select by Integer Index\n",
        "print(\"\\n--- DEMO 2: Select by Index (95) ---\")\n",
        "display_nova_example(ds, selector=543)\n",
        "\n",
        "# 3. Select by String Filename\n",
        "print(\"\\n--- DEMO 3: Select by Filename (Logical ID) ---\")\n",
        "display_nova_example(ds, selector=ds[0]['filename'])"
      ],
      "metadata": {
        "id": "6O1rffbKwOxV"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n"
      ],
      "metadata": {
        "id": "zZ8r9w7YFa6Y"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "mPsz_1vZLIFM"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}