예제 #1
0
def _display_stdin_widget(delay_millis=0):
    """Context manager that displays a stdin UI widget and hides it upon exit.

  Args:
    delay_millis: Duration (in milliseconds) to delay showing the widget within
      the UI.

  Yields:
    A callback that can be invoked with a single argument indicating whether
    echo is enabled.
  """
    shell = _ipython.get_ipython()
    display_args = ['cell_display_stdin', {'delayMillis': delay_millis}]
    _message.blocking_request(*display_args, parent=shell.parent_header)

    def echo_updater(new_echo_status):
        # Note: Updating the echo status uses colab_request / colab_reply on the
        # stdin socket. Input provided by the user also sends messages on this
        # socket. If user input is provided while the blocking_request call is still
        # waiting for a colab_reply, the input will be dropped per
        # https://github.com/googlecolab/colabtools/blob/56e4dbec7c4fa09fad51b60feb5c786c69d688c6/google/colab/_message.py#L100.
        update_args = ['cell_update_stdin', {'echo': new_echo_status}]
        _message.blocking_request(*update_args, parent=shell.parent_header)

    yield echo_updater

    hide_args = ['cell_remove_stdin', {}]
    _message.blocking_request(*hide_args, parent=shell.parent_header)
예제 #2
0
 def echo_updater(new_echo_status):
     # Note: Updating the echo status uses colab_request / colab_reply on the
     # stdin socket. Input provided by the user also sends messages on this
     # socket. If user input is provided while the blocking_request call is still
     # waiting for a colab_reply, the input will be dropped per
     # https://github.com/googlecolab/colabtools/blob/56e4dbec7c4fa09fad51b60feb5c786c69d688c6/google/colab/_message.py#L100.
     update_args = ['cell_update_stdin', {'echo': new_echo_status}]
     _message.blocking_request(*update_args, parent=shell.parent_header)
예제 #3
0
def register(url):
  """Add new snippets to the snippets pane from a notebook url.

  The snippets pane in Colab (visible with Ctrl-Alt-P) allows a colab user to
  search and insert snippets of code to do common tasks. This function will
  add new snippets to this menu, from any colab notebook URL accessible to the
  user. A notebook can contain multiple snippets, each under a markdown heading.

  Args:
    url: string. A URL that points to a saved Colab notebook
  """
  _message.blocking_request('register_snippets', {'url': url})
예제 #4
0
def Submit(exercise_id=None):
  if JWT_TOKEN == "":
    display.display(display.HTML("Please get JWT_TOKEN by visiting " +
                                 "<a href='" + SERVER_URL + "/login'>Login page</a>"))
    raise Exception("Please set JWT_TOKEN")
  notebook = google_message.blocking_request(
    "get_ipynb", request="", timeout_sec=120)["ipynb"]
  ids = []
  for cell in notebook['cells']:
        if 'metadata' not in cell:
          continue
        m = cell['metadata']
        if m and 'exercise_id' in m:
            cell_id = m['exercise_id']
            if cell_id:
                ids.append(cell_id)
  params = {}
  if exercise_id:
    if exercise_id not in ids:
        raise Exception('Not valid exercise ID: ' + exercise_id + ". Valid ids: " + ", ".join(ids))
    params["exercise_id"] = exercise_id
  data = json.dumps(notebook)
  r = requests.post(SERVER_URL + "/upload", files={"notebook": data},
                    headers={"Authorization": "Bearer " + JWT_TOKEN},
                    params=params)
  if r.status_code == 401:
    display.display(display.HTML("Not authorized: is your JWT_TOKEN correct? " +
                                 "Please get JWT_TOKEN by visiting " +
                                 "<a target='_blank' href='" + SERVER_URL + "/login'>Login page</a>" +
                                 "in a new browser tab."))  
  display.display(display.HTML(r.content.decode('utf-8')))
예제 #5
0
def GetNotebook():
    """Downloads the ipynb source of Colab notebook"""
    try:
        from google.colab import _message as google_message
    except Exception as e:
        raise Exception('Could not import google_message from google.colab. '
                        'Are you running in Google Colab?\n'
                        'Nested exception: ' + str(e))
    notebook = google_message.blocking_request("get_ipynb",
                                               request="",
                                               timeout_sec=120)["ipynb"]
    return notebook
예제 #6
0
def get_print_output_colab(input_, **kwargs):
    from google.colab import _message
    nb = _message.blocking_request('get_ipynb')

    for cell in nb['ipynb']['cells']:
        if cell['cell_type'] == 'code':
            for line in cell['source']:
                if line.lower().startswith(input_):
                    #selects the string between parentheses in print()
                    print_str = line[line.find("(") + 1:line.rfind(")")]
                    #print_str = line[6:-1]
                    output = eval(print_str, kwargs)
                    return output
예제 #7
0
def _get_colab_notebook_content():
    """Returns the colab notebook python code contents."""
    response = _message.blocking_request("get_ipynb", request="", timeout_sec=200)
    if response is None:
        raise RuntimeError("Unable to get the notebook contents.")
    cells = response["ipynb"]["cells"]
    py_content = []
    for cell in cells:
        if cell["cell_type"] == "code":
            # Add newline char to the last line of a code cell.
            cell["source"][-1] += "\n"

            # Combine all code cells.
            py_content.extend(cell["source"])
    return py_content
예제 #8
0
def GetNotebook():
    """Downloads the ipynb source of Colab notebook"""
    notebook = google_message.blocking_request("get_ipynb",
                                               request="",
                                               timeout_sec=120)["ipynb"]
    return notebook