-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
file-handler.ts
294 lines (264 loc) · 9.01 KB
/
file-handler.ts
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
// Copyright (c) 2023 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import * as arrow from 'apache-arrow';
import {parseInBatches} from '@loaders.gl/core';
import {JSONLoader, _JSONPath} from '@loaders.gl/json';
import {CSVLoader} from '@loaders.gl/csv';
import {ArrowLoader} from '@loaders.gl/arrow';
import {
processArrowTable,
processGeojson,
processKeplerglJSON,
processRowObject
} from './data-processor';
import {generateHashId, isPlainObject, generateHashIdFromString} from '@kepler.gl/utils';
import {DATASET_FORMATS} from '@kepler.gl/constants';
import {Loader} from '@loaders.gl/loader-utils';
import {FileCacheItem, ValidKeplerGlMap} from './types';
import {Feature, AddDataToMapPayload} from '@kepler.gl/types';
import {FeatureCollection} from '@turf/helpers';
const BATCH_TYPE = {
METADATA: 'metadata',
PARTIAL_RESULT: 'partial-result',
FINAL_RESULT: 'final-result'
};
const CSV_LOADER_OPTIONS = {
shape: 'object-row-table',
dynamicTyping: false // not working for now
};
const ARROW_LOADER_OPTIONS = {
shape: 'arrow-table'
};
const JSON_LOADER_OPTIONS = {
shape: 'object-row-table',
// instruct loaders.gl on what json paths to stream
jsonpaths: [
'$', // JSON Row array
'$.features', // GeoJSON
'$.datasets' // KeplerGL JSON
]
};
export type ProcessFileDataContent = {
data: unknown;
fileName: string;
length?: number;
progress?: {rowCount?: number; rowCountInBatch?: number; percent?: number};
/** metadata e.g. for arrow data, metadata could be the schema.fields */
metadata?: Map<string, string>;
};
/**
* check if table is an ArrowTable object
* @param table - object to check
* @returns {boolean} - true if table is an ArrowTable object type guarded
*/
export function isArrowTable(table: any): table is arrow.Table {
return Boolean(table instanceof arrow.Table);
}
/**
* check if data is an ArrowData object, which is an array of RecordBatch
* @param data - object to check
* @returns {boolean} - true if data is an ArrowData object type guarded
*/
export function isArrowData(data: any): boolean {
return Array.isArray(data) && Boolean(data[0].data && data[0].schema);
}
export function isGeoJson(json: unknown): json is Feature | FeatureCollection {
// json can be feature collection
// or single feature
return isPlainObject(json) && (isFeature(json) || isFeatureCollection(json));
}
export function isFeature(json: unknown): json is Feature {
return isPlainObject(json) && json.type === 'Feature' && Boolean(json.geometry);
}
export function isFeatureCollection(json: unknown): json is FeatureCollection {
return isPlainObject(json) && json.type === 'FeatureCollection' && Boolean(json.features);
}
export function isRowObject(json: any): boolean {
return Array.isArray(json) && isPlainObject(json[0]);
}
export function isKeplerGlMap(json: unknown): json is ValidKeplerGlMap {
return Boolean(
isPlainObject(json) &&
json.datasets &&
json.config &&
json.info &&
isPlainObject(json.info) &&
json.info.app === 'kepler.gl'
);
}
export async function* makeProgressIterator(
asyncIterator: AsyncIterable<any>,
info: {size: number}
): AsyncGenerator {
let rowCount = 0;
for await (const batch of asyncIterator) {
// the length could be stored in `batch.length` for arrow batch
const rowCountInBatch = (batch.data && (batch.data.length || batch.length)) || 0;
rowCount += rowCountInBatch;
const percent = Number.isFinite(batch.bytesUsed) ? batch.bytesUsed / info.size : null;
// Update progress object
const progress = {
rowCount,
rowCountInBatch,
...(Number.isFinite(percent) ? {percent} : {})
};
yield {...batch, progress};
}
}
// eslint-disable-next-line complexity
export async function* readBatch(
asyncIterator: AsyncIterable<any>,
fileName: string
): AsyncGenerator {
let result = null;
const batches = <any>[];
for await (const batch of asyncIterator) {
// Last batch will have this special type and will provide all the root
// properties of the parsed document.
// Only json parse will have `FINAL_RESULT`
if (batch.batchType === BATCH_TYPE.FINAL_RESULT) {
if (batch.container) {
result = {...batch.container};
}
// Set the streamed data correctly is Batch json path is set
// and the path streamed is not the top level object (jsonpath = '$')
if (batch.jsonpath && batch.jsonpath.length > 1) {
const streamingPath = new _JSONPath(batch.jsonpath);
streamingPath.setFieldAtPath(result, batches);
} else if (batch.jsonpath && batch.jsonpath.length === 1) {
// The streamed object is a ROW JSON-batch (jsonpath = '$')
// row objects
result = batches;
}
} else {
const batchData = isArrowTable(batch.data) ? batch.data.batches : batch.data;
for (let i = 0; i < batchData?.length; i++) {
batches.push(batchData[i]);
}
}
yield {
...batch,
...(batch.schema ? {headers: Object.keys(batch.schema)} : {}),
fileName,
// if dataset is CSV, data is set to the raw batches
data: result ? result : batches
};
}
}
export async function readFileInBatches({
file,
loaders = [],
loadOptions = {}
}: {
file: File;
fileCache: FileCacheItem[];
loaders: Loader[];
loadOptions: any;
}): Promise<AsyncGenerator> {
loaders = [JSONLoader, CSVLoader, ArrowLoader, ...loaders];
loadOptions = {
csv: CSV_LOADER_OPTIONS,
arrow: ARROW_LOADER_OPTIONS,
json: JSON_LOADER_OPTIONS,
metadata: true,
...loadOptions
};
const batchIterator = await parseInBatches(file, loaders, loadOptions);
const progressIterator = makeProgressIterator(batchIterator, {size: file.size});
return readBatch(progressIterator, file.name);
}
export function processFileData({
content,
fileCache
}: {
content: ProcessFileDataContent;
fileCache: FileCacheItem[];
}): Promise<FileCacheItem[]> {
return new Promise((resolve, reject) => {
let {fileName, data} = content;
let format: string | undefined;
let processor: Function | undefined;
// generate unique id with length of 4 using fileName string
const id = generateHashIdFromString(fileName);
if (isArrowData(data)) {
format = DATASET_FORMATS.arrow;
processor = processArrowTable;
} else if (isKeplerGlMap(data)) {
format = DATASET_FORMATS.keplergl;
processor = processKeplerglJSON;
} else if (isRowObject(data)) {
format = DATASET_FORMATS.row;
processor = processRowObject;
} else if (isGeoJson(data)) {
format = DATASET_FORMATS.geojson;
processor = processGeojson;
}
if (format && processor) {
const result = processor(data);
resolve([
...fileCache,
{
data: result,
info: {
id,
label: content.fileName,
format
}
}
]);
}
reject('Unknown File Format');
});
}
export function filesToDataPayload(fileCache: FileCacheItem[]): AddDataToMapPayload[] {
// seperate out files which could be a single datasets. or a keplergl map json
const collection = fileCache.reduce<{
datasets: FileCacheItem[];
keplerMaps: AddDataToMapPayload[];
}>(
(accu, file) => {
const {data, info} = file;
if (info?.format === DATASET_FORMATS.keplergl) {
// if file contains a single kepler map dataset & config
accu.keplerMaps.push({
...data,
options: {
centerMap: !(data.config && data.config.mapState)
}
});
} else if (DATASET_FORMATS[info?.format]) {
// if file contains only data
const newDataset = {
data,
info: {
id: info?.id || generateHashId(4),
...(info || {})
}
};
accu.datasets.push(newDataset);
}
return accu;
},
{datasets: [], keplerMaps: []}
);
// add kepler map first with config
// add datasets later in one add data call
return collection.keplerMaps.concat({datasets: collection.datasets});
}