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