Ejemplo n.º 1
0
    def wrapper(*args, **kwargs):
        J_LOGGER.debug("{}: {}", start_msg, f.__name__)

        result = f(*args, **kwargs)

        J_LOGGER.debug("{}: {}", close_msg, result)

        return result
def register_server(notebook_path: str, port_number: int) -> None:
    J_LOGGER.info("Registering notebook {notebook} on port {port}",
                  notebook=notebook_path,
                  port=port_number)

    _REGISTERED_SERVERS[notebook_path] = port_number

    J_LOGGER.debug("Updated notebook mappings: {}", _REGISTERED_SERVERS)
Ejemplo n.º 3
0
def perform_notebook_request(notebook_path: str, command_name: str, data: Dict[str, Any]) -> None:
    J_LOGGER.debug("Performing notebook request... ")

    notebook_server = get_server_for_notebook(notebook_path)
    if notebook_server is None:
        J_LOGGER.warning("==> Unable to process request")
        J_LOGGER.warning("==> {}", _REGISTERED_SERVERS)
        return

    request(notebook_server, command_name, data=data)
Ejemplo n.º 4
0
def _find_cell_number(lines: List[str], line_number: int) -> int:
    cell_index = -1

    for index, line in enumerate(lines):
        if any(pat.match(line) for pat in CELL_SEPARATOR_PATTERNS):
            J_LOGGER.debug(f"Found another new cell on line number: {index}")
            cell_index += 1
            J_LOGGER.debug(f"    New cell index {cell_index}")

        # Found line number, quit
        if index == int(line_number):
            break

    return cell_index
def perform_notebook_request(notebook_path: str, command_name: str,
                             data: Dict[str, Any]) -> Optional[Dict]:
    J_LOGGER.debug("Performing notebook request... ")

    try:
        notebook_server = get_server_for_notebook(notebook_path)
    except UnableToFindNotebookException:
        J_LOGGER.warning(
            f"Unabled to find {notebook_path} in {_REGISTERED_SERVERS}")
        return {"success": False, "notebook_path": notebook_path}

    request(notebook_server, command_name, data=data)

    return None
def get_server_for_notebook(notebook_str: str) -> Optional[str]:
    # Normalize to notebook path
    notebook_str = notebook_str.replace(f".{SYNC_EXTENSION}.py",
                                        f".{SYNC_EXTENSION}.ipynb")
    J_LOGGER.debug("Finding server for notebook_str, script_path: {}",
                   notebook_str)

    notebook_path = Path(notebook_str)

    def get_score_for_name(registered_name: str) -> int:
        """
        Note that it is matching on parts of a path

        Returns the consecutive count of matching parts of a path, from the end toward the start.

        registered ['tmp', 'notebooks', 'myfile.py']
        notebook   ['opt', 'notebooks', 'myfile.py']
         -> 2

        registered ['a', 'b', 'c']
        notebook   ['a', 'b', 'd']
         -> 0

        """
        return len(
            get_matching_tail_tokens(notebook_path.parts,
                                     Path(registered_name).parts))

    score_by_name = {
        x: get_score_for_name(x)
        for x in _REGISTERED_SERVERS.keys()
    }
    max_score = max(score_by_name.values())

    if max_score <= 0:
        raise UnableToFindNotebookException(
            f"Could not find server for notebook_str: {notebook_str}")

    # Only found one reasonable notebook.
    best_scores = [k for k, v in score_by_name.items() if v == max_score]

    if len(best_scores) == 1:
        notebook_port = _REGISTERED_SERVERS[best_scores[0]]

        J_LOGGER.debug("Found server at port {}", notebook_port)
        return _make_url(notebook_port)
    else:
        raise UnableToFindNotebookException(
            f"Could not find server for notebook_str: {notebook_str}")
Ejemplo n.º 7
0
def send(file_name: str, line_number: int, *args, **kwargs):
    J_LOGGER.debug("Starting execute request")

    # Always pass absolute path
    file_name = str(Path(file_name).absolute())

    request_obj = partial(ExecuteRequest, file_name=file_name, contents="")

    with open(file_name, "r") as reader:
        lines = reader.readlines()

    cell_index = _find_cell_number(lines, line_number)

    final_request = request_obj(cell_index=cell_index)
    J_LOGGER.info(f"Sending request with {final_request}")
    jupyter_server.request_notebook_command(final_request)
    J_LOGGER.info("... Complete")
Ejemplo n.º 8
0
def get_server_for_notebook(notebook_path: str) -> Optional[str]:
    # Normalize to notebook path
    notebook_path = notebook_path.replace(".synced.py", ".synced.ipynb")

    J_LOGGER.debug("Finding server for notebook_path, script_path: {}", notebook_path)

    potential_notebooks: List[str] = []
    for registered_name in _REGISTERED_SERVERS:
        if registered_name in notebook_path:
            potential_notebooks.append(registered_name)

    if len(potential_notebooks) > 1:
        J_LOGGER.warning("Found more than one notebook {}, {}", notebook_path, potential_notebooks)
        return None
    elif len(potential_notebooks) == 1:
        notebook_port = _REGISTERED_SERVERS[potential_notebooks[0]]

        J_LOGGER.debug("Found server at port {}", notebook_port)
        return f"http://localhost:{notebook_port}"
    else:
        J_LOGGER.warning("Could not find server for notebook_path: {}", notebook_path)
        return None
Ejemplo n.º 9
0
 def log_message(self, format, *args):
     J_LOGGER.debug(args)