forked from visualpython/visualpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcom_Config.js
More file actions
520 lines (483 loc) · 19.3 KB
/
Copy pathcom_Config.js
File metadata and controls
520 lines (483 loc) · 19.3 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/*
* Project Name : Visual Python
* Description : GUI-based Python code generator
* File Name : com_Config.js
* Author : Black Logic
* Note : Configuration and settings control
* License : GNU GPLv3 with Visual Python special exception
* Date : 2021. 09. 16
* Change Date :
*/
//============================================================================
// [CLASS] Configuration
//============================================================================
define([
'./com_Const',
'./com_util',
'./com_interface'
], function(com_Const, com_util, com_interface) {
'use strict';
//========================================================================
// Define Inner Variable
//========================================================================
/**
* Type of mode
*/
const _MODE_TYPE = {
DEVELOP : 0,
RELEASE : 1
}
//========================================================================
// Declare Class
//========================================================================
/**
* Configuration and settings
*/
class Config {
//========================================================================
// Constructor
//========================================================================
constructor(initialData) {
// initial configuration
this.data = {
// Configuration
'vpcfg': {
},
// User defined code for Snippets
'vpudf': {
'default import': [
'import numpy as np',
'import pandas as pd',
'import matplotlib.pyplot as plt',
'%matplotlib inline',
'import seaborn as sns',
'import plotly.express as px'
],
'matplotlib customizing': [
'import matplotlib.pyplot as plt',
'%matplotlib inline',
'',
"plt.rc('figure', figsize=(12, 8))",
'',
'from matplotlib import rcParams',
"rcParams['font.family'] = 'New Gulim'",
"rcParams['font.size'] = 10",
"rcParams['axes.unicode_minus'] = False"
],
'as_float': [
'def as_float(x):',
' """',
" usage: df['col'] = df['col'].apply(as_float)",
' """',
' if not isinstance(x, str):',
' return 0.0',
' else:',
' try:',
' result = float(x)',
' return result',
' except ValueError:',
' return 0.0'
],
'as_int': [
'def as_int(x):',
' """',
" usage: df['col'] = df['col'].apply(as_int)",
' """',
' if not isinstance(x, str):',
' return 0',
' else:',
' try:',
' result = int(x)',
' return result',
' except ValueError:',
' return 0.0'
]
},
'vpimport': [
{ library: 'numpy', alias:'np' },
{ library: 'pandas', alias:'pd' },
{ library: 'matplotlib.pyplot', alias:'plt',
include: [
'%matplotlib inline'
]
},
{ library: 'seaborn', alias:'sns' }
]
}
this.data = {
...this.data,
...initialData
}
this.defaultConfig = {};
this.metadataSettings = {};
this._readDefaultConfig();
}
/**
* Read dejault config
*/
_readDefaultConfig() {
// default values for system-wide configurable parameters
this.defaultConfig = {
indent: 4
};
// default values for per-notebook configurable parameters
this.metadataSettings = {
vp_config_version: '1.0.0',
vp_signature: 'VisualPython',
vp_position: {},
vp_section_display: false,
vp_note_display: true,
vp_menu_width: Config.MENU_MIN_WIDTH,
vp_note_width: Config.BOARD_MIN_WIDTH
};
let vp_width = Config.MENU_MIN_WIDTH + (this.metadataSettings.vp_note_display? Config.BOARD_MIN_WIDTH: 0) + Config.MENU_BOARD_SPACING;
this.metadataSettings['vp_position'] = {
// height: 'calc(100% - 110px)',
// width: vp_width + 'px',
// right: '0px',
// top: '110px',
width: vp_width
}
// merge default config
$.extend(true, this.defaultConfig, this.metadataSettings);
}
/**
* Read kernel functions for using visualpython
* - manually click restart menu (MenuFrame.js)
* - automatically restart on jupyter kernel restart (loadVisualpython.js)
*/
readKernelFunction() {
var libraryList = [
'printCommand.py',
'fileNaviCommand.py',
'pandasCommand.py',
'variableCommand.py',
'userCommand.py'
];
let promiseList = [];
libraryList.forEach(libName => {
var libPath = com_Const.PYTHON_PATH + libName
$.get(libPath).done(function(data) {
var code_init = data;
promiseList.push(vpKernel.execute(code_init));
}).fail(function() {
console.log('visualpython - failed to read library file', libName);
});
});
// run all promises
let failed = false;
Promise.all(promiseList).then(function(resultObj) {
}).catch(function(resultObj) {
failed = true;
console.log('visualpython - failed to load library', resultObj);
}).finally(function() {
if (!failed) {
console.log('visualpython - loaded libraries', libraryList);
} else {
console.log('visualpython - failed to load libraries');
}
});
}
getMode() {
return Config.serverMode;
}
loadData(configKey = 'vpudf') {
return new Promise(function(resolve, reject) {
Jupyter.notebook.config.load();
Jupyter.notebook.config.loaded.then(function() {
var data = Jupyter.notebook.config.data[configKey];
if (data == undefined) {
data = {};
}
resolve(data);
});
});
};
/**
* Get configuration data (on server)
* @param {String} dataKey
* @param {String} configKey
* @returns
*/
getData(dataKey='', configKey='vpudf') {
return new Promise(function(resolve, reject) {
Jupyter.notebook.config.load();
Jupyter.notebook.config.loaded.then(function() {
var data = Jupyter.notebook.config.data[configKey];
if (data == undefined) {
resolve(data);
return;
}
if (dataKey == '') {
resolve(data);
return;
}
if (Object.keys(data).length > 0) {
resolve(data[dataKey]);
return;
}
reject('No data available.');
});
});
}
getDataSimple(dataKey='', configKey='vpudf') {
Jupyter.notebook.config.load();
var data = Jupyter.notebook.config.data[configKey];
if (data == undefined) {
return undefined;
}
if (dataKey == '') {
return data;
}
if (Object.keys(data).length > 0) {
return data[dataKey];
}
return undefined;
}
/**
* Set configuration data (on server)
* @param {Object} dataObj
* @param {String} configKey
*/
setData(dataObj, configKey='vpudf') {
// set data using key
Jupyter.notebook.config.loaded.then(function() {
Jupyter.notebook.config.update({[configKey]: dataObj});
});
}
removeData(key, configKey = 'vpudf') {
// if set value to null, it removes from config data
Jupyter.notebook.config.loaded.then(function() {
Jupyter.notebook.config.update({[configKey]: {[key]: null}});
});
}
/**
* Get metadata (on jupyter file)
* @param {String} dataKey
* @param {String} configKey
*/
getMetadata(dataKey='', configKey='vp') {
let metadata = Jupyter.notebook.metadata[configKey];
if (metadata) {
// update this metadataSetting
this.metadataSettings = {
...this.metadataSettings,
...metadata
};
// no datakey, return all metadata
if (dataKey == '') {
return metadata;
}
return metadata[dataKey];
}
return {};
}
/**
* Set metadata (on jupyter file)
* @param {Object} dataObj
* @param {String} configKey
*/
setMetadata(dataObj, configKey='vp') {
let oldData = Jupyter.notebook.metadata[configKey];
Jupyter.notebook.metadata[configKey] = {
...oldData,
...dataObj
};
Jupyter.notebook.set_dirty();
// update this metadataSetting
this.metadataSettings = {
...this.metadataSettings,
...dataObj
};
}
/**
* Reset metadata (on jupyter file)
* @param {String} configKey
*/
resetMetadata(configKey='vp') {
Jupyter.notebook.metadata[configKey] = {};
}
/**
* Check vp pypi package version (Promise)
* usage:
* vpConfig.getPackageVersion('visualpython').then(function(version) {
* // do something after loading version
* ...
* }).catch(function(err) {
* // error handling
* ...
* })
*/
getPackageVersion(packName='visualpython') {
let url = `https://pypi.org/pypi/${packName}/json`;
// using the Fetch API
return new Promise(function(resolve, reject) {
try {
fetch(url).then(function (response) {
// if (response.statusCode === 200) {
// return response.json();
// } else if (response.statusCode === 204) {
// throw new Error('No Contents', response);
// } else if (response.statusCode === 404) {
// throw new Error('Page Not Found', response);
// } else if (response.statusCode === 500) {
// throw new Error('Internal Server Error', response);
// } else {
// throw new Error('Unexpected Http Status Code', response);
// }
if (response.ok) {
return response.json();
} else {
throw new Error('Error', response);
}
}).then(function (data) {
resolve(data.info.version);
}).catch(function(err) {
let errMsg = err.message;
if (errMsg.includes('Failed to fetch')) {
errMsg = 'Network connection error';
}
reject(errMsg);
});
} catch (err) {
reject(err);
}
});
}
getVpInstalledVersion() {
return Config.version;
}
checkVpVersion(background=false) {
let that = this;
let nowVersion = this.getVpInstalledVersion();
this.getPackageVersion().then(function(latestVersion) {
if (nowVersion === latestVersion) {
// if it's already up to date
// hide version update icon
$('#vp_versionUpdater').hide();
if (background) {
;
} else {
let msg = com_util.formatString('Visual Python is up to date. ({0})', latestVersion);
com_util.renderInfoModal(msg);
}
// update version_timestamp
that.setData({ 'version_timestamp': new Date().getTime() }, 'vpcfg');
} else {
let msg = com_util.formatString('Visual Python updates are available.<br/>(Latest version: {0} / Your version: {1})',
latestVersion, nowVersion);
// show version update icon
$('#vp_versionUpdater').attr('title', msg.replace('<br/>', ''));
$('#vp_versionUpdater').data('version', latestVersion);
$('#vp_versionUpdater').show();
// render update modal
com_util.renderModal({
title: 'Update version',
message: msg,
buttons: ['Cancel', 'Update'],
defaultButtonIdx: 0,
buttonClass: ['cancel', 'activated'],
finish: function(clickedBtnIdx) {
switch (clickedBtnIdx) {
case 0:
// cancel
break;
case 1:
// update
let info = [
'## Visual Python Upgrade',
'NOTE: ',
'- Refresh your web browser to start a new version.',
'- Save VP Note before refreshing the page.'
];
com_interface.insertCell('markdown', info.join('\n'));
com_interface.insertCell('code', '!pip install visualpython --upgrade');
com_interface.insertCell('code', '!visualpy install');
// update version_timestamp
that.setData({ 'version_timestamp': new Date().getTime() }, 'vpcfg');
// hide updater
$('#vp_versionUpdater').hide();
break;
}
}
});
}
}).catch(function(err) {
if (background) {
vpLog.display(VP_LOG_TYPE.ERROR, 'Version Checker - ' + err);
} else {
com_util.renderAlertModal(err);
}
})
}
getMLDataDict(key = '') {
if (key == '') {
return Config.ML_DATA_DICT;
}
return Config.ML_DATA_DICT[key];
}
getMLDataTypes() {
return Config.ML_DATA_TYPES;
}
}
//========================================================================
// Define static variable
//========================================================================
/**
* FIXME: before release, change it to _MODE_TYPE.RELEASE
*/
// Config.serverMode = _MODE_TYPE.DEVELOP;
Config.serverMode = _MODE_TYPE.RELEASE;
/**
* Version
*/
Config.version = "2.1.0";
/**
* Type of mode
*/
Config.MODE_TYPE = _MODE_TYPE;
/**
* Frame size settings
*/
Config.JUPYTER_HEADER_SPACING = 110;
Config.MENU_MIN_WIDTH = 273;
Config.BOARD_MIN_WIDTH = 263;
Config.MENU_BOARD_SPACING = 5;
Config.VP_MIN_WIDTH = Config.MENU_MIN_WIDTH + Config.BOARD_MIN_WIDTH + Config.MENU_BOARD_SPACING; // = MENU_MIN_WIDTH + BOARD_MIN_WIDTH + MENU_BOARD_SPACING
/**
* Data types using for searching model variables
*/
Config.ML_DATA_DICT = {
'Regression': [
'LinearRegression', 'Ridge', 'Lasso', 'ElasticNet', 'SVR', 'DecisionTreeRegressor', 'RandomForestRegressor', 'GradientBoostingRegressor', 'XGBRegressor', 'LGBMRegressor', 'CatBoostRegressor',
],
'Classification': [
'LogisticRegression', 'BernoulliNB', 'MultinomialNB', 'GaussianNB', 'SVC', 'DecisionTreeClassifier', 'RandomForestClassifier', 'GradientBoostingClassifier', 'XGBClassifier', 'LGBMClassifier', 'CatBoostClassifier',
],
'Auto ML': [
'AutoSklearnRegressor', 'AutoSklearnClassifier', 'TPOTRegressor', 'TPOTClassifier'
],
'Clustering': [
'KMeans', 'AgglomerativeClustering', 'GaussianMixture', 'DBSCAN',
],
'Dimension Reduction': [
'PCA', 'LinearDiscriminantAnalysis', 'TruncatedSVD', 'NMF', 'TSNE'
],
'Data Preparation': [
/** Encoding */
'OneHotEncoder', 'LabelEncoder', 'OrdinalEncoder', 'TargetEncoder', 'SMOTE',
/** Scaling */
'StandardScaler', 'RobustScaler', 'MinMaxScaler', 'Normalizer', 'FunctionTransformer', 'PolynomialFeatures'
]
};
Config.ML_DATA_TYPES = [
...Config.ML_DATA_DICT['Regression'],
...Config.ML_DATA_DICT['Classification'],
...Config.ML_DATA_DICT['Auto ML'],
...Config.ML_DATA_DICT['Clustering'],
...Config.ML_DATA_DICT['Dimension Reduction'],
...Config.ML_DATA_DICT['Data Preparation']
];
return Config;
});
/* End of file */