-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathextract_source_code.js
95 lines (82 loc) · 2.83 KB
/
extract_source_code.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// var fs = require('fs');
// const args = process.argv.slice(2);
// const filename = args[0];
// const programSrc = fs.readFileSync(filename).toString();
// const programJson = JSON.parse(programSrc);
// if (programJson.cells == undefined) {
// return;
// }
// var last_exe_cnt = -1;
// for (let cell of programJson.cells) {
// if (cell.execution_count == null) {
// cell.execution_count = last_exe_cnt + 10;
// }
// last_exe_cnt = cell.execution_count;
// }
// let res = "";
// for (let cell of programJson.cells) {
// if (cell.cell_type === 'code') {
// var sourceCode = "";
// for (let line of cell.source) {
// if (line[0] != '#' && line[0] != '%' && line[0] != '!' && line != "") {
// sourceCode += line;
// }
// }
// if (sourceCode != ""){
// res += "##" + cell.execution_count + "@@";
// res += sourceCode;
// }
// }
// }
// var new_name = filename.substring(0, filename.lastIndexOf('.'));
// fs.writeFile(new_name + '_source_code.txt', res, function (err) {
// if (err) throw err;
// });
var fs = require('fs');
const args = process.argv.slice(2);
const path = args[0];
let num_notebooks = 0;
function getExt(filename){
return filename.substring(filename.lastIndexOf('.')+1, filename.length);
}
const start = Date.now();
fs.readdirSync(path).forEach(file => {
if (getExt(file) === "ipynb") {
let filename = path + file;
const programSrc = fs.readFileSync(filename).toString();
const programJson = JSON.parse(programSrc);
if (programJson.cells == undefined) {
return;
}
var last_exe_cnt = -1;
for (let cell of programJson.cells) {
if (cell.execution_count == null) {
cell.execution_count = last_exe_cnt + 10;
}
last_exe_cnt = cell.execution_count;
}
let res = "";
for (let cell of programJson.cells) {
if (cell.cell_type === 'code') {
var sourceCode = "";
for (let line of cell.source) {
if (line[0] != '#' && line[0] != '%' && line[0] != '!' && line != "") {
sourceCode += line;
}
}
if (sourceCode != ""){
res += "#?#?" + cell.execution_count + "@@";
res += sourceCode;
}
}
}
var new_name = filename.substring(0, filename.lastIndexOf('.'));
fs.writeFile(new_name + '_source_code.txt', res, function (err) {
if (err) throw err;
});
num_notebooks += 1;
}
});
const millis = Date.now() - start;
console.log("Finished extracting source code for " + num_notebooks + " notebooks!");
console.log("Time used = " + millis + " ms!");