Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 39558
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
"""
5
Copyright (c) 2017, SageMath, Inc..
6
7
All rights reserved.
8
"""
9
10
import argparse, codecs, json, os
11
12
import sagews2pdf
13
14
def ipynb_string_list(s):
15
v = s.split('\n')
16
for i in range(len(v)-1):
17
v[i] += '\n'
18
return v
19
20
class Worksheet(sagews2pdf.Worksheet):
21
def ipynb(self):
22
obj = {
23
"metadata": {
24
"kernelspec": {
25
"display_name": "SageMath",
26
"language": "python",
27
"name": "sagemath"
28
},
29
"language_info": {
30
"codemirror_mode": {
31
"name": "ipython",
32
"version": 2
33
},
34
"file_extension": ".py",
35
"mimetype": "text/x-python",
36
"name": "python",
37
"nbconvert_exporter": "python",
38
"pygments_lexer": "ipython2",
39
"version": "2.7.12+"
40
}
41
},
42
"nbformat": 4,
43
"nbformat_minor": 0
44
}
45
obj['cells'] = self.ipynb_cells()
46
return obj
47
48
def ipynb_cells(self):
49
return [self.ipynb_cell(cell) for cell in self._cells]
50
51
def ipynb_cell(self, cell):
52
x = {"metadata":{"collapsed": False}}
53
source = cell.input.strip()
54
if source.startswith('%md'):
55
x['cell_type'] = 'markdown'
56
source = '\n'.join(source.split('\n')[1:])
57
else:
58
x['cell_type'] = 'code'
59
x['source'] = ipynb_string_list(source)
60
return x
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
def main():
71
parser = argparse.ArgumentParser(description="convert a sagews worksheet to a Jupyter Notebook")
72
parser.add_argument("filename", nargs='+', help="name of sagews files (required)", type=str)
73
args = parser.parse_args()
74
75
for filename in args.filename:
76
sagews_to_pdf(filename)
77
78
if __name__ == "__main__":
79
main()
80