File size: 11,825 Bytes
10de3c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# helper_utilities.ipynb\n",
    "> Helper functions for when we need to work with files in Google Colab or locally\n",
    "\n",
    "In this notebook, we write some generic code to help us interface more easily with loading in files."
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "skip_exec: true\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp IOHelperUtilities"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "import ipywidgets as widgets\n",
    "from IPython.display import display, clear_output\n",
    "from functools import partial\n",
    "from ipyfilechooser import FileChooser\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def check_is_colab():\n",
    "    \"\"\"\n",
    "    Check if the current environment is Google Colab.\n",
    "    \"\"\"\n",
    "    try:\n",
    "        import google.colab\n",
    "        return True\n",
    "    except:\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert not check_is_colab(), 'On this system, we should not be in Colab'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## File Choosers\n",
    "Jupyter notebooks, the different IDEs, and ipywidgets currently (as of August 8, 2023) are not playing nice together, and also are misaligned in terms of versions. What works in Jupyter Lab at version 8 somehow doesn't work in Google Colab and changes are needed. Neither the Google Colab version or the Jupyter Lab version work with VSCode.\n",
    "\n",
    "While this is being worked out between VS Code developers and ipywidgets, we've found a mid-term solutions which requires another package. We implement and test this below (thanks, Code Interpreter!)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class MultiFileChooser:\n",
    "    def __init__(self):\n",
    "        self.fc = FileChooser('.')\n",
    "        self.fc.title = \"Use the following file chooser to add each file individually.\\n You can remove files by clicking the remove button.\"\n",
    "        self.fc.use_dir_icons = True\n",
    "        self.fc.show_only_dirs = False\n",
    "        self.selected_files = []\n",
    "        \n",
    "        self.fc.register_callback(self.file_selected)\n",
    "        \n",
    "        self.output = widgets.Output()\n",
    "        \n",
    "    def file_selected(self, chooser):\n",
    "        if self.fc.selected is not None and self.fc.selected not in self.selected_files:\n",
    "            self.selected_files.append(self.fc.selected)\n",
    "            self.update_display()\n",
    "    \n",
    "    def update_display(self):\n",
    "        with self.output:\n",
    "            clear_output()\n",
    "            for this_file in self.selected_files:\n",
    "                remove_button = widgets.Button(description=\"Remove\", tooltip=\"Remove this file\")\n",
    "                remove_button.on_click(partial(self.remove_file, file=this_file))\n",
    "                display(widgets.HBox([widgets.Label(value=this_file), remove_button]))\n",
    "    \n",
    "    def remove_file(self, button, this_file):\n",
    "        if this_file in self.selected_files:\n",
    "            self.selected_files.remove(this_file)\n",
    "            self.update_display()\n",
    "    \n",
    "    def display(self):\n",
    "        display(self.fc, self.output)\n",
    "    \n",
    "    def get_selected_files(self):\n",
    "        return self.selected_files"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we test the file chooser very briefly to ensure that the results are as we desire."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "07ff01c3633c4addb72bfe758fb9c4e4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "FileChooser(path='/workspaces/lo-achievement/nbs', filename='', title='Use the following file chooser to add e…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1aa36e43d7254a2f8669a92e156b726c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Output()"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Create file chooser and interact\n",
    "mfc = MultiFileChooser()\n",
    "mfc.display()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['/workspaces/lo-achievement/nbs/_quarto.yml',\n",
       " '/workspaces/lo-achievement/nbs/nbdev.yml']"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# get files that were selected.\n",
    "mfc.get_selected_files()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## File loading\n",
    "Now, we implement a file chooser that will work across platforms, whether it be Google Colab or local environments."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def setup_drives(upload_set):\n",
    "\n",
    "    upload_set = upload_set.lower()\n",
    "    uploaded = None\n",
    "\n",
    "    # allow them to mount the drive if they chose Google Colab.\n",
    "    if upload_set == 'google drive':\n",
    "        if check_is_colab():\n",
    "            from google.colab import drive\n",
    "            drive.mount('/content/drive')\n",
    "        else:\n",
    "            raise ValueError(\"It looks like you're not on Google Colab. Google Drive mounting is currently only implemented for Google Colab.\")\n",
    "\n",
    "    # Everything else means that they'll need to use a file chooser (including Google Drive)\n",
    "    if check_is_colab():\n",
    "        from google.colab import files\n",
    "        uploaded = files.upload()\n",
    "    else:\n",
    "        # Create file chooser and interact\n",
    "        mfc = MultiFileChooser()\n",
    "        mfc.display()\n",
    "        uploaded = mfc.get_selected_files()\n",
    "    \n",
    "    return uploaded"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c88d8353fb0d4dc6a2df946ea2082e5f",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "FileChooser(path='/workspaces/lo-achievement/nbs', filename='', title='Use the following file chooser to add e…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9b8ed072582b4e87ace35d2d59c3a82f",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Output()"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "res = setup_drives('local drive')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['/workspaces/lo-achievement/nbs/_quarto.yml',\n",
       " '/workspaces/lo-achievement/nbs/nbdev.yml']"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we'll verify the behavior of Google Drive. We'll wrap this in a try/except block so the code can run all the way through."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "An exception of type ValueError occurred. Arguments:\n",
      "It looks like you're not on Google Colab. Google Drive mounting is currently only implemented for Google Colab.\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    setup_drives('google drive')\n",
    "except Exception as e:\n",
    "    print(f\"An exception of type {type(e).__name__} occurred. Arguments:\\n{e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Future expected implementation\n",
    "\n",
    "The following code is included as it works, just not in Visual Studio code. The current implementation of the File chooser is a bit inelegant, but this is due to the current limitations of the combination of the libraries and platforms. Once some errors with VS code can be updated, this code will be the preferable solution as it is more familiar to users."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ipywidgets as widgets\n",
    "from IPython.display import display\n",
    "\n",
    "class UniversalFileUpload:\n",
    "\n",
    "    def __init__(self):\n",
    "        self.filelist = []\n",
    "        self.uploader = None\n",
    "        self.status_output = None\n",
    "    \n",
    "    def _process_upload(self, change):\n",
    "        self.status_output.clear_output()\n",
    "        with self.status_output:\n",
    "            print('What is happening?')\n",
    "            print(change)\n",
    "\n",
    "    def process_uploads(self, change):\n",
    "        if change['new'] and change['new'] != None:\n",
    "          with self.status_output:\n",
    "              print(change)\n",
    "          \n",
    "          self.filelist = change['new']\n",
    "          \n",
    "          #get filenames and promt\n",
    "          fnames = [fileinfo['name'] for fileinfo in self.filelist['metadata']]\n",
    "          with self.status_output:\n",
    "              print('Uploaded files:', fnames)\n",
    "          \n",
    "          #clear it so it doesn't save state\n",
    "          self.uploader.close()\n",
    "    \n",
    "    def get_upload_value(self):\n",
    "        return self.filelist\n",
    "    \n",
    "    def choose_files(self):\n",
    "        self.uploader = widgets.FileUpload(accept='', multiple=True, description='cat')\n",
    "        self.status_output = widgets.Output()\n",
    "        self.file_output_box = widgets.VBox([self.uploader, self.status_output])\n",
    "        self.uploader.observe(self._process_upload)\n",
    "\n",
    "        with self.status_output:\n",
    "            print('Waiting...')\n",
    "\n",
    "        return self.file_output_box"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#test\n",
    "ul = UniversalFileUpload()\n",
    "ul.choose_files()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}