| 1 | #!/usr/bin/env python |
| 2 | # -*- coding: utf-8 -*- |
| 3 | |
| 4 | import sys |
| 5 | import tarfile |
| 6 | import os |
| 7 | import shutil |
| 8 | import codecs |
| 9 | import tempfile |
| 10 | from sagenb.misc.worksheet2rst import worksheet2rst |
| 11 | |
| 12 | def process_sws(file_name): |
| 13 | |
| 14 | sws_file = tarfile.open(file_name, mode='r:bz2') |
| 15 | #TODO: python complains about using tempnam, but I don't |
| 16 | #know hot to fix it or see any danger |
| 17 | # tempname = os.tempnam('.') |
| 18 | tempname = os.path.join(tempfile.gettempdir(), file_name) |
| 19 | sws_file.extractall(tempname) |
| 20 | base_name = os.path.splitext(file_name)[0] |
| 21 | |
| 22 | #Images |
| 23 | images_dir = base_name + '_media' |
| 24 | if not os.path.exists(images_dir): |
| 25 | os.mkdir(images_dir) |
| 26 | |
| 27 | #"data" dir |
| 28 | data_path = os.path.join(tempname,'sage_worksheet','data') |
| 29 | if os.path.exists(data_path): |
| 30 | for image in os.listdir(data_path): |
| 31 | try: |
| 32 | shutil.move(os.path.join(data_path, image), images_dir) |
| 33 | except shutil.Error: |
| 34 | pass |
| 35 | |
| 36 | #cells |
| 37 | cells_path = os.path.join(tempname,'sage_worksheet','cells') |
| 38 | for cell in os.listdir(cells_path): |
| 39 | cell_path = os.path.join(cells_path, cell) |
| 40 | for image in os.listdir(cell_path): |
| 41 | shutil.copy2(os.path.join(cell_path, image), images_dir) |
| 42 | shutil.move(os.path.join(images_dir, image), |
| 43 | os.path.join(images_dir, 'cell_%s_%s'%(cell,image))) |
| 44 | |
| 45 | #read html file, parse it, write rst file |
| 46 | file = codecs.open(os.path.join('.',tempname,'sage_worksheet','worksheet.html'), |
| 47 | mode='r', |
| 48 | encoding='utf-8') |
| 49 | html_text = file.read() |
| 50 | file.close() |
| 51 | rst_text = worksheet2rst(html_text, images_dir = images_dir) |
| 52 | rst_file = base_name + '.rst' |
| 53 | out_file = codecs.open(rst_file, mode='w', |
| 54 | encoding='utf-8') |
| 55 | out_file.write(rst_text) |
| 56 | out_file.close() |
| 57 | |
| 58 | shutil.rmtree(tempname) |
| 59 | |
| 60 | if __name__=='__main__': |
| 61 | if len(sys.argv)<=1: |
| 62 | print 'First argument should be a sws file' |
| 63 | sys.exit() |
| 64 | for file_name in sys.argv[1:]: |
| 65 | print file_name |
| 66 | process_sws(file_name) |
| 67 | |
| 68 | |