# Script to create a notebook out of `requirements.txt` (installing the dependencies) and `app.py` import json from textwrap import dedent def create_colab(requirements_file='requirements.txt', app_file='app.py'): # cells = [] requirements_txt = open('requirements.txt', 'r').read().replace('\n', '\\n') def text_to_cell(text, cell_type='code'): lines = dedent(text).splitlines() # add a \n to the end of each line except the last one lines = [ f'{line}\n' for line in lines[:-1] ] + [ lines[-1] ] return dict( metadata={}, execution_count=None, outputs=[], cell_type=cell_type, source=lines ) cells = [ # Cell to mount drive, install the dependencies etc. text_to_cell(f"""\ from google.colab import drive mount_drive = True #@param {{type:"boolean"}} if mount_drive: drive.mount('/content/drive') requirements_txt = "{requirements_txt}" # Save the requirements.txt file with open('requirements.txt', 'w') as f: f.write(requirements_txt) # Install the dependencies %pip install -r requirements.txt """), # Cell to run the app text_to_cell(open(app_file, 'r').read()) ] # Add notebook metadata metadata = dict( kernelspec = dict( display_name = 'Python 3', language = 'python', name = 'python3' ), language_info = dict( name = 'python', version = '3.7.5', ), orig_nbformat = 4, ) # Finalize the notebook notebook = dict( cells=cells, metadata=metadata, nbformat=4, nbformat_minor=2, ) # Name the notebook the same as the parent directory from pathlib import Path notebook_name = f'{Path().absolute().name}.ipynb' # Save the notebook in JSON format open(notebook_name, 'w').write(json.dumps(notebook, indent=2)) return notebook if __name__ == '__main__': create_colab()