ipy2inc.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import argparse
  2. import json
  3. import sys
  4. import logging
  5. log = logging.getLogger(__name__)
  6. # log.setLevel(logging.WARN)
  7. log.setLevel(logging.INFO)
  8. # log.setLevel(logging.DEBUG)
  9. class NotebookToTextApp(object):
  10. @classmethod
  11. def __init__(self, sys_argv=None):
  12. if sys_argv is None:
  13. sys_argv = sys.argv[1:]
  14. parser = argparse.ArgumentParser()
  15. parser.add_argument('input_path',
  16. help='.ipynb file to parse',
  17. # default=256,
  18. # type=int,
  19. )
  20. # parser.add_argument('--num-workers',
  21. # help='Number of worker processes for background data loading',
  22. # default=8,
  23. # type=int,
  24. # )
  25. # parser.add_argument('--scaled',
  26. # help="Scale the CT chunks to square voxels.",
  27. # default=False,
  28. # action='store_true',
  29. # )
  30. self.cli_args = parser.parse_args(sys_argv)
  31. def main(self):
  32. log.info("Starting {}, {}".format(type(self).__name__, self.cli_args))
  33. with open(self.cli_args.input_path) as nb_file:
  34. nb = json.load(nb_file)
  35. with open(self.cli_args.input_path.replace('.ipynb', '.nbinclude'), 'w', encoding='utf8') as out_file:
  36. for cell_index, cell_dict in enumerate(nb['cells']):
  37. if cell_dict['cell_type'] != 'code':
  38. continue
  39. cell_index += 1
  40. print('# tag::cell_{}'.format(cell_index), file=out_file)
  41. print('# In[{}]:'.format(cell_index), file=out_file)
  42. print('# tag::cell_{}_code'.format(cell_index), file=out_file)
  43. print(''.join(cell_dict['source']), file=out_file)
  44. print('# end::cell_{}_code'.format(cell_index), file=out_file)
  45. print('', file=out_file)
  46. print('# Out[{}]:'.format(cell_index), file=out_file)
  47. print('# tag::cell_{}_output'.format(cell_index), file=out_file)
  48. for output_dict in cell_dict['outputs']:
  49. output_list = output_dict.get('data', {}).get('text/plain', [])
  50. if output_list:
  51. print(''.join(output_list), file=out_file)
  52. print('# end::cell_{}_output'.format(cell_index), file=out_file)
  53. print('# end::cell_{}'.format(cell_index), file=out_file)
  54. print('\n', file=out_file)
  55. if __name__ == '__main__':
  56. sys.exit(NotebookToTextApp().main() or 0)