Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/smc_pyutil/smc_pyutil/sagews2ipynb.py
Views: 285
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
# This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
4
# License: AGPLv3 s.t. "Commons Clause" – read LICENSE.md for details
5
6
from __future__ import absolute_import, print_function
7
8
import argparse, codecs, json, os
9
from . import sagews2pdf
10
11
12
def ipynb_string_list(s):
13
v = s.split('\n')
14
for i in range(len(v) - 1):
15
v[i] += '\n'
16
return v
17
18
19
class Worksheet(sagews2pdf.Worksheet):
20
def ipynb(self):
21
obj = {
22
"metadata": {
23
"kernelspec": {
24
"display_name": "SageMath",
25
"language": "python",
26
"name": "sagemath"
27
},
28
"language_info": {
29
"codemirror_mode": {
30
"name": "ipython",
31
"version": 2
32
},
33
"file_extension": ".py",
34
"mimetype": "text/x-python",
35
"name": "python",
36
"nbconvert_exporter": "python",
37
"pygments_lexer": "ipython2",
38
"version": "2.7.12+"
39
}
40
},
41
"nbformat": 4,
42
"nbformat_minor": 4
43
}
44
obj['cells'] = self.ipynb_cells()
45
return obj
46
47
def ipynb_cells(self):
48
return [self.ipynb_cell(cell) for cell in self._cells]
49
50
def ipynb_cell(self, cell):
51
x = {"metadata": {"collapsed": False}}
52
source = cell.input.strip()
53
if source.startswith('%md'):
54
x['cell_type'] = 'markdown'
55
source = '\n'.join(source.split('\n')[1:])
56
else:
57
x['cell_type'] = 'code'
58
x['source'] = ipynb_string_list(source)
59
return x
60
61
62
def sagews_to_pdf(filename):
63
base = os.path.splitext(filename)[0]
64
ipynb = base + ".ipynb"
65
print("converting: %s --> %s" % (filename, ipynb))
66
W = Worksheet(filename)
67
codecs.open(ipynb, 'w', 'utf8').write(json.dumps(W.ipynb(), indent=1))
68
print("Created", ipynb)
69
70
71
def main():
72
parser = argparse.ArgumentParser(
73
description="convert a sagews worksheet to a Jupyter Notebook")
74
parser.add_argument("filename",
75
nargs='+',
76
help="name of sagews files (required)",
77
type=str)
78
args = parser.parse_args()
79
80
for filename in args.filename:
81
sagews_to_pdf(filename)
82
83
84
if __name__ == "__main__":
85
main()
86
87