├── .dockerignore ├── .gitattribute ├── .gitignore ├── CONTRIBUTING.md ├── Configure.png ├── Dockerfile ├── ExtensionIcon.png ├── KaggleJupyterLab.png ├── LICENSE ├── README.md ├── Work.png ├── docker └── usr │ └── local │ └── bin │ └── start-notebook.d │ └── install-labextension.sh ├── package.json ├── prettierrc.js ├── schema └── kaggle.json ├── src ├── index.ts ├── kaggle │ └── index.ts ├── service.ts ├── widget.ts └── widgets │ ├── apiSettings.tsx │ ├── controlls.tsx │ └── datasetPicker.tsx ├── style ├── index.css └── kaggle.svg ├── tsconfig.json └── yarn.lock /.dockerignore: -------------------------------------------------------------------------------- 1 | .git/ 2 | 3 | .dockerignore 4 | .gitignore 5 | 6 | # editor 7 | **/.vscode/ 8 | **/.idea/ 9 | 10 | **/npm_packages/ 11 | **/node_modules/ 12 | **/test/build/* 13 | **/package-lock.json 14 | 15 | # misc 16 | .DS_Store 17 | 18 | *.bundle.* 19 | *.tsbuildinfo 20 | *.log* 21 | -------------------------------------------------------------------------------- /.gitattribute: -------------------------------------------------------------------------------- 1 | * text eol=lf 2 | 3 | # these files needs to have linux style line ending 4 | *.sh text eol=lf 5 | *.py text eol=lf 6 | *.json text eol=lf 7 | Dockerfile text eol=lf 8 | LICENSE text eol=lf 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # npm 2 | **/lib/ 3 | **/npm_packages/ 4 | **/node_modules/ 5 | **/test/build/* 6 | **/package-lock.json 7 | 8 | # editor 9 | **/.vscode/ 10 | **/.idea/ 11 | 12 | # misc 13 | .DS_Store 14 | 15 | *.bundle.* 16 | *.tsbuildinfo 17 | *.log* 18 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution; 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows [Google's Open Source Community 28 | Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /Configure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kaggle/jupyterlab/d891d14456af0dc3cfbe87c12fd53653da8aa455/Configure.png -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM jupyter/minimal-notebook:1386e2046833 AS base 2 | 3 | LABEL author="Kaggle " 4 | LABEL maintainer="Kaggle " 5 | 6 | # do stuff here 7 | ENV JUPYTER_ENABLE_LAB=yes 8 | 9 | CMD ["start-notebook.sh", "--watch"] 10 | 11 | USER root 12 | 13 | COPY docker/usr/local/bin/start-notebook.d /usr/local/bin/start-notebook.d 14 | RUN fix-permissions /usr/local/bin/start-notebook.d/ 15 | 16 | USER $NB_UID 17 | WORKDIR $HOME 18 | -------------------------------------------------------------------------------- /ExtensionIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kaggle/jupyterlab/d891d14456af0dc3cfbe87c12fd53653da8aa455/ExtensionIcon.png -------------------------------------------------------------------------------- /KaggleJupyterLab.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kaggle/jupyterlab/d891d14456af0dc3cfbe87c12fd53653da8aa455/KaggleJupyterLab.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WARNING: This extension as been deprecated and is unmaintained. 2 | 3 | # @kaggle/jupyterlab 4 | 5 | Official Kaggle extension for JupyterLab. 6 | 7 | ## Requirements 8 | 9 | * JupyterLab >= 1.1.0 10 | * A Kaggle account for accessing Kaggle API 11 | 12 | To run this extension, you will need to download a Kaggle API token. You can 13 | find the token on your [Kaggle account page](https://www.kaggle.com/me/account). 14 | 15 | Once you download the token to your local machine, you can drag & drop the 16 | token onto the settings page of the Kaggle extension for JupyterLab. 17 | 18 | ## Overview 19 | 20 | Kaggle extension for JupyterLab enables you to browse and download Kaggle 21 | Datasets for use in your JupyterLab instance. 22 | 23 | ![Kaggle](KaggleJupyterLab.png 'Kaggle') 24 | 25 | ## Getting started 26 | 27 | ### Install 28 | 29 | Run the following command on your JupyterLab system to install the extension. 30 | 31 | ```bash 32 | jupyter labextension install @kaggle/jupyterlab 33 | ``` 34 | 35 | Next time you start JupyterLab, you should see a shiny new Kaggle icon on the left panel. 36 | 37 | ![SideIcon](ExtensionIcon.png 'Icon') 38 | 39 | ### Configure 40 | 41 | To use the extension, you’ll need to download your Kaggle API token from your account page. You can import the token into the extension by dragging & dropping the downloaded file into the dotted area, or you can click on the input box to bring up the file browser (1). Once you’ve imported the file, be sure to save your changes (2). 42 | 43 | ![Configure](Configure.png 'Configure') 44 | 45 | Once you save the changes, it will automatically take you to the dataset list panel, but you can always click on the settings icon to update the token. 46 | 47 | ### Work 48 | 49 | 1. On the dataset listing page, you can enter a search term in the input box to filter the results. 50 | 2. Once you find the dataset you’re interested in, click the download icon to download the dataset to your system. 51 | 52 | 53 | ![Work](Work.png 'Work') 54 | 55 | ## Contributing 56 | 57 | We'd love to accept your patches and contributions to this project. See 58 | [CONTRIBUTING.md](CONTRIBUTING.md) for more information. 59 | 60 | ### Development 61 | 62 | Here are some quick instructions to get you started experimenting with 63 | this extension locally. 64 | 65 | #### Requirements 66 | 67 | * JupyterLab >= 1.1.0 68 | * A Kaggle account for accessing Kaggle API 69 | * [Yarn](https://yarnpkg.com) 70 | * [Docker](https://www.docker.com) 71 | 72 | #### Build & Run 73 | 74 | ```bash 75 | # Clone the repo to your local environment 76 | # Move to jupyterlab directory 77 | 78 | # Install dependencies 79 | > yarn 80 | 81 | # Build All 82 | > yarn build:all 83 | 84 | # Start the docker running JupyterLab with @kaggle/jupyterlab extension 85 | # Look for the url to access the JupyterLab instance in the console output 86 | # once the service finishes starting up 87 | > yarn docker 88 | 89 | # If you are working on Windows, run this command instead 90 | > yarn docker:win 91 | ``` 92 | 93 | You can modify the Typescript files while docker is running and rebuild 94 | the extension to see the changes in JupyterLab. This requires a refresh of 95 | your browser after the extension has been rebuilt. 96 | 97 | ```bash 98 | # Rebuild Typescript source after making changes 99 | > yarn build 100 | ``` 101 | 102 | 103 | -------------------------------------------------------------------------------- /Work.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kaggle/jupyterlab/d891d14456af0dc3cfbe87c12fd53653da8aa455/Work.png -------------------------------------------------------------------------------- /docker/usr/local/bin/start-notebook.d/install-labextension.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | jupyter labextension install /github.com/kaggle/jupyterlab/ --log-level='DEBUG' 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@kaggle/jupyterlab", 3 | "version": "1.0.1", 4 | "description": "Official Kaggle extension for JupyterLab.", 5 | "keywords": [ 6 | "kaggle", 7 | "jupyter", 8 | "jupyterlab", 9 | "jupyterlab-extension" 10 | ], 11 | "homepage": "https://github.com/kaggle/jupyterlab", 12 | "bugs": { 13 | "url": "https://github.com/kaggle/jupyterlab/issues" 14 | }, 15 | "license": "Apache-2.0", 16 | "author": { 17 | "name": "Kaggle", 18 | "email": "support@kaggle.com" 19 | }, 20 | "files": [ 21 | "lib/*/*.d.ts", 22 | "lib/*/*.js", 23 | "lib/*.d.ts", 24 | "lib/*.js", 25 | "schema/*.json", 26 | "style/*.*" 27 | ], 28 | "main": "lib/index.js", 29 | "types": "lib/index.d.ts", 30 | "style": "style/index.css", 31 | "directories": { 32 | "lib": "lib/" 33 | }, 34 | "repository": { 35 | "type": "git", 36 | "url": "https://github.com/kaggle/jupyterlab.git" 37 | }, 38 | "scripts": { 39 | "build": "yarn build:tsc", 40 | "build:all": "yarn build:tsc && yarn build:docker", 41 | "build:docker": "docker build -t kaggle/jupyterlab-dev:head -f Dockerfile .", 42 | "build:tsc": "prettier --config prettierrc.js --write src/**/*{.ts,.tsx} && tsc", 43 | "clean": "rimraf lib && rimraf tsconfig.tsbuildinfo", 44 | "docker": "docker run -it --rm -p 127.0.0.1:8888:8888 --name kaggle-jupyterlab-dev --mount type=bind,src=$(pwd),dst=/github.com/kaggle/jupyterlab kaggle/jupyterlab-dev:head", 45 | "docker:win": "docker run -it --rm -p 127.0.0.1:8888:8888 --name kaggle-jupyterlab-dev --mount type=bind,src=%CD%,dst=/github.com/kaggle/jupyterlab kaggle/jupyterlab-dev:head", 46 | "postinstall": "echo install server extension", 47 | "test": "echo placeholder" 48 | }, 49 | "dependencies": { 50 | "@fortawesome/fontawesome-svg-core": "^1.2.21", 51 | "@fortawesome/free-solid-svg-icons": "^5.10.1", 52 | "@fortawesome/react-fontawesome": "^0.1.4", 53 | "@jupyterlab/application": "^1.1.0", 54 | "@jupyterlab/apputils": "^1.1.0", 55 | "@jupyterlab/coreutils": "^3.1.0", 56 | "@jupyterlab/docmanager": "^1.1.0", 57 | "@jupyterlab/notebook": "^1.1.0", 58 | "@jupyterlab/services": "^4.1.0", 59 | "@phosphor/coreutils": "^1.3.1", 60 | "@phosphor/widgets": "^1.9.0", 61 | "filesize": "^4.1.2", 62 | "moment": "^2.24.0", 63 | "react": "16.8.6", 64 | "react-dom": "16.8.6", 65 | "react-dropzone": "^10.1.8", 66 | "styled-components": "^4.3.2" 67 | }, 68 | "devDependencies": { 69 | "@types/filesize": "^4.1.0", 70 | "@types/jest": "^24.0.18", 71 | "@types/styled-components": "4.1.0", 72 | "jest": "^24.9.0", 73 | "prettier": "1.18.2", 74 | "rimraf": "^3.0.0", 75 | "typescript": "~3.6.2" 76 | }, 77 | "resolutions": { 78 | "@types/react": "16.8.25" 79 | }, 80 | "jupyterlab": { 81 | "extension": true, 82 | "schemaDir": "schema" 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | printWidth: 80, 3 | parser: "typescript", 4 | tabWidth: 2, 5 | trailingComma: "es5", 6 | }; 7 | -------------------------------------------------------------------------------- /schema/kaggle.json: -------------------------------------------------------------------------------- 1 | { 2 | "jupyter.lab.setting-icon-class": "jp-Kaggle-icon", 3 | "jupyter.lab.setting-icon-label": "Kaggle", 4 | "title": "Kaggle", 5 | "description": "Settings for the Kaggle plugin.", 6 | "definitions": { 7 | "datasetSearch": { 8 | "properties": { 9 | "page": { 10 | "type": "number" 11 | }, 12 | "search": { 13 | "type": "string" 14 | }, 15 | "group": { 16 | "type": "string" 17 | }, 18 | "sortBy": { 19 | "type": "string" 20 | }, 21 | "filetype": { 22 | "type": "string" 23 | }, 24 | "license": { 25 | "type": "string" 26 | } 27 | }, 28 | "type": "object", 29 | "additionalProperties": false 30 | } 31 | }, 32 | "properties": { 33 | "datasetSearch": { 34 | "$ref": "#/definitions/datasetSearch", 35 | "title": "Dataset Search parameters", 36 | "description": "Current dataset search filters", 37 | "default": { 38 | "page": 1, 39 | "search": "", 40 | "group": "", 41 | "sortBy": "", 42 | "filetype": "", 43 | "license": "" 44 | } 45 | } 46 | }, 47 | "additionalProperties": false, 48 | "type": "object" 49 | } 50 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Kaggle Inc 2 | // 3 | // Licensed under the Apache License, Version 2.0(the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import { 16 | ILayoutRestorer, 17 | JupyterFrontEnd, 18 | JupyterFrontEndPlugin, 19 | } from "@jupyterlab/application"; 20 | 21 | import { IStateDB } from "@jupyterlab/coreutils"; 22 | import { IDocumentManager } from "@jupyterlab/docmanager"; 23 | import { KaggleWidget } from "./widget"; 24 | import { KaggleService } from "./service"; 25 | 26 | /** 27 | * The plugin registration information. 28 | */ 29 | const kaggleDatasetPlugin: JupyterFrontEndPlugin = { 30 | id: KaggleService.PLUGIN_ID, 31 | activate, 32 | autoStart: true, 33 | requires: [IDocumentManager, ILayoutRestorer, IStateDB], 34 | }; 35 | 36 | /** 37 | * Activate the extension. 38 | */ 39 | function activate( 40 | app: JupyterFrontEnd, 41 | manager: IDocumentManager, 42 | restorer: ILayoutRestorer, 43 | stateDB: IStateDB 44 | ): void { 45 | const kaggleService: KaggleService = new KaggleService(app, manager, stateDB); 46 | const kaggleWidget: KaggleWidget = new KaggleWidget(kaggleService); 47 | 48 | restorer.add(kaggleWidget, KaggleService.NAMESPACE); 49 | app.shell.add(kaggleWidget, "left", { rank: 1001 }); 50 | } 51 | 52 | /** 53 | * Export the plugin as default. 54 | */ 55 | export default kaggleDatasetPlugin; 56 | -------------------------------------------------------------------------------- /src/kaggle/index.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Kaggle Inc 2 | // 3 | // Licensed under the Apache License, Version 2.0(the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | export interface ApiToken { 16 | username: string; 17 | token: string; 18 | } 19 | 20 | interface DatasetFilesResult { 21 | message: string; 22 | datasetFiles: DatasetFile[]; 23 | } 24 | 25 | export enum SortBy { 26 | "hottest", 27 | "votes", 28 | "updated", 29 | "active", 30 | } 31 | 32 | export enum DatasetGroup { 33 | "public", 34 | "my", 35 | "myPrivate", 36 | "updated", 37 | } 38 | 39 | export enum FileType { 40 | "all", 41 | "csv", 42 | "sqlite", 43 | "json", 44 | "bigQuery", 45 | } 46 | 47 | export enum License { 48 | "all", 49 | "cc", 50 | "gpl", 51 | "odb", 52 | "other", 53 | } 54 | 55 | interface Content { 56 | ref: string; 57 | } 58 | 59 | export interface Tag extends Content { 60 | competitionCount: number; 61 | datasetCount: number; 62 | description: string; 63 | fullPath: string; 64 | name: string; 65 | scriptCount: number; 66 | totalCount: number; 67 | } 68 | 69 | export interface DatasetItem extends Content { 70 | creatorName: string; 71 | creatorUrl: string; 72 | currentVersionNumber: number; 73 | description: string; 74 | downloadCount: number; 75 | isFeatured: boolean; 76 | isPrivate: boolean; 77 | isReviewed: boolean; 78 | kernelCount: number; 79 | lastUpdated: Date; 80 | licenseName: string; 81 | ownerName: string; 82 | ownerRef: string; 83 | subtitle: string; 84 | tags: Tag[]; 85 | title: string; 86 | topicCount: number; 87 | totalBytes: number; 88 | url: string; 89 | usabilityRating: number; 90 | viewCount: number; 91 | voteCount: number; 92 | } 93 | 94 | export interface DatasetFile extends Content { 95 | fileType: string; 96 | name: string; 97 | totalBytes: number; 98 | } 99 | 100 | export class KaggleApi { 101 | static KAGGLE_API_URL = "https://www.kaggle.com/api/v1/"; 102 | 103 | private _token: ApiToken; 104 | 105 | constructor(token: ApiToken) { 106 | this._token = token; 107 | } 108 | 109 | private getHeaders() { 110 | let headers = new Headers({ 111 | Authorization: 112 | "Basic " + btoa(this._token.username + ":" + this._token.token), 113 | "X-User-Agent": "@kaggle/jupyterlab", 114 | }); 115 | return headers; 116 | } 117 | 118 | async hello() { 119 | const url = new URL("hello", KaggleApi.KAGGLE_API_URL); 120 | 121 | try { 122 | let response = await fetch(url.href, { 123 | method: "get", 124 | mode: "cors", 125 | headers: this.getHeaders(), 126 | }); 127 | if (response.status < 300) { 128 | return true; 129 | } 130 | 131 | return false; 132 | } catch (e) { 133 | console.warn(e); 134 | return false; 135 | } 136 | } 137 | 138 | async listDatasets( 139 | page?: number, 140 | search?: string, 141 | group?: DatasetGroup, 142 | sortBy?: SortBy, 143 | filetype?: FileType, 144 | license?: License 145 | ) { 146 | const url = new URL("datasets/list", KaggleApi.KAGGLE_API_URL); 147 | if (search) { 148 | url.searchParams.append("search", search); 149 | } 150 | 151 | if (page) { 152 | if (page < 1) { 153 | page = 1; 154 | } 155 | url.searchParams.append("page", page.toFixed(0)); 156 | } 157 | 158 | if (group) { 159 | url.searchParams.append("group", group.toString()); 160 | } 161 | 162 | if (sortBy) { 163 | url.searchParams.append("sortBy", sortBy.toString()); 164 | } 165 | 166 | if (filetype) { 167 | url.searchParams.append("filetype", filetype.toString()); 168 | } 169 | 170 | if (license) { 171 | url.searchParams.append("license", license.toString()); 172 | } 173 | 174 | try { 175 | const response = await fetch(url.href, { 176 | method: "get", 177 | mode: "cors", 178 | headers: this.getHeaders(), 179 | }); 180 | const data = await response.json(); 181 | return data as DatasetItem[]; 182 | } catch (e) { 183 | console.warn(e); 184 | return [] as DatasetItem[]; 185 | } 186 | } 187 | 188 | async listDatasetFiles(dataset: DatasetItem) { 189 | const url = new URL( 190 | dataset.ref, 191 | KaggleApi.KAGGLE_API_URL + "datasets/list/" 192 | ); 193 | 194 | try { 195 | const response = await fetch(url.href, { 196 | method: "get", 197 | mode: "cors", 198 | headers: this.getHeaders(), 199 | }); 200 | const data = (await response.json()) as DatasetFilesResult; 201 | return data.datasetFiles; 202 | } catch (e) { 203 | console.warn(e); 204 | return [] as DatasetFile[]; 205 | } 206 | } 207 | 208 | async downloadDataset(dataset: DatasetItem) { 209 | const url = new URL( 210 | dataset.ref, 211 | KaggleApi.KAGGLE_API_URL + "datasets/download/" 212 | ); 213 | url.searchParams.append("noRedirect", "true"); 214 | 215 | const response = await fetch(url.href, { 216 | method: "get", 217 | mode: "cors", 218 | headers: this.getHeaders(), 219 | }); 220 | 221 | const json = await response.json(); 222 | const download = await fetch(json, { 223 | method: "get", 224 | mode: "cors", 225 | }); 226 | 227 | return download.body; 228 | } 229 | 230 | async downloadDatasetFile(dataset: DatasetItem, file: DatasetFile) { 231 | let downloadUrl = "datasets/download-raw/"; 232 | let fileUrl = file.ref; 233 | if (file.fileType == ".zip") { 234 | downloadUrl = "datasets/download/"; 235 | } 236 | if (fileUrl.includes("/")) { 237 | fileUrl = fileUrl.replace(/\//g, "%2F"); 238 | downloadUrl = "datasets/download/"; 239 | } 240 | 241 | const url = new URL( 242 | dataset.ref + "/" + fileUrl, 243 | KaggleApi.KAGGLE_API_URL + downloadUrl 244 | ); 245 | url.searchParams.append("noRedirect", "true"); 246 | console.debug("downloadDatasetFile", url.href); 247 | 248 | const response = await fetch(url.href, { 249 | method: "get", 250 | mode: "cors", 251 | headers: this.getHeaders(), 252 | }); 253 | 254 | const json = await response.json(); 255 | const download = await fetch(json, { 256 | method: "get", 257 | mode: "cors", 258 | }); 259 | 260 | return download.body; 261 | } 262 | } 263 | -------------------------------------------------------------------------------- /src/service.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Kaggle Inc 2 | // 3 | // Licensed under the Apache License, Version 2.0(the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import { JupyterFrontEnd } from "@jupyterlab/application"; 16 | import { JSONObject, ReadonlyJSONValue } from "@phosphor/coreutils"; 17 | import { PathExt, PageConfig, IStateDB } from "@jupyterlab/coreutils"; 18 | import { IDocumentManager } from "@jupyterlab/docmanager"; 19 | import { Contents } from "@jupyterlab/services"; 20 | 21 | import { KaggleApi, ApiToken, DatasetItem, DatasetFile } from "./kaggle"; 22 | 23 | interface ApiTokenObject extends ApiToken, JSONObject {} 24 | 25 | export class KaggleService { 26 | static NAMESPACE = "kaggle"; 27 | static ROOT_PATH = "kaggle"; 28 | static WORK_PATH = "work"; 29 | static PLUGIN_ID = "@kaggle/jupyterlab:kaggle"; 30 | static KAGGLE_API_URL = KaggleApi.KAGGLE_API_URL; 31 | static KAGGLE_BASE_URL = "https://www.kaggle.com"; 32 | 33 | private _app: JupyterFrontEnd; 34 | private _manager: IDocumentManager; 35 | private _stateDB: IStateDB; 36 | private _drive: Contents.IManager; 37 | 38 | private _kapi: KaggleApi; 39 | private _ready: boolean; 40 | 41 | public onTokenChangeAccepted: () => void; 42 | 43 | constructor( 44 | app: JupyterFrontEnd, 45 | manager: IDocumentManager, 46 | stateDB: IStateDB 47 | ) { 48 | this._ready = false; 49 | this._app = app; 50 | this._manager = manager; 51 | this._stateDB = stateDB; 52 | 53 | this._drive = this._manager.services.contents; 54 | 55 | this.getApiToken().then(apiToken => { 56 | if ( 57 | apiToken && 58 | apiToken.username && 59 | apiToken.username != "" && 60 | apiToken.token && 61 | apiToken.username != "" 62 | ) { 63 | const kapi2 = new KaggleApi(apiToken); 64 | if (kapi2.hello()) { 65 | this._ready = true; 66 | this._kapi = kapi2; 67 | this.onTokenChangeAccepted(); 68 | } 69 | } 70 | }); 71 | } 72 | 73 | public isReady(): boolean { 74 | return this._ready; 75 | } 76 | 77 | public async getApiToken(): Promise { 78 | const apiToken = (await this._stateDB.fetch( 79 | `${KaggleService.PLUGIN_ID}:apiToken` 80 | )) as ApiTokenObject; 81 | return apiToken; 82 | } 83 | 84 | public getOwnerUrl(data: DatasetItem): string { 85 | return data && "https://www.kaggle.com/" + data.ownerRef; 86 | } 87 | 88 | public async onTokenChanged( 89 | username: string, 90 | token: string 91 | ): Promise { 92 | const apiToken = { username: username, token: token } as ApiTokenObject; 93 | const kapi2 = new KaggleApi(apiToken); 94 | 95 | if (await kapi2.hello()) { 96 | this._kapi = kapi2; 97 | await this._stateDB.save( 98 | `${KaggleService.PLUGIN_ID}:apiToken`, 99 | apiToken as ReadonlyJSONValue 100 | ); 101 | this._ready = true; 102 | this.onTokenChangeAccepted && this.onTokenChangeAccepted(); 103 | return true; 104 | } 105 | 106 | return false; 107 | } 108 | 109 | public listDatasets(page?: number, search?: string) { 110 | if (!this.isReady()) { 111 | throw new Error("KaggleApi not initialized."); 112 | } 113 | 114 | return this._kapi.listDatasets(page, search); 115 | } 116 | 117 | public async addDataset(dataset: DatasetItem): Promise { 118 | if (!this.isReady()) { 119 | throw new Error("KaggleApi not initialized."); 120 | } 121 | 122 | await this._drive 123 | .get(KaggleService.ROOT_PATH, { content: false }) 124 | .catch(async reason => { 125 | const e = reason as Error; 126 | if (e && e.message == "Invalid response: 404 Not Found") { 127 | console.log("Creating root folder for", KaggleService.ROOT_PATH); 128 | await this._drive.save(KaggleService.ROOT_PATH, { 129 | path: "", 130 | type: "directory", 131 | }); 132 | } 133 | }); 134 | 135 | const ownerPath: string = PathExt.join( 136 | KaggleService.ROOT_PATH, 137 | dataset.ownerRef 138 | ); 139 | await this._drive.get(ownerPath, { content: false }).catch(async reason => { 140 | const e = reason as Error; 141 | if (e && e.message == "Invalid response: 404 Not Found") { 142 | console.log("Creating folder for owner", dataset.ownerName); 143 | await this._drive.save(ownerPath, { path: "", type: "directory" }); 144 | } 145 | }); 146 | 147 | const datasetPath: string = PathExt.join( 148 | KaggleService.ROOT_PATH, 149 | dataset.ref 150 | ); 151 | await this._drive 152 | .get(datasetPath, { content: false }) 153 | .then(model => { 154 | throw new Error("Dataset already downloaded."); 155 | }) 156 | .catch(async reason => { 157 | const e = reason as Error; 158 | if (e && e.message == "Invalid response: 404 Not Found") { 159 | console.log("Creating folder for dataset", dataset.title); 160 | await this._drive.save(datasetPath, { path: "", type: "directory" }); 161 | } else { 162 | throw reason; 163 | } 164 | }); 165 | 166 | return await this._kapi.listDatasetFiles(dataset); 167 | } 168 | 169 | public async downloadFile( 170 | dataset: DatasetItem, 171 | file: DatasetFile 172 | ): Promise { 173 | console.debug("downloadFile", file.ref); 174 | await this.ensureFolder(dataset.ref, file.ref); 175 | const datasetPath: string = PathExt.join( 176 | KaggleService.ROOT_PATH, 177 | dataset.ref 178 | ); 179 | 180 | await this._kapi 181 | .downloadDatasetFile(dataset, file) 182 | .then(async stream => { 183 | const reader = stream.getReader(); 184 | const filePath: string = PathExt.join(datasetPath, file.ref); 185 | let chunk = 1; 186 | while (true) { 187 | const result = await reader.read(); 188 | if (result.done) { 189 | break; 190 | } 191 | this._drive.save(filePath, { 192 | name: file.ref, 193 | path: filePath, 194 | type: "file", 195 | format: "base64", 196 | content: this.bytesToBase64(result.value), 197 | writable: false, 198 | chunk: chunk++, 199 | } as Contents.IModel); 200 | } 201 | }) 202 | .catch(async reason => { 203 | console.warn("error", reason); 204 | }); 205 | } 206 | 207 | public async createNotebook(dataset: DatasetItem): Promise { 208 | await this._drive 209 | .get(KaggleService.WORK_PATH, { content: false }) 210 | .catch(async reason => { 211 | const e = reason as Error; 212 | if (e && e.message == "Invalid response: 404 Not Found") { 213 | console.log("Creating working folder for", KaggleService.WORK_PATH); 214 | await this._drive.save(KaggleService.WORK_PATH, { 215 | path: "", 216 | type: "directory", 217 | }); 218 | } 219 | }); 220 | 221 | const notebook = await this._manager.newUntitled({ 222 | path: KaggleService.WORK_PATH, 223 | type: "notebook", 224 | }); 225 | 226 | const kagglePath: string = 227 | "/" + 228 | PathExt.join(PageConfig.getOption("serverRoot"), KaggleService.ROOT_PATH); 229 | 230 | const datasetPath: string = 231 | "/" + 232 | PathExt.join( 233 | PageConfig.getOption("serverRoot"), 234 | KaggleService.ROOT_PATH, 235 | dataset.ref 236 | ); 237 | 238 | const notebook2 = await this._manager.services.contents.save( 239 | notebook.path, 240 | { 241 | content: { 242 | cells: [ 243 | { 244 | cell_type: "code", 245 | execution_count: null, 246 | metadata: { 247 | truested: true, 248 | }, 249 | outputs: [], 250 | source: [ 251 | "# You might want to install some useful Python packages to get started\n", 252 | "# For example, here are several helpful packages to install \n", 253 | "\n", 254 | "# From a terminal run `pip install numpy` than uncomment the next line\n", 255 | "#import numpy as np # linear algebra\n", 256 | "\n", 257 | "# From a terminal run `pip install pandas` than uncomment the next line\n", 258 | "#import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n", 259 | "\n", 260 | '# Input data files are available in the "' + 261 | kagglePath + 262 | '" directory.\n', 263 | "# For example, running this snippet (by clicking run or pressing Shift+Enter)\n", 264 | "# will list all files under the input directory\n", 265 | "\n", 266 | "import os\n", 267 | "for dirname, _, filenames in os.walk('" + 268 | datasetPath + 269 | "'):\n", 270 | " for filename in filenames:\n", 271 | " print(os.path.join(dirname, filename))\n", 272 | ], 273 | }, 274 | ], 275 | metadata: { 276 | kernelspec: { 277 | display_name: "Python 3", 278 | language: "python", 279 | name: "python3", 280 | }, 281 | language_info: { 282 | codemirror_mode: { 283 | name: "ipython", 284 | version: 3, 285 | }, 286 | file_extension: ".py", 287 | mimetype: "text/x-python", 288 | name: "python", 289 | nbconvert_exporter: "python", 290 | pygments_lexer: "ipython3", 291 | version: "3.7.3", 292 | }, 293 | }, 294 | nbformat: 4, 295 | nbformat_minor: 4, 296 | }, 297 | type: notebook.type, 298 | } 299 | ); 300 | 301 | this._manager.openOrReveal(notebook2.path); 302 | this._app.commands.execute("filebrowser:activate", { 303 | path: notebook2.path, 304 | }); 305 | this._app.commands.execute("filebrowser:go-to-path", { 306 | path: notebook2.path, 307 | }); 308 | } 309 | 310 | private async ensureFolder( 311 | basePath: string, 312 | filePath: string 313 | ): Promise { 314 | let directory = PathExt.dirname(decodeURI(filePath)); 315 | 316 | if (directory == null || directory == "") { 317 | return; 318 | } 319 | 320 | const fullPath = PathExt.join(KaggleService.ROOT_PATH, basePath, directory); 321 | 322 | await this._drive.get(fullPath, { content: false }).catch(async reason => { 323 | const e = reason as Error; 324 | if (e && e.message == "Invalid response: 404 Not Found") { 325 | await this.ensureFolder(basePath, directory); 326 | await this._drive.save(fullPath, { path: "", type: "directory" }); 327 | } 328 | }); 329 | } 330 | 331 | private bytesToBase64(bytes: Uint8Array): string { 332 | let base64 = ""; 333 | let encodings = 334 | "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 335 | 336 | let byteLength = bytes.byteLength; 337 | let byteRemainder = byteLength % 3; 338 | let mainLength = byteLength - byteRemainder; 339 | 340 | let a, b, c, d; 341 | let chunk; 342 | 343 | // Main loop deals with bytes in chunks of 3 344 | for (let i = 0; i < mainLength; i = i + 3) { 345 | // Combine the three bytes into a single integer 346 | chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; 347 | 348 | // Use bitmasks to extract 6-bit segments from the triplet 349 | a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 350 | b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 351 | c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 352 | d = chunk & 63; // 63 = 2^6 - 1 353 | 354 | // Convert the raw binary segments to the appropriate ASCII encoding 355 | base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; 356 | } 357 | 358 | // Deal with the remaining bytes and padding 359 | if (byteRemainder == 1) { 360 | chunk = bytes[mainLength]; 361 | 362 | a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 363 | 364 | // Set the 4 least significant bits to zero 365 | b = (chunk & 3) << 4; // 3 = 2^2 - 1 366 | 367 | base64 += encodings[a] + encodings[b] + "=="; 368 | } else if (byteRemainder == 2) { 369 | chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; 370 | 371 | a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 372 | b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 373 | 374 | // Set the 2 least significant bits to zero 375 | c = (chunk & 15) << 2; // 15 = 2^4 - 1 376 | 377 | base64 += encodings[a] + encodings[b] + encodings[c] + "="; 378 | } 379 | 380 | return base64; 381 | } 382 | } 383 | -------------------------------------------------------------------------------- /src/widget.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Kaggle Inc 2 | // 3 | // Licensed under the Apache License, Version 2.0(the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import { PanelLayout, Widget } from "@phosphor/widgets"; 16 | import { ToolbarButton, Toolbar } from "@jupyterlab/apputils"; 17 | import { DatasetPickerWidget } from "./widgets/datasetPicker"; 18 | import { ApiSettingsWidget } from "./widgets/apiSettings"; 19 | import { KaggleService } from "./service"; 20 | 21 | export class KaggleWidget extends Widget { 22 | private _toolbar: Toolbar; 23 | private _settingsButton: ToolbarButton; 24 | private _datasetButton: ToolbarButton; 25 | 26 | private _rootPanel: PanelLayout; 27 | private _settingsPanel: Widget; 28 | private _datasetPickerWidget: Widget; 29 | 30 | constructor(service: KaggleService) { 31 | super(); 32 | this.addClass("jp-Kaggle"); 33 | 34 | this.id = "kaggle-widget"; 35 | this.title.iconClass = "jp-Kaggle-icon jp-SideBar-tabIcon"; 36 | this.title.caption = "Import Kaggle content"; 37 | 38 | this._toolbar = new Toolbar(); 39 | 40 | this._rootPanel = new PanelLayout(); 41 | this._rootPanel.addWidget(this._toolbar); 42 | this.layout = this._rootPanel; 43 | 44 | this._datasetPickerWidget = new DatasetPickerWidget(service); 45 | this._settingsPanel = new ApiSettingsWidget(service); 46 | service.onTokenChangeAccepted = () => { 47 | this._settingsPanel.parent = null; 48 | this._rootPanel.addWidget(this._datasetPickerWidget); 49 | }; 50 | 51 | if (service.isReady()) { 52 | this._rootPanel.addWidget(this._datasetPickerWidget); 53 | } else { 54 | this._rootPanel.addWidget(this._settingsPanel); 55 | } 56 | 57 | this._settingsButton = new ToolbarButton({ 58 | onClick: () => { 59 | this._datasetPickerWidget.parent = null; 60 | this._rootPanel.addWidget(this._settingsPanel); 61 | }, 62 | iconClassName: "jp-SettingsIcon", 63 | tooltip: "Configure Kaggle extension.", 64 | }); 65 | this._toolbar.addItem("Config", this._settingsButton); 66 | 67 | this._datasetButton = new ToolbarButton({ 68 | onClick: () => { 69 | if (service.isReady()) { 70 | this._settingsPanel.parent = null; 71 | this._rootPanel.addWidget(this._datasetPickerWidget); 72 | } 73 | }, 74 | iconClassName: "jp-SearchIcon", 75 | tooltip: "Browse Kaggle Datasets.", 76 | }); 77 | this._toolbar.addItem("Dataset", this._datasetButton); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/widgets/apiSettings.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Kaggle Inc 2 | // 3 | // Licensed under the Apache License, Version 2.0(the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // DO NOT RENAME THIS FILE TO settings.tsx THINGS WILL BREAK 16 | import React from "react"; 17 | import styled from "styled-components"; 18 | import ReactDropzone, { DropzoneRef, DropEvent } from "react-dropzone"; 19 | import { ReactWidget } from "@jupyterlab/apputils"; 20 | import { KaggleService } from "../service"; 21 | import { 22 | BaseInput, 23 | BaseButton, 24 | BaseLabel, 25 | WidgetWrapper, 26 | BaseWrapper, 27 | BaseLink, 28 | Icon, 29 | } from "./controlls"; 30 | 31 | const SectionHeading = styled.h3` 32 | color: var(--jp-content-font-color1); 33 | `; 34 | 35 | const ErrorMessage = styled(BaseLabel)` 36 | color: var(--jp-error-color1); 37 | padding: 2px 4px; 38 | `; 39 | 40 | const HelpText = styled(BaseLabel)` 41 | margin: 4px 0px; 42 | `; 43 | 44 | const KaggleLink = styled(BaseLink)``; 45 | 46 | const TokenLabel = styled(BaseLabel)` 47 | font-weight: var(--jp-content-heading-font-weight); 48 | padding: 2px 4px; 49 | `; 50 | 51 | const Username = styled(BaseInput)` 52 | color: var(--jp-content-font-color3); 53 | margin: 2px; 54 | padding: 0px 2px; 55 | width: calc(100% - 4px); 56 | ::placeholder { 57 | font-size: var(--jp-content-font-size0); 58 | } 59 | `; 60 | 61 | const SaveAction = styled(BaseButton)` 62 | margin: 4px 0px; 63 | padding: 0px 4px; 64 | :disabled { 65 | background-color: var(--jp-layout-color3); 66 | } 67 | `; 68 | 69 | const ImportInput = styled(BaseInput)` 70 | display: none; 71 | height: 0px; 72 | `; 73 | 74 | const Dropzone = styled(BaseWrapper)` 75 | border: 3px; 76 | border-color: var(--jp-accent-color1); 77 | border-style: dashed; 78 | justify-content: space-between; 79 | margin: 4px 0px; 80 | padding: 0px; 81 | height: auto; 82 | width: auto; 83 | `; 84 | 85 | interface ApiSettingsProps { 86 | service: KaggleService; 87 | } 88 | 89 | function ApiSettings(props: ApiSettingsProps) { 90 | const [username, setUsername] = React.useState(""); 91 | const [token, setToken] = React.useState(""); 92 | const [showError, setShowError] = React.useState(true); 93 | const [error, setError] = React.useState( 94 | "Start by importing your Kaggle Api token" 95 | ); 96 | 97 | props.service.getApiToken().then(apiToken => { 98 | if (apiToken && apiToken.username !== "") { 99 | setUsername(apiToken.username); 100 | setToken(apiToken.token); 101 | setError(""); 102 | setShowError(false); 103 | } 104 | }); 105 | 106 | const dropzoneRef = React.createRef(); 107 | const onTokenDrop = ( 108 | acceptedFiles: File[], 109 | rejectedFiles: File[], 110 | event: DropEvent 111 | ) => { 112 | const reader = new FileReader(); 113 | 114 | reader.onabort = () => console.log("file reading was aborted"); 115 | reader.onerror = () => console.log("file reading has failed"); 116 | reader.onload = () => { 117 | try { 118 | const token = JSON.parse(reader.result.toString()); 119 | if (!(token && token.username && token.key)) { 120 | setError("Invalid token file."); 121 | setShowError(true); 122 | return; 123 | } 124 | setError(""); 125 | setShowError(false); 126 | setUsername(token.username); 127 | setToken(token.key); 128 | } catch (e) { 129 | setError("Invalid token file."); 130 | setShowError(true); 131 | } 132 | }; 133 | 134 | acceptedFiles.forEach(file => reader.readAsBinaryString(file)); 135 | }; 136 | 137 | const onSave = async (e: React.MouseEvent) => { 138 | console.debug("onSave"); 139 | if (await props.service.onTokenChanged(username, token)) { 140 | setError(""); 141 | setShowError(false); 142 | } else { 143 | setError("Invalid api token."); 144 | setShowError(true); 145 | } 146 | }; 147 | 148 | return ( 149 | 150 | Kaggle extension for JupyterLab 151 | 152 | 156 | Kaggle extension for JupyterLab 157 | 158 | {" "} 159 | enables you to browse and download Kaggle Dataset to use in your 160 | JupyterLab. 161 | 162 | Getting started 163 | 164 | Download your Kaggle API token from your{" "} 165 | 166 | Kaggle user's account page 167 | 168 | 169 | to get started. (Click on the "Create New API Token" button.) 170 | 171 | 172 | {({ getRootProps, getInputProps }) => ( 173 | 174 | API Token 175 | 176 | 182 | 183 | 184 | )} 185 | 186 | Don't forget to save your changes. 187 | 188 | Save 189 | 190 | 191 | ); 192 | } 193 | 194 | export class ApiSettingsWidget extends ReactWidget { 195 | private service: KaggleService; 196 | 197 | constructor(service: KaggleService) { 198 | super(); 199 | this.service = service; 200 | } 201 | 202 | render() { 203 | return ; 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /src/widgets/controlls.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Kaggle Inc 2 | // 3 | // Licensed under the Apache License, Version 2.0(the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import styled from "styled-components"; 16 | import { library } from "@fortawesome/fontawesome-svg-core"; 17 | import { 18 | faCalendar, 19 | faCheck, 20 | faCloudDownloadAlt, 21 | faDatabase, 22 | faExternalLinkSquareAlt, 23 | faSpinner, 24 | faTimes, 25 | faToolbox, 26 | faUser, 27 | } from "@fortawesome/free-solid-svg-icons"; 28 | import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; 29 | 30 | library.add(faCalendar); 31 | library.add(faCheck); 32 | library.add(faCloudDownloadAlt); 33 | library.add(faExternalLinkSquareAlt); 34 | library.add(faDatabase); 35 | library.add(faSpinner); 36 | library.add(faTimes); 37 | library.add(faToolbox); 38 | library.add(faUser); 39 | 40 | export const BaseWrapper = styled.div` 41 | display: flex; 42 | flex-direction: column; 43 | flex-wrap: nowrap; 44 | height: 100%; 45 | margin: 0px; 46 | padding: 0px; 47 | `; 48 | 49 | export const WidgetWrapper = styled(BaseWrapper)` 50 | background-color: var(--jp-layout-color1); 51 | font-family: var(--jp-content-font-family); 52 | font-size: var(--jp-content-font-size1); 53 | height: calc(100vh - 95px); 54 | min-width: 270px; 55 | padding: 4px; 56 | `; 57 | 58 | export const BaseLabel = styled.span` 59 | color: var(--jp-content-font-color0); 60 | display: block; 61 | font-size: var(--jp-content-font-size1); 62 | `; 63 | 64 | export const BaseInput = styled.input` 65 | background: transparent; 66 | border: var(--jp-border-width) solid var(--jp-border-color1); 67 | box-sizing: border-box; 68 | color: var(--jp-content-font-color0); 69 | display: block; 70 | font-size: var(--jp-content-font-size2); 71 | height: var(--jp-content-line-height); 72 | margin: 0 4px 8px 0; 73 | width: 100%; 74 | :focus-within { 75 | border: var(--jp-border-width) solid var(--jp-brand-color1); 76 | box-shadow: inset 0 0 4px var(--jp-brand-color2); 77 | } 78 | ::placeholder { 79 | color: var(--jp-content-font-color3); 80 | } 81 | `; 82 | 83 | export const BaseButton = styled.button` 84 | background-color: rgb(0, 138, 188); 85 | border: 0px; 86 | border-radius: var(--jp-border-radius); 87 | color: var(--jp-ui-inverse-font-color1); 88 | font-size: var(--jp-content-font-size3); 89 | margin: 0 0 8px 0; 90 | :hover { 91 | background-color: #00a7ec; 92 | } 93 | `; 94 | 95 | export const BaseLink = styled.a` 96 | color: var(--jp-content-link-color); 97 | font-size: var(--jp-content-font-size1); 98 | :hover { 99 | color: var(--jp-content-link-color); 100 | } 101 | `; 102 | 103 | export const Icon = styled(FontAwesomeIcon)` 104 | margin: 0px 4px 0px 4px; 105 | `; 106 | -------------------------------------------------------------------------------- /src/widgets/datasetPicker.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Kaggle Inc 2 | // 3 | // Licensed under the Apache License, Version 2.0(the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import * as React from "react"; 16 | import filesize from "filesize"; 17 | import moment from "moment"; 18 | import styled from "styled-components"; 19 | import { ReactWidget } from "@jupyterlab/apputils"; 20 | import { DatasetItem } from "../kaggle"; 21 | import { KaggleService } from "../service"; 22 | import { 23 | BaseButton, 24 | BaseLabel, 25 | BaseLink, 26 | BaseInput, 27 | BaseWrapper, 28 | Icon, 29 | WidgetWrapper, 30 | } from "./controlls"; 31 | import { IconProp } from "@fortawesome/fontawesome-svg-core"; 32 | 33 | const SearchInput = styled(BaseInput)``; 34 | 35 | const ListDatasetsAction = styled(BaseButton)``; 36 | 37 | const DatasetListWrapper = styled(BaseWrapper)` 38 | margin: 4px 0px 4px 0px; 39 | padding: 0px; 40 | overflow-y: auto; 41 | `; 42 | 43 | const DatasetItemWrapper = styled(BaseWrapper)` 44 | margin: 0px; 45 | padding: 2px 2px 2px 6px; 46 | :hover { 47 | background-color: var(--jp-layout-color3); 48 | } 49 | :nth-child(2n) { 50 | background-color: var(--jp-layout-color2); 51 | :hover { 52 | background-color: var(--jp-layout-color3); 53 | } 54 | } 55 | `; 56 | 57 | const DatasetInfoWrapper = styled(BaseWrapper)` 58 | border-style: none; 59 | border-width: 0px; 60 | height: auto; 61 | margin: 1px 0px 1px 0px; 62 | padding: 0px; 63 | `; 64 | 65 | const DatasetTopWrapper = styled(BaseWrapper)` 66 | border-style: none; 67 | border-width: 0px; 68 | display: flex; 69 | flex-direction: row; 70 | flex-wrap: nowrap; 71 | height: auto; 72 | margin: 1px 0px 1px 0px; 73 | padding: 0px; 74 | `; 75 | 76 | const DatasetTitleLabel = styled(BaseLabel)` 77 | color: var(--jp-content-font-color2); 78 | font-size: var(--jp-content-font-size2); 79 | margin-left: 2px; 80 | width: calc(100% - 24px); 81 | `; 82 | 83 | const DatasetSlugLabel = styled(BaseLink)` 84 | display: block; 85 | font-size: var(--jp-content-font-size0); 86 | `; 87 | 88 | const DatasetOwnerLabel = styled(BaseLink)` 89 | display: block; 90 | font-size: var(--jp-content-font-size0); 91 | `; 92 | 93 | const DownloadDataset = styled(BaseWrapper)` 94 | color: rgb(0, 138, 188); 95 | font-size: var(--jp-content-font-size3); 96 | :hover { 97 | cursor: copy; 98 | } 99 | `; 100 | 101 | const DatasetStatsWrapper = styled(BaseWrapper)` 102 | border-style: none; 103 | border-width: 0px; 104 | display: flex; 105 | flex-direction: row; 106 | flex-wrap: nowrap; 107 | height: auto; 108 | margin: 1px 0px 1px 0px; 109 | padding: 0px; 110 | `; 111 | 112 | const TimeAgo = styled(BaseLabel)` 113 | color: var(--jp-content-font-color2); 114 | font-size: var(--jp-content-font-size0); 115 | width: 120px; 116 | `; 117 | 118 | const TotalBytes = styled(BaseLabel)` 119 | color: var(--jp-content-font-color2); 120 | font-size: var(--jp-content-font-size0); 121 | width: 100px; 122 | `; 123 | 124 | const Rating = styled(BaseLabel)` 125 | color: var(--jp-content-font-color2); 126 | font-size: var(--jp-content-font-size0); 127 | width: 50px; 128 | `; 129 | 130 | const DatasetDownloadWrapper = styled(BaseWrapper)` 131 | height: auto; 132 | margin: 4px 0px 4px 0px; 133 | padding: 0px; 134 | `; 135 | 136 | const DownloadStatus = styled(BaseLabel)` 137 | margin: 8px 0px 8px 0px; 138 | `; 139 | 140 | interface DatasetPickerProps { 141 | service: KaggleService; 142 | } 143 | 144 | interface DatasetItemProps extends DatasetPickerProps { 145 | data: DatasetItem; 146 | onDownload?: (e: React.MouseEvent) => void; 147 | children?: JSX.Element; 148 | } 149 | 150 | function DatasetItemView(props: DatasetItemProps) { 151 | return ( 152 | 153 | 154 | 155 | {props.data.title} 156 | 157 | 158 | 159 | 160 | 161 | 162 | {props.data.ref} 163 | 164 | 168 | 169 | {props.data.ownerName} 170 | 171 | 172 | 173 | 174 | 175 | {moment(props.data.lastUpdated).fromNow()} 176 | 177 | 178 | 179 | {filesize(props.data.totalBytes)} 180 | 181 | 182 | 183 | {(props.data.usabilityRating * 10).toFixed(1)} 184 | 185 | 186 | {props.children && props.children} 187 | 188 | ); 189 | } 190 | 191 | function DatasetPicker(props: DatasetPickerProps) { 192 | const [search, setSearch] = React.useState(""); 193 | const [datasetItems, setDatasetItems] = React.useState(null as DatasetItem[]); 194 | const [selectedDatasetItem, setSelectedDatasetItem] = React.useState( 195 | null as DatasetItem 196 | ); 197 | const [downloadMessage, setDownloadMessage] = React.useState(""); 198 | const [downloadIcon, setDownloadIcon] = React.useState("spinner" as IconProp); 199 | const [spinDownloadIcon, setSpinDownloadIcon] = React.useState(true); 200 | const [currentPage, setCurrentPage] = React.useState(1); 201 | const [currentSearch, setCurrentSearch] = React.useState(""); 202 | 203 | React.useEffect(() => { 204 | setSelectedDatasetItem(null); 205 | setDatasetItems(null); 206 | LoadDatasets(1); 207 | }, [currentSearch]); 208 | 209 | const LoadDatasets = async (page: number) => { 210 | setCurrentPage(page); 211 | const result = await props.service.listDatasets(page, currentSearch); 212 | if (page == 1) { 213 | setDatasetItems(result); 214 | } else { 215 | setDatasetItems(datasetItems.concat(result)); 216 | } 217 | }; 218 | 219 | const OnKeyUp = async (keyCode: number) => { 220 | switch (keyCode) { 221 | case 13: 222 | setCurrentSearch(search); 223 | break; 224 | case 27: 225 | setSearch(currentSearch); 226 | break; 227 | } 228 | }; 229 | 230 | const DownloadDataset = async (dataset: DatasetItem) => { 231 | setDownloadIcon("spinner"); 232 | setSpinDownloadIcon(true); 233 | setDownloadMessage("Retrieving file list."); 234 | await props.service 235 | .addDataset(dataset) 236 | .then(async files => { 237 | for (let i = 0; i < files.length; i++) { 238 | setDownloadMessage( 239 | "Downloading file " + (i + 1) + " of " + files.length 240 | ); 241 | await props.service.downloadFile(dataset, files[i]); 242 | } 243 | 244 | setDownloadMessage("Download completed"); 245 | setDownloadIcon("check"); 246 | setSpinDownloadIcon(false); 247 | 248 | await props.service.createNotebook(dataset); 249 | }) 250 | .catch(reason => { 251 | const e = reason as Error; 252 | if (e) { 253 | console.error(e.message); 254 | setDownloadMessage(e.message); 255 | setDownloadIcon("times"); 256 | setSpinDownloadIcon(false); 257 | } 258 | }); 259 | }; 260 | 261 | return ( 262 | 263 | setSearch(e.target.value)} 267 | onBlur={e => setCurrentSearch(search)} 268 | onKeyUp={e => OnKeyUp(e.keyCode)} 269 | /> 270 | {selectedDatasetItem && ( 271 | 272 | 273 | 274 | 275 | {downloadMessage} 276 | 277 | 278 | 279 | )} 280 | {datasetItems && ( 281 | 282 | {datasetItems.map((item, i) => ( 283 | { 288 | setSelectedDatasetItem(item); 289 | DownloadDataset(item); 290 | }} 291 | /> 292 | ))} 293 | LoadDatasets(currentPage + 1)}> 294 | Load More 295 | 296 | 297 | )} 298 | 299 | ); 300 | } 301 | 302 | export class DatasetPickerWidget extends ReactWidget { 303 | private service: KaggleService; 304 | 305 | constructor(service: KaggleService) { 306 | super(); 307 | this.service = service; 308 | } 309 | 310 | render() { 311 | return ; 312 | } 313 | } 314 | -------------------------------------------------------------------------------- /style/index.css: -------------------------------------------------------------------------------- 1 | /* Copyright 2019 Kaggle Inc 2 | // 3 | // Licensed under the Apache License, Version 2.0(the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | */ 15 | 16 | .jp-Kaggle { 17 | background-color: var(--jp-layout-color1); 18 | height: 100%; 19 | width: 283px; 20 | } 21 | 22 | .jp-Kaggle-icon { 23 | background-image: url(kaggle.svg) 24 | } 25 | 26 | /* this is not in the JupyterLab css by default */ 27 | .jp-SearchIcon { 28 | background-image: var(--jp-icon-search); 29 | } 30 | -------------------------------------------------------------------------------- /style/kaggle.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 9 | 13 | 15 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | "target": "esnext", 5 | "module": "esnext", 6 | "jsx": "react", 7 | "outDir": "lib", 8 | "rootDir": "src", 9 | "declaration": true, 10 | "composite": true, 11 | "incremental": true, 12 | "noEmitOnError": true, 13 | "esModuleInterop": true, 14 | "preserveWatchOutput": true, 15 | /* Strict Type-Checking Options */ 16 | "strict": true, 17 | "noUnusedLocals": true, 18 | "noFallthroughCasesInSwitch": true, 19 | /* JupyterLab requires these */ 20 | "moduleResolution": "node", 21 | "noUnusedParameters": false, 22 | "strictNullChecks": false, 23 | }, 24 | "include": ["src/**/*"] 25 | } 26 | --------------------------------------------------------------------------------