Path: blob/master/src/smc_pyutil/smc_pyutil/sagews2ipynb.py
Views: 285
#!/usr/bin/env python31# -*- coding: utf-8 -*-2# This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.3# License: AGPLv3 s.t. "Commons Clause" – read LICENSE.md for details45from __future__ import absolute_import, print_function67import argparse, codecs, json, os8from . import sagews2pdf91011def ipynb_string_list(s):12v = s.split('\n')13for i in range(len(v) - 1):14v[i] += '\n'15return v161718class Worksheet(sagews2pdf.Worksheet):19def ipynb(self):20obj = {21"metadata": {22"kernelspec": {23"display_name": "SageMath",24"language": "python",25"name": "sagemath"26},27"language_info": {28"codemirror_mode": {29"name": "ipython",30"version": 231},32"file_extension": ".py",33"mimetype": "text/x-python",34"name": "python",35"nbconvert_exporter": "python",36"pygments_lexer": "ipython2",37"version": "2.7.12+"38}39},40"nbformat": 4,41"nbformat_minor": 442}43obj['cells'] = self.ipynb_cells()44return obj4546def ipynb_cells(self):47return [self.ipynb_cell(cell) for cell in self._cells]4849def ipynb_cell(self, cell):50x = {"metadata": {"collapsed": False}}51source = cell.input.strip()52if source.startswith('%md'):53x['cell_type'] = 'markdown'54source = '\n'.join(source.split('\n')[1:])55else:56x['cell_type'] = 'code'57x['source'] = ipynb_string_list(source)58return x596061def sagews_to_pdf(filename):62base = os.path.splitext(filename)[0]63ipynb = base + ".ipynb"64print("converting: %s --> %s" % (filename, ipynb))65W = Worksheet(filename)66codecs.open(ipynb, 'w', 'utf8').write(json.dumps(W.ipynb(), indent=1))67print("Created", ipynb)686970def main():71parser = argparse.ArgumentParser(72description="convert a sagews worksheet to a Jupyter Notebook")73parser.add_argument("filename",74nargs='+',75help="name of sagews files (required)",76type=str)77args = parser.parse_args()7879for filename in args.filename:80sagews_to_pdf(filename)818283if __name__ == "__main__":84main()858687