-
Notifications
You must be signed in to change notification settings - Fork 311
/
Cleaner.ts
229 lines (208 loc) · 8.89 KB
/
Cleaner.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
/**
* Copyright 2020 AXA Group Operations S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { DrawingDetectionModule } from './processing/DrawingDetectionModule/DrawingDetectionModule';
import { HeaderFooterDetectionModule } from './processing/HeaderFooterDetectionModule/HeaderFooterDetectionModule';
import { HierarchyDetectionModule } from './processing/HierarchyDetectionModule/HierarchyDetectionModule';
import { ImageDetectionModule } from './processing/ImageDetectionModule/ImageDetectionModule';
import { KeyValueDetectionModule } from './processing/KeyValueDetectionModule/KeyValueDetectionModule';
import { LinesToParagraphModule } from './processing/LinesToParagraphModule/LinesToParagraphModule';
import { LinkDetectionModule } from './processing/LinkDetectionModule/LinkDetectionModule';
import { ListDetectionModule } from './processing/ListDetectionModule/ListDetectionModule';
import { MlHeadingDetectionModule } from './processing/MlHeadingDetectionModule/MlHeadingDetectionModule';
import { Module } from './processing/Module';
import { NumberCorrectionModule } from './processing/NumberCorrectionModule/NumberCorrectionModule';
import { OutOfPageRemovalModule } from './processing/OutOfPageRemovalModule/OutOfPageRemovalModule';
import { PageNumberDetectionModule } from './processing/PageNumberDetectionModule/PageNumberDetectionModule';
import { ReadingOrderDetectionModule } from './processing/ReadingOrderDetectionModule/ReadingOrderDetectionModule';
import { RedundancyDetectionModule } from './processing/RedundancyDetectionModule/RedundancyDetectionModule';
import { RegexMatcherModule } from './processing/RegexMatcherModule/RegexMatcherModule';
import { RemoteModule } from './processing/RemoteModule/RemoteModule';
import { SeparateWordsModule } from './processing/SeparateWordsModule/SeparateWordsModule';
import { TableDetection2Module } from './processing/TableDetection2Module/TableDetection2Module';
import { TableDetectionModule } from './processing/TableDetectionModule/TableDetectionModule';
import { TableOfContentsDetectionModule } from './processing/TableOfContentsDetectionModule/TableOfContentsDetectionModule';
import { WhitespaceRemovalModule } from './processing/WhitespaceRemovalModule/WhitespaceRemovalModule';
import { WordsToLineModule } from './processing/WordsToLineModule/WordsToLineModule';
import { WordsToLineNewModule } from './processing/WordsToLineNewModule/WordsToLineNew';
import { CleanerConfig, Config } from './types/Config';
import { Document } from './types/DocumentRepresentation/Document';
import logger from './utils/Logger';
/**
* The cleaner a pipeline of tool used to clean up the PDF file represented in the Json,
* such as removing useless white blocks, merging text blocks together to form words, sentences or paragraphs.
* It can also add some metadata to any block to help higher level tools.
*/
export class Cleaner {
private modules: Module[] = [];
private solvedDependencies: Array<typeof Module> = [];
// Every newly created module should figure in this register
private cleaningToolRegister: Array<typeof Module> = [
OutOfPageRemovalModule,
ReadingOrderDetectionModule,
WordsToLineModule,
WordsToLineNewModule,
KeyValueDetectionModule,
LinesToParagraphModule,
MlHeadingDetectionModule,
HierarchyDetectionModule,
LinkDetectionModule,
ListDetectionModule,
HeaderFooterDetectionModule,
PageNumberDetectionModule,
NumberCorrectionModule,
RedundancyDetectionModule,
WhitespaceRemovalModule,
TableDetection2Module,
TableDetectionModule,
ImageDetectionModule,
RegexMatcherModule,
RemoteModule,
SeparateWordsModule,
TableOfContentsDetectionModule,
DrawingDetectionModule,
// Add your own module here!
];
/**
* Constructor for a cleaner based class.
*
* @param config Configuration for the cleaner type module.
* @remarks Sets up the cleaner module with the configuration passed, along with checking if the dependencies.
*/
constructor(config: Config) {
if (config.version <= 0.4) {
this.parse0_4Config(config.cleaner);
} else {
this.parseLatestConfig(config.cleaner);
}
}
/**
* Get a module using just its name.
*
* @param config Configuration for the cleaner type module.
* @returns The found module.
* @remarks Sets up the cleaner module with the configuration passed, along with checking if the dependencies.
*/
public getModuleByName(name: string): typeof Module {
const moduleClass: typeof Module = this.cleaningToolRegister.filter(
M => M.moduleName === name,
)[0];
if (!moduleClass) {
throw new Error(
`Module called ${name} not found. Please check your config file with the documentation.`,
);
}
return moduleClass;
}
/**
* Runs the cleaning pipeline.
*
* @param document The document to be cleaned
* @returns The promise of the document after the run of all the cleaning modules.
* @remarks Goes through all the modules one by one and executes them, noting
* the execution time for each one, then logging it.
*/
public run(document: Document, config: Config): Promise<Document> {
const startTime: number = Date.now();
return this.runNextModule(document, 0, config).then(newDocument => {
const endTime: number = (Date.now() - startTime) / 1000;
logger.info(`Total elapsed time: ${endTime}s`);
return newDocument;
});
}
private parseLatestConfig(config: CleanerConfig) {
config.forEach((entry: string | [string, object]) => {
let toolName: string;
let options: object = {};
if (Array.isArray(entry)) {
toolName = entry[0];
if (typeof entry[1] === 'object') {
options = entry[1];
}
} else {
toolName = entry;
}
const moduleClass: typeof Module = this.getModuleByName(toolName);
this.checkDependenciesAndAdd(moduleClass);
logger.info('Check config module: ' + toolName);
this.modules.push(new moduleClass(options));
});
}
private parse0_4Config(config: CleanerConfig) {
for (let i = 0; i < config.length; i++) {
const toolName = config[i];
if (typeof toolName !== 'string') {
throw new Error(`expected tool name as string instead of options as object at index ${i}`);
}
let options: object = {};
const opt = config[i + 1];
if (i + 1 < config.length && typeof opt === 'object') {
options = opt;
i++;
}
const moduleClass: typeof Module = this.getModuleByName(toolName);
this.checkDependenciesAndAdd(moduleClass);
this.modules.push(new moduleClass(options));
}
}
/**
* Get a module using just its name.
*
* @param document The document on which the module is to be run.
* @param i The index of the module to be run (among a list of modules).
* @returns The promise of the document after running the next module.
* @remarks Sets up the cleaner module with the configuration passed, along with checking of the dependencies.
*/
private runNextModule(document: Document, i: number, config: Config): Promise<Document> {
if (i < this.modules.length) {
logger.info(
`Running module: ${this.modules[i].constructor.name}, Options: ${JSON.stringify(
this.modules[i].options,
)}`,
);
const startTime: number = Date.now();
return this.modules[i].run(document, config).then((doc: Document) => {
const endTime: number = (Date.now() - startTime) / 1000;
logger.info(` Elapsed time: ${endTime}s`);
return this.runNextModule(doc, i + 1, config);
});
} else {
return Promise.resolve(document);
}
}
/**
* Check for dependencies given a type of a module, and then add it
*
* @param moduleClass The type of a module to be checked for.
*/
private checkDependenciesAndAdd(moduleClass: typeof Module) {
const unresolved: Array<typeof Module> = [];
let isCovered: boolean = true;
moduleClass.dependencies.forEach(dependency => {
if (!this.solvedDependencies.includes(dependency)) {
isCovered = false;
unresolved.push(dependency);
}
});
if (isCovered) {
this.solvedDependencies.push(moduleClass);
} else {
const unresolvedStr: string = unresolved.map(m => m.moduleName).join(', ');
throw new Error(
`Module ${moduleClass.moduleName} has unresolved dependencies (${unresolvedStr}).`,
);
}
}
}