File size: 1,929 Bytes
631e673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# 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()