Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 39558
1
#!/usr/bin/env python
2
# this script converts an html-exported sagews file back to sagews
3
4
from __future__ import print_function, unicode_literals
5
6
import sys
7
import os
8
import urllib
9
import base64
10
11
def extract(in_fn, out_fn):
12
print("extracting from '{in_fn}' to '{out_fn}'".format(**locals()))
13
start = 'href="data:application/octet-stream'
14
def get_href():
15
for line in open(in_fn, 'r'):
16
if '<a' in line and start in line and 'download=' in line:
17
i = line.find(start)
18
href = line[i:].split('"', 2)[1]
19
return href
20
21
href = get_href()
22
if href is None:
23
raise Exception("embedded sagews file not found!")
24
base64str = href.split(',', 1)
25
if len(base64str) <= 1:
26
raise Exception("unable to parse href data")
27
data = base64.b64decode(urllib.unquote(base64str[1]))
28
open(out_fn, 'w').write(data)
29
30
def main():
31
if len(sys.argv) <= 1:
32
raise Exception("first argument needs to be the converted HTML file (likely '*.sagews.html')")
33
in_fn = sys.argv[1]
34
if len(sys.argv) == 2:
35
# detecting a 'filename.sagews.html' pattern
36
in_split = in_fn.rsplit('.', 2)
37
if len(in_split) >= 3 and in_split[-2] == 'sagews':
38
out_fn = '.'.join(in_split[:-1])
39
else:
40
out_fn = in_fn + '.sagews'
41
else:
42
out_fn = sys.argv[2]
43
extract(in_fn, out_fn)
44
45
if __name__ == '__main__':
46
main()
47