├── environment.yml ├── .gitignore ├── run_locally.ipynb ├── README.md ├── helper.py ├── LICENSE └── run_google_colab.ipynb /environment.yml: -------------------------------------------------------------------------------- 1 | # To use: 2 | # $ conda env create -f environment.yml 3 | # $ conda activate 4 | name: machinelearnear-hf-spaces 5 | dependencies: 6 | - python=3.9 7 | - pip 8 | - nb_conda_kernels 9 | - ipykernel 10 | - ipywidgets 11 | - gh 12 | - opencv 13 | - pip: 14 | - streamlit 15 | - gradio -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /run_locally.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "53b74bb6-8659-490f-b0db-16bbc6babfa1", 6 | "metadata": { 7 | "tags": [] 8 | }, 9 | "source": [ 10 | "[![Open In SageMaker Studio Lab](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/machinelearnear/open-hf-spaces-in-studiolab/blob/main/launch_app.ipynb)" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "id": "261a11ab-2952-4901-a5ee-99a090dc13ed", 16 | "metadata": { 17 | "tags": [] 18 | }, 19 | "source": [ 20 | "# Open Hugging Face spaces in SageMaker Studio Lab\n", 21 | "- https://huggingface.co/spaces" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "id": "25a5b73b-13f7-4d46-8be0-2c0f8699b16a", 28 | "metadata": {}, 29 | "outputs": [], 30 | "source": [ 31 | "from helper import RepoHandler" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": null, 37 | "id": "20787388-0d6f-4074-9665-9d00b68a5559", 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "domain = 'luzdatd5d7fmka0'\n", 42 | "region = 'us-east-2'" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": null, 48 | "id": "f8eab75d-0dc2-4445-aa94-3d094168b7d1", 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "app = RepoHandler(\n", 53 | " repo_url='https://huggingface.co/spaces/hysts/LoRA-SD-training'\n", 54 | ")" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": null, 60 | "id": "bb3788bd-e5cd-4430-a127-dfb01bea9e69", 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "app.clone_repo(overwrite=True)\n", 65 | "app.install_requirements()" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": null, 71 | "id": "4ebf9889-31a4-46e2-8a50-23511fbdb410", 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "app.run_web_demo()" 76 | ] 77 | } 78 | ], 79 | "metadata": { 80 | "kernelspec": { 81 | "display_name": "default:Python", 82 | "language": "python", 83 | "name": "conda-env-default-py" 84 | }, 85 | "language_info": { 86 | "codemirror_mode": { 87 | "name": "ipython", 88 | "version": 3 89 | }, 90 | "file_extension": ".py", 91 | "mimetype": "text/x-python", 92 | "name": "python", 93 | "nbconvert_exporter": "python", 94 | "pygments_lexer": "ipython3", 95 | "version": "3.9.13" 96 | } 97 | }, 98 | "nbformat": 4, 99 | "nbformat_minor": 5 100 | } 101 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Open 🤗 Spaces in SageMaker Studio Lab 2 | 3 | `HF Spaces` are a great way to showcase your ML work and are quickly becoming the platform of choice for that. This repository is a short step by step tutorial about how to run an ML application hosted on [Hugging Face Spaces](https://huggingface.co/spaces) inside SageMaker Studio Lab. This is relevant because Studio Lab offers free GPU (Nvidia T4, better than Google Colab) for 4 hours at a time plus 15G of persistant storage. Have a look at this [other repo](https://github.com/machinelearnear/use-gradio-streamlit-sagemaker-studiolab) to understand more about what we are doing here. 4 | 5 | https://user-images.githubusercontent.com/78419164/162445810-18ebea84-1b4f-4b1c-b24d-0feff6ad3ff6.mov 6 | 7 | ## Watch YouTube Explainer Video 8 | [![[#08] Cómo usar 🤗 Spaces + GPU sin costo en minutos con SM Studio Lab](https://img.youtube.com/vi/skaYsdSuE70/0.jpg)](https://www.youtube.com/watch?v=skaYsdSuE70) 9 | 10 | ## Getting started 11 | - [SageMaker StudioLab Explainer Video](https://www.youtube.com/watch?v=FUEIwAsrMP4) 12 | - [Hugging Face Spaces Documentation](https://huggingface.co/docs/hub/spaces#reference) 13 | - [Gradio Documentation](https://gradio.app/getting_started/) 14 | - [Streamlit Documentation](https://docs.streamlit.io/) 15 | - [Use Gradio or Streamlit on Studio Lab](https://github.com/machinelearnear/use-gradio-streamlit-sagemaker-studiolab) 16 | 17 | ## Step by step tutorial 18 | 19 | ### Setup your environment 20 | 21 | First, you need to get a [SageMaker Studio Lab](https://studiolab.sagemaker.aws/) account. This is completely free and you don't need an AWS account. Because this new service is still in Preview and AWS is looking to reduce fraud (e.g. crypto mining), you will need to wait 1-3 days for your account to be approved. You can see [this video](https://www.youtube.com/watch?v=FUEIwAsrMP4&ab_channel=machinelearnear) for more information. 22 | 23 | Now that you have your Studio Lab account, you can follow the steps shown in `launch_app.ipynb` [![Open In SageMaker Studio Lab](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/machinelearnear/open-hf-spaces-in-studiolab/blob/main/launch_app.ipynb). 24 | 25 | Click on `Copy to project` in the top right corner. This will open the Studio Lab web interface and ask you whether you want to clone the entire repo or just the Notebook. Clone the entire repo and click `Yes` when asked about building the `Conda` environment automatically. You will now be running on top of a `Python` environment with `Streamlit` and `Gradio` already installed along with other libraries. 26 | 27 | In order to browse to Streamlit or Gradio, you will need to add `proxy/6006/` at the end of your Studio Lab url. It will look like this: 28 | 29 | ```python 30 | studiolab_url = f'https://{studiolab_domain}.studio.{studiolab_region}.sagemaker.aws/studiolab/default/jupyter/proxy/6006/' 31 | ``` 32 | 33 | ### Clone repo and install dependencies 34 | 35 | We first point to the Spaces url that we want to run on Studio Lab: 36 | 37 | ```python 38 | hf_spaces_url = 'https://huggingface.co/spaces/swzamir/Restormer' # choose any demo you like from https://huggingface.co/spaces 39 | hf_spaces_folder = hf_spaces_url.split('/')[-1] 40 | ``` 41 | 42 | Clone the repo and install dependencies. 43 | 44 | ```python 45 | import os 46 | from os.path import exists as path_exists 47 | if not path_exists(hf_spaces_folder): 48 | os.system(f'git clone {hf_spaces_url}') 49 | os.system(f'pip install -r {hf_spaces_folder}/requirements.txt') 50 | ``` 51 | 52 | Within every `Space` there's a `README.md` with information about the app. Example below: 53 | 54 | ``` 55 | --- 56 | title: Image Restoration with Restormer 57 | emoji: 🌍 58 | colorFrom: yellow 59 | colorTo: yellow 60 | sdk: gradio 61 | sdk_version: 2.9.0 62 | app_file: app.py 63 | pinned: false 64 | license: afl-3.0 65 | --- 66 | 67 | Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference 68 | ``` 69 | 70 | We parse that file into a dict to make our lives easier down the line. We use: 71 | 72 | ```python 73 | def info_from_readme(fname): 74 | readme = {} 75 | with open(fname) as f: 76 | for line in f: 77 | if not line.find(':') > 0 or 'Check' in line: continue 78 | (k,v) = line.split(':') 79 | readme[(k)] = v.strip().replace('\n','') 80 | 81 | return readme 82 | ``` 83 | 84 | ### Launch your ML application 85 | 86 | So now we have our repo, we have installed the required libraries, and all we have to do is launch our app. For that we define a very simple function that takes the local path to the repo, prints the Studio Lab url your application will run on, and then launches either Streamlit or Gradio on the right server port depending on the type of `sdk` that was used on HF Spaces: 87 | 88 | ```python 89 | def launch_demo(folder_name, url=studiolab_url): 90 | if path_exists(folder_name): 91 | readme = info_from_readme(f'{folder_name}/README.md') 92 | else: 93 | print('No `README.md` file') 94 | return 95 | 96 | print('\033[1m' + f'Demo: {readme["title"]}\n' + '\033[0m') 97 | print(f'Please wait a few seconds before you click the link below to load your demo \n{url}\n') 98 | 99 | if readme["sdk"] == 'gradio': 100 | os.system(f'export GRADIO_SERVER_PORT=6006 && cd {folder_name} && python {readme["app_file"]}') 101 | elif readme["title"] == 'streamlit': 102 | os.sytem(f'cd {folder_name} && streamlit run {readme["app_file"]} --server.port 6006') # 6006 or 80/8080 are open 103 | else: 104 | print('This notebook will not work with static apps hosted on `Spaces`') 105 | ``` 106 | 107 | All we need to do now is to run `launch_demo(hf_spaces_folder)`. 108 | 109 | ## References 110 | - See more about Restormer here: https://huggingface.co/spaces/swzamir/Restormer 111 | 112 | ## Disclaimer 113 | - The content provided in this repository is for demonstration purposes and not meant for production. You should use your own discretion when using the content. 114 | - The ideas and opinions outlined in these examples are my own and do not represent the opinions of AWS. 115 | -------------------------------------------------------------------------------- /helper.py: -------------------------------------------------------------------------------- 1 | #@title Un poco de código para configurar todo, clonar el repo, instalar las librerias, etc. 2 | # source: https://www.youtube.com/c/machinelearnear 3 | 4 | import os 5 | import sys 6 | import shutil 7 | import subprocess 8 | import re 9 | 10 | try: 11 | import gradio as gr 12 | except ImportError: 13 | subprocess.run(["pip", "install", "gradio"]) 14 | import gradio as gr 15 | 16 | from os.path import exists as path_exists 17 | from pathlib import Path 18 | from typing import Dict 19 | 20 | newline, bold, unbold = "\n", "\033[1m", "\033[0m" 21 | 22 | class RepoHandler: 23 | def __init__(self, repo_url: str) -> None: 24 | """ 25 | Initialize the RepoHandler class with the provided repository URL and requirements file. 26 | Args: 27 | - repo_url: URL of the git repository to clone. 28 | Returns: 29 | None 30 | """ 31 | self.is_google_colab = False 32 | self.fix_for_gr, self.fix_for_st = None, None 33 | self.app_file = "app.py" 34 | if 'google.colab' in str(get_ipython()): 35 | print(f'{bold}Running on: "Google Colab"{unbold}') 36 | self.is_google_colab = True 37 | else: 38 | print(f'{bold}Running on: Local or "SM Studio Lab"{unbold}') 39 | self.repo_url = repo_url 40 | self.repo_name = self.repo_url.split('/')[-1] 41 | 42 | def __str__(self): 43 | if os.path.exists(self.repo_name): 44 | return self.retrieve_readme(f'{self.repo_name}/README.md') 45 | else: 46 | print(f"{bold}The repo '{self.repo_name}' has not been cloned yet.{unbold}") 47 | return None 48 | 49 | def retrieve_readme(self, filename) -> Dict: 50 | readme = {} 51 | if path_exists(filename): 52 | with open(filename) as f: 53 | for line in f: 54 | if not line.find(':') > 0 or 'Check' in line: continue 55 | (k,v) = line.split(':') 56 | readme[(k)] = v.strip().replace('\n','') 57 | else: 58 | print(f"{bold}No 'readme.md' file{unbold}") 59 | 60 | return readme 61 | 62 | def clone_repo(self, overwrite=False) -> None: 63 | """ 64 | Clone the git repository specified in the repo_url attribute. 65 | Returns: 66 | None 67 | """ 68 | # Check if repository has already been cloned locally 69 | if overwrite and os.path.exists(self.repo_name): 70 | try: 71 | shutil.rmtree(self.repo_name) 72 | except OSError as e: 73 | print("Error: %s - %s." % (e.filename, e.strerror)) 74 | if os.path.exists(self.repo_name): 75 | print(f"{bold}Repository '{self.repo_name}' has already been cloned.{unbold}") 76 | else: 77 | print(f"{bold}Cloning repo... may take a few minutes... remember to set your Space to 'public'...{unbold}") 78 | subprocess.run(["apt-get", "install", "git-lfs"]) 79 | subprocess.run(["git", "lfs", "install", "--system", "--skip-repo"]) 80 | subprocess.run(["git", "clone", "--recurse-submodules", self.repo_url]) 81 | 82 | def install_requirements(self, requirements_file: str = None, install_xformers: bool = False) -> None: 83 | """ 84 | Install the requirements specified in the requirements_file attribute. 85 | 86 | Args: 87 | - requirements_file: Name of the file containing the requirements to install. This file must be 88 | located in the root directory of the repository. Defaults to "requirements.txt". 89 | Returns: 90 | None 91 | """ 92 | if not requirements_file: requirements_file = f"{self.repo_name}/requirements.txt" 93 | 94 | # install requirements 95 | print(f"{bold}Installing requirements... may take a few minutes...{unbold}") 96 | subprocess.run(["pip", "install", "-r", requirements_file]) 97 | if install_xformers: self.install_xformers() 98 | 99 | def run_web_demo(self, aws_domain=None, aws_region=None) -> None: 100 | """ 101 | Launch the Gradio or Streamlit web demo for the cloned repository. 102 | Works with Google Colab or SageMaker Studio Lab. 103 | Returns: 104 | None 105 | """ 106 | import torch 107 | if torch.cuda.is_available(): print(f"{bold}Using: {unbold}{self.get_gpu_memory_map()}") 108 | else: print(f"{bold}Not using the GPU{unbold}") 109 | 110 | readme = self.__str__() 111 | self.app_file = readme["app_file"] 112 | print(f"{bold}Demo: `{readme['title']}`{newline}{unbold}") 113 | print(f"{bold}Downloading models... might take up to 10 minutes to finish...{unbold}") 114 | print(f"{bold}Once finished, click the link below to open your application (in SM Studio Lab):{newline}{unbold}") 115 | if all([aws_domain, aws_region]): 116 | print(f'{bold}https://{aws_domain}.studio.{aws_region}.sagemaker.aws/studiolab/default/jupyter/proxy/6006/{unbold}') 117 | 118 | self.unset_environment_variables() 119 | 120 | if readme["sdk"] == 'gradio': 121 | gr.close_all() 122 | if not self.is_google_colab: 123 | !export GRADIO_SERVER_PORT=6006 && cd $self.repo_name && python $self.app_file 124 | # os.system(f'export GRADIO_SERVER_PORT=6006 && cd {self.repo_name} && python {readme["app_file"]}') 125 | else: 126 | new_filename = self.replace_gradio_launcher(f'{self.repo_name}/{readme["app_file"]}') 127 | !cd $self.repo_name && python $new_filename 128 | # os.system(f'cd {self.repo_name} && python {readme["app_file"]}') 129 | elif readme["title"] == 'streamlit': 130 | if not self.is_google_colab: 131 | !cd $self.repo_name && streamlit run $self.app_file --server.port 6006 132 | # os.system(f'cd {self.repo_name} && streamlit run {readme["app_file"]} --server.port 6006') 133 | else: 134 | !cd $self.repo_name && streamlit run $self.app_file 135 | # os.system(f'cd {self.repo_name} && streamlit run {readme["app_file"]}') 136 | else: 137 | print('This notebook will not work with static apps hosted on "Spaces"') 138 | 139 | def get_gpu_memory_map(self) -> Dict[str, int]: 140 | """Get the current gpu usage. 141 | Return: 142 | A dictionary in which the keys are device ids as integers and 143 | values are memory usage as integers in MB. 144 | """ 145 | result = subprocess.run( 146 | ["nvidia-smi", "--query-gpu=name,memory.total,memory.free", "--format=csv,noheader",], 147 | encoding="utf-8", 148 | # capture_output=True, # valid for python version >=3.7 149 | stdout=subprocess.PIPE, 150 | stderr=subprocess.PIPE, # for backward compatibility with python version 3.6 151 | check=True, 152 | ) 153 | # Convert lines into a dictionary, return f"{}" 154 | gpu_memory = [x for x in result.stdout.strip().split(os.linesep)] 155 | gpu_memory_map = {f"gpu_{index}": memory for index, memory in enumerate(gpu_memory)} 156 | 157 | return gpu_memory_map 158 | 159 | def replace_gradio_launcher(self, old_filename) -> str: 160 | # Read the contents of the file 161 | with open(old_filename, "r") as f: 162 | contents = f.read() 163 | # Define the regular expression pattern 164 | pattern = r"\.launch\((.*?)\)" 165 | # Use the sub method to replace the text 166 | contents = re.sub(pattern, ".launch(share=True)", contents) 167 | # Write the modified contents back to the file 168 | new_filename = Path(old_filename).parent / f"{Path(old_filename).stem}_modified.py" 169 | with open(new_filename, "w") as f: 170 | f.write(contents) 171 | 172 | return new_filename.name 173 | 174 | def unset_environment_variables(self) -> None: 175 | os.unsetenv("SHARED_UI") 176 | os.environ.pop("SHARED_UI", None) 177 | 178 | os.unsetenv("IS_SHARED") 179 | os.environ.pop("IS_SHARED", None) 180 | 181 | def install_xformers(self) -> None: 182 | from subprocess import getoutput 183 | from IPython.display import HTML 184 | from IPython.display import clear_output 185 | import time 186 | 187 | subprocess.run(["pip", "install", "-U", "--pre", "triton"]) 188 | 189 | s = getoutput('nvidia-smi') 190 | if 'T4' in s: gpu = 'T4' 191 | elif 'P100' in s: gpu = 'P100' 192 | elif 'V100' in s: gpu = 'V100' 193 | elif 'A100' in s: gpu = 'A100' 194 | 195 | while True: 196 | try: 197 | gpu=='T4'or gpu=='P100'or gpu=='V100'or gpu=='A100' 198 | break 199 | except: 200 | pass 201 | print(f'{bold} Seems that your GPU is not supported at the moment.{unbold}') 202 | time.sleep(5) 203 | 204 | if (gpu=='T4'): 205 | precompiled_wheels = "https://github.com/TheLastBen/fast-stable-diffusion/raw/main/precompiled/T4/xformers-0.0.13.dev0-py3-none-any.whl" 206 | elif (gpu=='P100'): 207 | precompiled_wheels = "https://github.com/TheLastBen/fast-stable-diffusion/raw/main/precompiled/P100/xformers-0.0.13.dev0-py3-none-any.whl" 208 | elif (gpu=='V100'): 209 | precompiled_wheels = "https://github.com/TheLastBen/fast-stable-diffusion/raw/main/precompiled/V100/xformers-0.0.13.dev0-py3-none-any.whl" 210 | elif (gpu=='A100'): 211 | precompiled_wheels = "https://github.com/TheLastBen/fast-stable-diffusion/raw/main/precompiled/A100/xformers-0.0.13.dev0-py3-none-any.whl" 212 | 213 | subprocess.run(["pip", "install", "-q", precompiled_wheels]) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /run_google_colab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/machinelearnear/open-hf-spaces-in-studiolab/blob/main/run_google_colab.ipynb)" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": { 13 | "id": "tA1VyFSQOAjd", 14 | "tags": [] 15 | }, 16 | "source": [ 17 | "# `< Nombre >` a través de Hugging Face Spaces\n", 18 | "\n", 19 | "`machinelearnear` 🧉🤖 > https://www.youtube.com/c/machinelearnear\n", 20 | "---\n", 21 | "**Referencias**\n", 22 | "- https://www.youtube.com/watch?v=vqdl31w-nWo" 23 | ] 24 | }, 25 | { 26 | "cell_type": "markdown", 27 | "metadata": { 28 | "id": "j9RkjQ99OIU_", 29 | "jp-MarkdownHeadingCollapsed": true, 30 | "tags": [] 31 | }, 32 | "source": [ 33 | "## Configurar entorno de Hugging Face Spaces" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": { 40 | "id": "rmBjvPVHO1fs" 41 | }, 42 | "outputs": [], 43 | "source": [ 44 | "#@title Un poco de código para configurar todo, clonar el repo, instalar las librerias, etc.\n", 45 | "# source: https://www.youtube.com/c/machinelearnear\n", 46 | "\n", 47 | "import os\n", 48 | "import sys\n", 49 | "import shutil\n", 50 | "import subprocess\n", 51 | "import re\n", 52 | "\n", 53 | "try:\n", 54 | " import gradio as gr\n", 55 | "except ImportError:\n", 56 | " subprocess.run([\"pip\", \"install\", \"gradio\"])\n", 57 | " import gradio as gr\n", 58 | "\n", 59 | "from os.path import exists as path_exists\n", 60 | "from pathlib import Path\n", 61 | "from typing import Dict\n", 62 | "\n", 63 | "newline, bold, unbold = \"\\n\", \"\\033[1m\", \"\\033[0m\"\n", 64 | "\n", 65 | "class RepoHandler:\n", 66 | " def __init__(self, repo_url: str) -> None:\n", 67 | " \"\"\"\n", 68 | " Initialize the RepoHandler class with the provided repository URL and requirements file.\n", 69 | " Args:\n", 70 | " - repo_url: URL of the git repository to clone.\n", 71 | " Returns:\n", 72 | " None\n", 73 | " \"\"\"\n", 74 | " self.is_google_colab = False\n", 75 | " self.fix_for_gr, self.fix_for_st = None, None\n", 76 | " self.app_file = \"app.py\"\n", 77 | " if 'google.colab' in str(get_ipython()):\n", 78 | " print(f'{bold}Running on: \"Google Colab\"{unbold}')\n", 79 | " self.is_google_colab = True\n", 80 | " else:\n", 81 | " print(f'{bold}Running on: Local or \"SM Studio Lab\"{unbold}')\n", 82 | " self.repo_url = repo_url\n", 83 | " self.repo_name = self.repo_url.split('/')[-1]\n", 84 | "\n", 85 | " def __str__(self):\n", 86 | " if os.path.exists(self.repo_name):\n", 87 | " return self.retrieve_readme(f'{self.repo_name}/README.md')\n", 88 | " else:\n", 89 | " print(f\"{bold}The repo '{self.repo_name}' has not been cloned yet.{unbold}\")\n", 90 | " return None\n", 91 | " \n", 92 | " def retrieve_readme(self, filename) -> Dict:\n", 93 | " readme = {}\n", 94 | " if path_exists(filename):\n", 95 | " with open(filename) as f:\n", 96 | " for line in f:\n", 97 | " if line.find('http') > 0: continue\n", 98 | " if not line.find(':') > 0 or 'Check' in line: continue\n", 99 | " (k,v) = line.split(':')\n", 100 | " readme[(k)] = v.strip().replace('\\n','')\n", 101 | " else:\n", 102 | " print(f\"{bold}No 'readme.md' file{unbold}\")\n", 103 | " \n", 104 | " return readme\n", 105 | " \n", 106 | " def clone_repo(self, overwrite=False) -> None:\n", 107 | " \"\"\"\n", 108 | " Clone the git repository specified in the repo_url attribute.\n", 109 | " Returns:\n", 110 | " None\n", 111 | " \"\"\"\n", 112 | " # Check if repository has already been cloned locally\n", 113 | " if overwrite and os.path.exists(self.repo_name): \n", 114 | " try:\n", 115 | " shutil.rmtree(self.repo_name)\n", 116 | " except OSError as e:\n", 117 | " print(\"Error: %s - %s.\" % (e.filename, e.strerror))\n", 118 | " if os.path.exists(self.repo_name):\n", 119 | " print(f\"{bold}Repository '{self.repo_name}' has already been cloned.{unbold}\")\n", 120 | " else:\n", 121 | " print(f\"{bold}Cloning repo... may take a few minutes... remember to set your Space to 'public'...{unbold}\")\n", 122 | " subprocess.run([\"apt-get\", \"install\", \"git-lfs\"])\n", 123 | " subprocess.run([\"git\", \"lfs\", \"install\", \"--system\", \"--skip-repo\"])\n", 124 | " subprocess.run([\"git\", \"clone\", \"--recurse-submodules\", self.repo_url])\n", 125 | "\n", 126 | " def install_requirements(self, requirements_file: str = None, install_xformers: bool = False) -> None:\n", 127 | " \"\"\"\n", 128 | " Install the requirements specified in the requirements_file attribute.\n", 129 | " \n", 130 | " Args:\n", 131 | " - requirements_file: Name of the file containing the requirements to install. This file must be \n", 132 | " located in the root directory of the repository. Defaults to \"requirements.txt\".\n", 133 | " Returns:\n", 134 | " None\n", 135 | " \"\"\"\n", 136 | " if not requirements_file: requirements_file = f\"{self.repo_name}/requirements.txt\"\n", 137 | " \n", 138 | " # install requirements\n", 139 | " print(f\"{bold}Installing requirements... may take a few minutes...{unbold}\")\n", 140 | " subprocess.run([\"pip\", \"install\", \"-r\", requirements_file])\n", 141 | " if install_xformers: self.install_xformers()\n", 142 | "\n", 143 | " def run_web_demo(self, aws_domain=None, aws_region=None) -> None:\n", 144 | " \"\"\"\n", 145 | " Launch the Gradio or Streamlit web demo for the cloned repository.\n", 146 | " Works with Google Colab or SageMaker Studio Lab.\n", 147 | " Returns:\n", 148 | " None\n", 149 | " \"\"\"\n", 150 | " import torch\n", 151 | " if torch.cuda.is_available(): print(f\"{bold}Using: {unbold}{self.get_gpu_memory_map()}\")\n", 152 | " else: print(f\"{bold}Not using the GPU{unbold}\")\n", 153 | " \n", 154 | " readme = self.__str__()\n", 155 | " self.app_file = readme[\"app_file\"]\n", 156 | " print(f\"{bold}Demo: `{readme['title']}`{newline}{unbold}\")\n", 157 | " print(f\"{bold}Downloading models... might take up to 10 minutes to finish...{unbold}\")\n", 158 | " print(f\"{bold}Once finished, click the link below to open your application (in SM Studio Lab):{newline}{unbold}\")\n", 159 | " if all([aws_domain, aws_region]):\n", 160 | " print(f'{bold}https://{aws_domain}.studio.{aws_region}.sagemaker.aws/studiolab/default/jupyter/proxy/6006/{unbold}')\n", 161 | " \n", 162 | " self.unset_environment_variables()\n", 163 | " \n", 164 | " if readme[\"sdk\"] == 'gradio':\n", 165 | " gr.close_all()\n", 166 | " if not self.is_google_colab:\n", 167 | " !export GRADIO_SERVER_PORT=6006 && cd $self.repo_name && python $self.app_file\n", 168 | " # os.system(f'export GRADIO_SERVER_PORT=6006 && cd {self.repo_name} && python {readme[\"app_file\"]}')\n", 169 | " else:\n", 170 | " new_filename = self.replace_gradio_launcher(f'{self.repo_name}/{readme[\"app_file\"]}')\n", 171 | " !cd $self.repo_name && python $new_filename\n", 172 | " # os.system(f'cd {self.repo_name} && python {readme[\"app_file\"]}')\n", 173 | " elif readme[\"title\"] == 'streamlit':\n", 174 | " if not self.is_google_colab:\n", 175 | " !cd $self.repo_name && streamlit run $self.app_file --server.port 6006\n", 176 | " # os.system(f'cd {self.repo_name} && streamlit run {readme[\"app_file\"]} --server.port 6006')\n", 177 | " else:\n", 178 | " !cd $self.repo_name && streamlit run $self.app_file\n", 179 | " # os.system(f'cd {self.repo_name} && streamlit run {readme[\"app_file\"]}')\n", 180 | " else:\n", 181 | " print('This notebook will not work with static apps hosted on \"Spaces\"')\n", 182 | "\n", 183 | " def get_gpu_memory_map(self) -> Dict[str, int]:\n", 184 | " \"\"\"Get the current gpu usage.\n", 185 | " Return:\n", 186 | " A dictionary in which the keys are device ids as integers and\n", 187 | " values are memory usage as integers in MB.\n", 188 | " \"\"\"\n", 189 | " result = subprocess.run(\n", 190 | " [\"nvidia-smi\", \"--query-gpu=name,memory.total,memory.free\", \"--format=csv,noheader\",],\n", 191 | " encoding=\"utf-8\",\n", 192 | " # capture_output=True, # valid for python version >=3.7\n", 193 | " stdout=subprocess.PIPE,\n", 194 | " stderr=subprocess.PIPE, # for backward compatibility with python version 3.6\n", 195 | " check=True,\n", 196 | " )\n", 197 | " # Convert lines into a dictionary, return f\"{}\"\n", 198 | " gpu_memory = [x for x in result.stdout.strip().split(os.linesep)]\n", 199 | " gpu_memory_map = {f\"gpu_{index}\": memory for index, memory in enumerate(gpu_memory)}\n", 200 | " \n", 201 | " return gpu_memory_map\n", 202 | "\n", 203 | " def replace_gradio_launcher(self, old_filename) -> str:\n", 204 | " # Read the contents of the file\n", 205 | " with open(old_filename, \"r\") as f:\n", 206 | " contents = f.read()\n", 207 | " # Define the regular expression pattern\n", 208 | " pattern = r\"\\.launch\\((.*?)\\)\"\n", 209 | " # Use the sub method to replace the text\n", 210 | " contents = re.sub(pattern, \".launch(share=True)\", contents)\n", 211 | " # Write the modified contents back to the file\n", 212 | " new_filename = Path(old_filename).parent / f\"{Path(old_filename).stem}_modified.py\"\n", 213 | " with open(new_filename, \"w\") as f:\n", 214 | " f.write(contents)\n", 215 | "\n", 216 | " return new_filename.name\n", 217 | " \n", 218 | " def unset_environment_variables(self) -> None:\n", 219 | " os.unsetenv(\"SHARED_UI\")\n", 220 | " os.environ.pop(\"SHARED_UI\", None)\n", 221 | " \n", 222 | " os.unsetenv(\"IS_SHARED\")\n", 223 | " os.environ.pop(\"IS_SHARED\", None)\n", 224 | "\n", 225 | " def install_xformers(self) -> None:\n", 226 | " from subprocess import getoutput\n", 227 | " from IPython.display import HTML\n", 228 | " from IPython.display import clear_output\n", 229 | " import time\n", 230 | "\n", 231 | " subprocess.run([\"pip\", \"install\", \"-U\", \"--pre\", \"triton\"])\n", 232 | "\n", 233 | " s = getoutput('nvidia-smi')\n", 234 | " if 'T4' in s: gpu = 'T4'\n", 235 | " elif 'P100' in s: gpu = 'P100'\n", 236 | " elif 'V100' in s: gpu = 'V100'\n", 237 | " elif 'A100' in s: gpu = 'A100'\n", 238 | "\n", 239 | " while True:\n", 240 | " try: \n", 241 | " gpu=='T4'or gpu=='P100'or gpu=='V100'or gpu=='A100'\n", 242 | " break\n", 243 | " except:\n", 244 | " pass\n", 245 | " print(f'{bold} Seems that your GPU is not supported at the moment.{unbold}')\n", 246 | " time.sleep(5)\n", 247 | "\n", 248 | " if (gpu=='T4'): \n", 249 | " precompiled_wheels = \"https://github.com/TheLastBen/fast-stable-diffusion/raw/main/precompiled/T4/xformers-0.0.13.dev0-py3-none-any.whl\"\n", 250 | " elif (gpu=='P100'): \n", 251 | " precompiled_wheels = \"https://github.com/TheLastBen/fast-stable-diffusion/raw/main/precompiled/P100/xformers-0.0.13.dev0-py3-none-any.whl\"\n", 252 | " elif (gpu=='V100'): \n", 253 | " precompiled_wheels = \"https://github.com/TheLastBen/fast-stable-diffusion/raw/main/precompiled/V100/xformers-0.0.13.dev0-py3-none-any.whl\"\n", 254 | " elif (gpu=='A100'): \n", 255 | " precompiled_wheels = \"https://github.com/TheLastBen/fast-stable-diffusion/raw/main/precompiled/A100/xformers-0.0.13.dev0-py3-none-any.whl\"\n", 256 | "\n", 257 | " subprocess.run([\"pip\", \"install\", \"-q\", precompiled_wheels])" 258 | ] 259 | }, 260 | { 261 | "cell_type": "markdown", 262 | "metadata": { 263 | "id": "ioW5IDk4PXg4" 264 | }, 265 | "source": [ 266 | "## Ya tenemos todo listo, empezar el proceso! 🚀" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": null, 272 | "metadata": { 273 | "colab": { 274 | "base_uri": "https://localhost:8080/" 275 | }, 276 | "id": "DvACWIthPn4P", 277 | "outputId": "9ce736c1-5ef8-4737-e48b-8b27fa0c6797" 278 | }, 279 | "outputs": [], 280 | "source": [ 281 | "app = RepoHandler(\n", 282 | " repo_url='https://huggingface.co/spaces/hysts/LoRA-SD-training'\n", 283 | ")" 284 | ] 285 | }, 286 | { 287 | "cell_type": "code", 288 | "execution_count": null, 289 | "metadata": { 290 | "colab": { 291 | "base_uri": "https://localhost:8080/" 292 | }, 293 | "id": "xfE0Zx-2PvUd", 294 | "outputId": "073e29e0-40ba-4d47-d816-d0dceb98b6a9" 295 | }, 296 | "outputs": [], 297 | "source": [ 298 | "app.clone_repo(overwrite=False)\n", 299 | "app.install_requirements()" 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": null, 305 | "metadata": { 306 | "colab": { 307 | "base_uri": "https://localhost:8080/" 308 | }, 309 | "id": "6tkTJI0SPvv5", 310 | "outputId": "e69a7612-5556-40c9-ada8-3bbac606f8a0" 311 | }, 312 | "outputs": [], 313 | "source": [ 314 | "app.run_web_demo()" 315 | ] 316 | } 317 | ], 318 | "metadata": { 319 | "accelerator": "GPU", 320 | "colab": { 321 | "name": "machinelearnear_sd_paint_by_example.ipynb", 322 | "provenance": [] 323 | }, 324 | "gpuClass": "standard", 325 | "kernelspec": { 326 | "display_name": "default:Python", 327 | "language": "python", 328 | "name": "conda-env-default-py" 329 | }, 330 | "language_info": { 331 | "codemirror_mode": { 332 | "name": "ipython", 333 | "version": 3 334 | }, 335 | "file_extension": ".py", 336 | "mimetype": "text/x-python", 337 | "name": "python", 338 | "nbconvert_exporter": "python", 339 | "pygments_lexer": "ipython3", 340 | "version": "3.9.13" 341 | } 342 | }, 343 | "nbformat": 4, 344 | "nbformat_minor": 4 345 | } 346 | --------------------------------------------------------------------------------