text
stringlengths
81
112k
Read a notebook represented as text def reads(self, s, **_): """Read a notebook represented as text""" if self.fmt.get('format_name') == 'pandoc': return md_to_notebook(s) lines = s.splitlines() cells = [] metadata, jupyter_md, header_cell, pos = header_to_metadata...
Return the text representation of the notebook def writes(self, nb, metadata=None, **kwargs): """Return the text representation of the notebook""" if self.fmt.get('format_name') == 'pandoc': metadata = insert_jupytext_info_and_filter_metadata(metadata, self.ext, self.implementation) ...
Remove prefix (and space) from line def uncomment_line(line, prefix): """Remove prefix (and space) from line""" if not prefix: return line if line.startswith(prefix + ' '): return line[len(prefix) + 1:] if line.startswith(prefix): return line[len(prefix):] return line
Return encoding and executable lines for a notebook, if applicable def encoding_and_executable(notebook, metadata, ext): """Return encoding and executable lines for a notebook, if applicable""" lines = [] comment = _SCRIPT_EXTENSIONS.get(ext, {}).get('comment') jupytext_metadata = metadata.get('jupytex...
Update the notebook metadata to include Jupytext information, and filter the notebook metadata according to the default or user filter def insert_jupytext_info_and_filter_metadata(metadata, ext, text_format): """Update the notebook metadata to include Jupytext information, and filter the notebook metadata ...
Return the text header corresponding to a notebook, and remove the first cell of the notebook if it contained the header def metadata_and_cell_to_header(notebook, metadata, text_format, ext): """ Return the text header corresponding to a notebook, and remove the first cell of the notebook if it contain...
Return the metadata, a boolean to indicate if a jupyter section was found, the first cell of notebook if some metadata is found outside of the jupyter section, and next loc in text def header_to_metadata_and_cell(lines, header_prefix, ext=None): """ Return the metadata, a boolean to indicate if a jupyter ...
Execute the given bash command def system(*args, **kwargs): """Execute the given bash command""" kwargs.setdefault('stdout', subprocess.PIPE) proc = subprocess.Popen(args, **kwargs) out, _ = proc.communicate() if proc.returncode: raise SystemExit(proc.returncode) return out.decode('utf-...
Parse Yes/No/Default string https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse def str2bool(value): """Parse Yes/No/Default string https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse""" if value.lower() in ('yes', 'true', 't', 'y', '1'): ...
Command line parser for jupytext def parse_jupytext_args(args=None): """Command line parser for jupytext""" parser = argparse.ArgumentParser( description='Jupyter notebooks as markdown documents, Julia, Python or R scripts', formatter_class=argparse.RawTextHelpFormatter) # Input parser...
Entry point for the jupytext script def jupytext_cli(args=None): """Entry point for the jupytext script""" try: jupytext(args) except (ValueError, TypeError, IOError) as err: sys.stderr.write('[jupytext] Error: ' + str(err) + '\n') exit(1)
Internal implementation of Jupytext command line def jupytext(args=None): """Internal implementation of Jupytext command line""" args = parse_jupytext_args(args) def log(text): if not args.quiet: sys.stdout.write(text + '\n') if args.version: log(__version__) retur...
Return the list of modified and deleted ipynb files in the git index that match the given format def notebooks_in_git_index(fmt): """Return the list of modified and deleted ipynb files in the git index that match the given format""" git_status = system('git', 'status', '--porcelain') re_modified = re.compi...
Display the paired paths for this notebook def print_paired_paths(nb_file, fmt): """Display the paired paths for this notebook""" notebook = readf(nb_file, fmt) formats = notebook.metadata.get('jupytext', {}).get('formats') if formats: for path, _ in paired_paths(nb_file, fmt, formats): ...
Update recursively a (nested) dictionary with the content of another. Inspired from https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth def recursive_update(target, update): """ Update recursively a (nested) dictionary with the content of another. Inspired from ...
Apply the desired format options to the format description fmt def set_format_options(fmt, format_options): """Apply the desired format options to the format description fmt""" if not format_options: return for opt in format_options: try: key, value = opt.split('=') exc...
Add prefix and suffix information from jupytext.formats if format and path matches def set_prefix_and_suffix(fmt, notebook, nb_file): """Add prefix and suffix information from jupytext.formats if format and path matches""" for alt_fmt in long_form_multiple_formats(notebook.metadata.get('jupytext', {}).get('for...
Update the notebook with the inputs and outputs of the most recent paired files def load_paired_notebook(notebook, fmt, nb_file, log): """Update the notebook with the inputs and outputs of the most recent paired files""" formats = notebook.metadata.get('jupytext', {}).get('formats') if not formats: ...
Pipe the notebook, in the desired representation, to the given command. Update the notebook with the returned content if desired. def pipe_notebook(notebook, command, fmt='py:percent', update=True, preserve_outputs=True): """Pipe the notebook, in the desired representation, to the given command. Update the not...
Remove prefix and space, or only prefix, when possible def uncomment(lines, prefix='#'): """Remove prefix and space, or only prefix, when possible""" if not prefix: return lines prefix_and_space = prefix + ' ' length_prefix = len(prefix) length_prefix_and_space = len(prefix_and_space) r...
Is the paragraph fully commented? def paragraph_is_fully_commented(lines, comment, main_language): """Is the paragraph fully commented?""" for i, line in enumerate(lines): if line.startswith(comment): if line.startswith((comment + ' %', comment + ' ?', comment + ' !')) and is_magic(line, ma...
Is the next unescaped line indented? def next_code_is_indented(lines): """Is the next unescaped line indented?""" for line in lines: if _BLANK_LINE.match(line) or _PY_COMMENT.match(line): continue return _PY_INDENTED.match(line) return False
How many blank lines between end of cell marker and next cell? def count_lines_to_next_cell(cell_end_marker, next_cell_start, total, explicit_eoc): """How many blank lines between end of cell marker and next cell?""" if cell_end_marker < total: lines_to_next_cell = next_cell_start - cell_end_marker ...
Are the two last lines blank, and not the third last one? def last_two_lines_blank(source): """Are the two last lines blank, and not the third last one?""" if len(source) < 3: return False return not _BLANK_LINE.match(source[-3]) and _BLANK_LINE.match(source[-2]) and _BLANK_LINE.match(source[-1])
Read one cell from the given lines, and return the cell, plus the position of the next cell def read(self, lines): """Read one cell from the given lines, and return the cell, plus the position of the next cell """ # Do we have an explicit code marker on the first line? ...
Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary. def metadata_and_language_from_option_line(self, line): """Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.""" ...
Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start def find_cell_content(self, lines): """Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start""" cell_end_marker, next_cell_start, self.explic...
Return position of end of cell marker, and position of first line after cell def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.in_region: self.cell_type = 'markdown' for i, line in enumerate...
Return position of end of cell marker, and position of first line after cell def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.metadata is None and lines[0].startswith("#'"): self.cell_type = 'markdown'...
Return position of end of cell marker, and position of first line after cell def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.metadata is None and not (self.cell_marker_end and self.end_code_re.match(lines[0])) \ ...
Find the end of the region started with start and end markers def find_region_end(self, lines): """Find the end of the region started with start and end markers""" if self.metadata and 'cell_type' in self.metadata: self.cell_type = self.metadata.pop('cell_type') else: se...
Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary. def metadata_and_language_from_option_line(self, line): """Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.""" ...
Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start def find_cell_content(self, lines): """Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start""" cell_end_marker, next_cell_start, explicit_eo...
Return position of end of cell marker, and position of first line after cell def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.metadata and 'cell_type' in self.metadata: self.cell_type = self.metadata....
Does this line starts a new markdown cell? Then, return the cell marker def start_of_new_markdown_cell(self, line): """Does this line starts a new markdown cell? Then, return the cell marker""" for empty_markdown_cell in ['""', "''"]: if line == empty_markdown_cell: ...
Return position of end of cell, and position of first line after cell, and whether there was an explicit end of cell marker def find_cell_end(self, lines): """Return position of end of cell, and position of first line after cell, and whether there was an explicit end of cell mar...
Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start def find_cell_content(self, lines): """Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start""" cell_end_marker, next_cell_start, explicit_eo...
Given a path and options for a format (ext, suffix, prefix), return the corresponding base path def base_path(main_path, fmt): """Given a path and options for a format (ext, suffix, prefix), return the corresponding base path""" if not fmt: return os.path.splitext(main_path)[0] fmt = long_form_one...
Return the full path for the notebook, given the base path def full_path(base, fmt): """Return the full path for the notebook, given the base path""" ext = fmt['extension'] suffix = fmt.get('suffix') prefix = fmt.get('prefix') full = base if prefix: prefix_dir, prefix_file_name = os.p...
Return the base path and the format corresponding to the given path def find_base_path_and_format(main_path, formats): """Return the base path and the format corresponding to the given path""" for fmt in formats: try: return base_path(main_path, fmt), fmt except InconsistentPath: ...
Return the list of paired notebooks, given main path, and the list of formats def paired_paths(main_path, fmt, formats): """Return the list of paired notebooks, given main path, and the list of formats""" if not formats: return [(main_path, {'extension': os.path.splitext(main_path)[1]})] formats =...
Convert language and metadata information to their rmd representation :param language: :param metadata: :return: def metadata_to_rmd_options(language, metadata): """ Convert language and metadata information to their rmd representation :param language: :param metadata: :return: """ ...
Update metadata using the _BOOLEAN_OPTIONS_DICTIONARY mapping :param name: option name :param value: option value :param metadata: :return: def update_metadata_from_rmd_options(name, value, metadata): """ Update metadata using the _BOOLEAN_OPTIONS_DICTIONARY mapping :param name: option name...
Given a R markdown option line, returns a list of pairs name,value :param line: :return: def parse_rmd_options(line): """ Given a R markdown option line, returns a list of pairs name,value :param line: :return: """ parsing_context = ParsingContext(line) result = [] prev_char = ...
Parse rmd options and return a metadata dictionary :param options: :return: def rmd_options_to_metadata(options): """ Parse rmd options and return a metadata dictionary :param options: :return: """ options = re.split(r'\s|,', options, 1) if len(options) == 1: language = opti...
Encode {'class':None, 'key':'value'} into 'class key="value"' def metadata_to_md_options(metadata): """Encode {'class':None, 'key':'value'} into 'class key="value"' """ return ' '.join(["{}={}".format(key, dumps(metadata[key])) if metadata[key] is not None else key for key in metadata])
Parse 'python class key="value"' into [('python', None), ('class', None), ('key', 'value')] def parse_md_code_options(options): """Parse 'python class key="value"' into [('python', None), ('class', None), ('key', 'value')]""" metadata = [] while options: name_and_value = re.split(r'[\s=]+', option...
Parse markdown options and return language and metadata def md_options_to_metadata(options): """Parse markdown options and return language and metadata""" metadata = parse_md_code_options(options) if metadata: language = metadata[0][0] for lang in _JUPYTER_LANGUAGES + ['julia', 'scheme', '...
Evaluate given metadata to a python object, if possible def try_eval_metadata(metadata, name): """Evaluate given metadata to a python object, if possible""" value = metadata[name] if not isinstance(value, (str, unicode)): return if (value.startswith('"') and value.endswith('"')) or (value.start...
Read metadata from its json representation def json_options_to_metadata(options, add_brackets=True): """Read metadata from its json representation""" try: options = loads('{' + options + '}' if add_brackets else options) return options except ValueError: return {}
Is the cell active for the given file extension? def is_active(ext, metadata): """Is the cell active for the given file extension?""" if metadata.get('run_control', {}).get('frozen') is True: return False if 'active' not in metadata: return True return ext.replace('.', '') in re.split('...
Parse double percent options def double_percent_options_to_metadata(options): """Parse double percent options""" matches = _PERCENT_CELL.findall('# %%' + options) # Fail safe when regexp matching fails #116 # (occurs e.g. if square brackets are found in the title) if not matches: return {'...
Metadata to double percent lines def metadata_to_double_percent_options(metadata): """Metadata to double percent lines""" options = [] if 'cell_depth' in metadata: options.append('%' * metadata.pop('cell_depth')) if 'title' in metadata: options.append(metadata.pop('title')) if 'cell...
Currently inside an expression def in_global_expression(self): """Currently inside an expression""" return (self.parenthesis_count == 0 and self.curly_bracket_count == 0 and self.square_bracket_count == 0 and not self.in_single_quote and not self.in_double_quote)
Update parenthesis counters def count_special_chars(self, char, prev_char): """Update parenthesis counters""" if char == '(': self.parenthesis_count += 1 elif char == ')': self.parenthesis_count -= 1 if self.parenthesis_count < 0: raise RMarkd...
Return the implementation for the desired format def get_format_implementation(ext, format_name=None): """Return the implementation for the desired format""" # remove pre-extension if any ext = '.' + ext.split('.')[-1] formats_for_extension = [] for fmt in JUPYTEXT_FORMATS: if fmt.extensio...
Return the header metadata def read_metadata(text, ext): """Return the header metadata""" ext = '.' + ext.split('.')[-1] lines = text.splitlines() if ext in ['.md', '.Rmd']: comment = '' else: comment = _SCRIPT_EXTENSIONS.get(ext, {}).get('comment', '#') metadata, _, _, _ = he...
Return the format of the file, when that information is available from the metadata def read_format_from_metadata(text, ext): """Return the format of the file, when that information is available from the metadata""" metadata = read_metadata(text, ext) rearrange_jupytext_metadata(metadata) return format...
Guess the format and format options of the file, given its extension and content def guess_format(text, ext): """Guess the format and format options of the file, given its extension and content""" lines = text.splitlines() metadata = read_metadata(text, ext) if ('jupytext' in metadata and set(metadat...
Guess the format of the notebook, based on its content #148 def divine_format(text): """Guess the format of the notebook, based on its content #148""" try: nbformat.reads(text, as_version=4) return 'ipynb' except nbformat.reader.NotJSONError: pass lines = text.splitlines() ...
Raise if file version in source file would override outputs def check_file_version(notebook, source_path, outputs_path): """Raise if file version in source file would override outputs""" if not insert_or_test_version_number(): return _, ext = os.path.splitext(source_path) if ext.endswith('.ipy...
Return the format name for that extension def format_name_for_ext(metadata, ext, cm_default_formats=None, explicit_default=True): """Return the format name for that extension""" # Is the format information available in the text representation? text_repr = metadata.get('jupytext', {}).get('text_representati...
Do the two (long representation) of formats target the same file? def identical_format_path(fmt1, fmt2): """Do the two (long representation) of formats target the same file?""" for key in ['extension', 'prefix', 'suffix']: if fmt1.get(key) != fmt2.get(key): return False return True
Update the jupytext_format metadata in the Jupyter notebook def update_jupytext_formats_metadata(metadata, new_format): """Update the jupytext_format metadata in the Jupyter notebook""" new_format = long_form_one_format(new_format) formats = long_form_multiple_formats(metadata.get('jupytext', {}).get('form...
Convert the jupytext_formats metadata entry to jupytext/formats, etc. See #91 def rearrange_jupytext_metadata(metadata): """Convert the jupytext_formats metadata entry to jupytext/formats, etc. See #91""" # Backward compatibility with nbrmd for key in ['nbrmd_formats', 'nbrmd_format_version']: if ...
Parse 'sfx.py:percent' into {'suffix':'sfx', 'extension':'py', 'format_name':'percent'} def long_form_one_format(jupytext_format, metadata=None, update=None): """Parse 'sfx.py:percent' into {'suffix':'sfx', 'extension':'py', 'format_name':'percent'}""" if isinstance(jupytext_format, dict): if update: ...
Convert a concise encoding of jupytext.formats to a list of formats, encoded as dictionaries def long_form_multiple_formats(jupytext_formats, metadata=None): """Convert a concise encoding of jupytext.formats to a list of formats, encoded as dictionaries""" if not jupytext_formats: return [] if not...
Represent one jupytext format as a string def short_form_one_format(jupytext_format): """Represent one jupytext format as a string""" if not isinstance(jupytext_format, dict): return jupytext_format fmt = jupytext_format['extension'] if 'suffix' in jupytext_format: fmt = jupytext_format...
Convert jupytext formats, represented as a list of dictionaries, to a comma separated list def short_form_multiple_formats(jupytext_formats): """Convert jupytext formats, represented as a list of dictionaries, to a comma separated list""" if not isinstance(jupytext_formats, list): return jupytext_forma...
Validate extension and options for the given format def validate_one_format(jupytext_format): """Validate extension and options for the given format""" if not isinstance(jupytext_format, dict): raise JupytextFormatError('Jupytext format should be a dictionary') for key in jupytext_format: ...
Remove characters that may be changed when reformatting the text with black def black_invariant(text, chars=None): """Remove characters that may be changed when reformatting the text with black""" if chars is None: chars = [' ', '\t', '\n', ',', "'", '"', '(', ')', '\\'] for char in chars: ...
Copy outputs of the second notebook into the first one, for cells that have matching inputs def combine_inputs_with_outputs(nb_source, nb_outputs, fmt=None): """Copy outputs of the second notebook into the first one, for cells that have matching inputs""" output_code_cells = [cell for cell in nb_outpu...
Return the kernel specification for the first kernel with a matching language def kernelspec_from_language(language): """Return the kernel specification for the first kernel with a matching language""" try: for name in find_kernel_specs(): kernel_specs = get_kernel_spec(name) if...
Return the preferred format for the given extension def preferred_format(incomplete_format, preferred_formats): """Return the preferred format for the given extension""" incomplete_format = long_form_one_format(incomplete_format) if 'format_name' in incomplete_format: return incomplete_format ...
Remove the current notebook from the list of paired notebooks def drop_paired_notebook(self, path): """Remove the current notebook from the list of paired notebooks""" if path not in self.paired_notebooks: return fmt, formats = self.paired_notebooks.pop(path) prev_paired_pa...
Update the list of paired notebooks to include/update the current pair def update_paired_notebooks(self, path, fmt, formats): """Update the list of paired notebooks to include/update the current pair""" if not formats: self.drop_paired_notebook(path) return new_paired_p...
Set default format option def set_default_format_options(self, format_options, read=False): """Set default format option""" if self.default_notebook_metadata_filter: format_options.setdefault('notebook_metadata_filter', self.default_notebook_metadata_filter) if self.default_cell_met...
Return the default formats, if they apply to the current path #157 def default_formats(self, path): """Return the default formats, if they apply to the current path #157""" formats = long_form_multiple_formats(self.default_jupytext_formats) for fmt in formats: try: b...
Create the prefix dir, if missing def create_prefix_dir(self, path, fmt): """Create the prefix dir, if missing""" create_prefix_dir(self._get_os_path(path.strip('/')), fmt)
Save the file model and return the model with no content. def save(self, model, path=''): """Save the file model and return the model with no content.""" if model['type'] != 'notebook': return super(TextFileContentsManager, self).save(model, path) nbk = model['content'] try...
Takes a path for an entity and returns its model def get(self, path, content=True, type=None, format=None, load_alternative_format=True): """ Takes a path for an entity and returns its model""" path = path.strip('/') ext = os.path.splitext(path)[1] # Not a notebook? if not self...
Trust the current notebook def trust_notebook(self, path): """Trust the current notebook""" if path.endswith('.ipynb') or path not in self.paired_notebooks: super(TextFileContentsManager, self).trust_notebook(path) return fmt, formats = self.paired_notebooks[path] ...
Rename the current notebook, as well as its alternative representations def rename_file(self, old_path, new_path): """Rename the current notebook, as well as its alternative representations""" if old_path not in self.paired_notebooks: try: # we do not know yet if this is a p...
Is the first non-empty, non-commented line of the cell either a function or a class? def next_instruction_is_function_or_class(lines): """Is the first non-empty, non-commented line of the cell either a function or a class?""" for i, line in enumerate(lines): if not line.strip(): # empty line ...
Does the last line of the cell belong to an indented code? def cell_ends_with_function_or_class(lines): """Does the last line of the cell belong to an indented code?""" non_quoted_lines = [] parser = StringParser('python') for line in lines: if not parser.is_quoted(): non_quoted_lin...
Is the last line of the cell a line with code? def cell_ends_with_code(lines): """Is the last line of the cell a line with code?""" if not lines: return False if not lines[-1].strip(): return False if lines[-1].startswith('#'): return False return True
Is there any code in this cell? def cell_has_code(lines): """Is there any code in this cell?""" for i, line in enumerate(lines): stripped_line = line.strip() if stripped_line.startswith('#'): continue # Two consecutive blank lines? if not stripped_line: ...
How many blank lines should be added between the two python paragraphs to make them pep8? def pep8_lines_between_cells(prev_lines, next_lines, ext): """How many blank lines should be added between the two python paragraphs to make them pep8?""" if not next_lines: return 1 if not prev_lines: ...
Cell type, metadata and source from given cell def filtered_cell(cell, preserve_outputs, cell_metadata_filter): """Cell type, metadata and source from given cell""" metadata = copy(cell.metadata) filter_metadata(metadata, cell_metadata_filter, _IGNORE_CELL_METADATA) filtered = {'cell_type': cell.cell_...
Notebook metadata, filtered for metadata added by Jupytext itself def filtered_notebook_metadata(notebook): """Notebook metadata, filtered for metadata added by Jupytext itself""" metadata = copy(notebook.metadata) metadata = filter_metadata(metadata, notebook.metadata.get('j...
Is the content of two cells the same, except for an optional final blank line? def same_content(ref_source, test_source, allow_removed_final_blank_line): """Is the content of two cells the same, except for an optional final blank line?""" if ref_source == test_source: return True if not allow_remo...
Compare the two notebooks, and raise with a meaningful message that explains the differences, if any def compare_notebooks(notebook_expected, notebook_actual, fmt=None, allow_expected_differences=True, raise_on_first_difference...
Return the source of the current cell, as an array of lines def cell_source(cell): """Return the source of the current cell, as an array of lines""" source = cell.source if source == '': return [''] if source.endswith('\n'): return source.splitlines() + [''] return source.splitlines...
Issues #31 #38: does the cell contain a blank line? In that case we add an end-of-cell marker def endofcell_marker(source, comment): """Issues #31 #38: does the cell contain a blank line? In that case we add an end-of-cell marker""" endofcell = '-' while True: endofcell_re = re.compile(r'...
Is this cell a code cell? def is_code(self): """Is this cell a code cell?""" if self.cell_type == 'code': return True if self.cell_type == 'raw' and 'active' in self.metadata: return True return False
Return the text representation for the cell def cell_to_text(self): """Return the text representation for the cell""" if self.is_code(): return self.code_to_text() source = copy(self.source) if not self.comment: escape_code_start(source, self.ext, None) ...
Escape the given source, for a markdown cell def markdown_to_text(self, source): """Escape the given source, for a markdown cell""" if self.comment and self.comment != "#'": source = copy(source) comment_magic(source, self.language, self.comment_magics) return comment_l...
Return the text representation of a cell def cell_to_text(self): """Return the text representation of a cell""" if self.cell_type == 'markdown': # Is an explicit region required? if self.metadata or self.cell_reader(self.fmt).read(self.source)[1] < len(self.source): ...
Return the text representation of a code cell def code_to_text(self): """Return the text representation of a code cell""" source = copy(self.source) comment_magic(source, self.language, self.comment_magics) options = [] if self.cell_type == 'code' and self.language: ...
Return the text representation of a code cell def code_to_text(self): """Return the text representation of a code cell""" active = is_active(self.ext, self.metadata) if self.language != self.default_language and 'active' not in self.metadata: active = False source = copy(se...