-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCommandLineInterface.java
More file actions
316 lines (290 loc) · 10.1 KB
/
CommandLineInterface.java
File metadata and controls
316 lines (290 loc) · 10.1 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
package com.mindee.v1;
import com.mindee.MindeeException;
import com.mindee.input.LocalInputSource;
import com.mindee.input.PageOptions;
import com.mindee.input.PageOptionsOperation;
import com.mindee.v1.cli.CommandLineInterfaceProducts;
import com.mindee.v1.cli.ProductProcessor;
import com.mindee.v1.clientoptions.PollingOptions;
import com.mindee.v1.clientoptions.PredictOptions;
import com.mindee.v1.http.Endpoint;
import com.mindee.v1.parsing.common.AsyncPredictResponse;
import com.mindee.v1.parsing.common.Inference;
import com.mindee.v1.parsing.common.PredictResponse;
import com.mindee.v1.parsing.common.ocr.Ocr;
import com.mindee.v1.product.generated.GeneratedV1;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import picocli.CommandLine.ScopeType;
import picocli.CommandLine.Spec;
/**
* Command Line Interface for the Mindee client.
*/
@Command(
name = "CLI",
description = "Invoke Off The Shelf API for invoice, receipt, and passports",
subcommands = { CommandLine.HelpCommand.class },
mixinStandardHelpOptions = true
)
public class CommandLineInterface implements ProductProcessor {
@Spec
CommandSpec spec;
@Option(
names = { "-w", "--all-words" },
scope = ScopeType.INHERIT,
paramLabel = "WORDS",
description = "Include all document words in the response"
)
private boolean words;
@Option(
names = { "-f", "--full-text" },
scope = ScopeType.INHERIT,
paramLabel = "FULL_TEXT",
description = "Include full text response, if available"
)
private boolean fullText;
private enum OutputChoices {
summary,
full,
raw
}
@Option(
names = { "-o", "--output-type" },
scope = ScopeType.INHERIT,
paramLabel = "OUTPUT_TYPE",
description = "Output type, one of:\n"
+ " summary - document predictions\n"
+ " full - all predictions\n"
+ " raw - raw response from the server",
defaultValue = "summary"
)
private OutputChoices outputType;
@Option(
names = { "-k", "--api-key" },
scope = ScopeType.INHERIT,
paramLabel = "MINDEE_API_KEY",
description = "API key, if not set, will use system property"
)
private String apiKey;
@Option(
names = { "-c", "--cut-doc" },
scope = ScopeType.INHERIT,
paramLabel = "<CutDoc>",
description = "Keep only the first 5 pages of the document"
)
private boolean cutDoc;
/**
* Instantiates all products one by one in a separate picocli instance and relays the command to
* them.
*
* @param args CLI args.
*/
public static void main(String[] args) {
CommandLineInterface cli = new CommandLineInterface();
CommandLine commandLine = new CommandLine(cli);
CommandLineInterfaceProducts products = new CommandLineInterfaceProducts(cli);
for (Method method : CommandLineInterfaceProducts.class.getDeclaredMethods()) {
if (method.isAnnotationPresent(CommandLine.Command.class)) {
CommandLine.Command annotation = method.getAnnotation(CommandLine.Command.class);
String subcommandName = annotation.name();
CommandLine subCmd = new CommandLine(new ProductCommandHandler(products, method));
subCmd.getCommandSpec().usageMessage().description(annotation.description());
commandLine.addSubcommand(subcommandName, subCmd);
}
}
int exitCode = commandLine.execute(args);
System.exit(exitCode);
}
/**
* Adds all commands from CommandLineInterfaceProducts automatically.
*/
@CommandLine.Command(
mixinStandardHelpOptions = true,
description = "Auto-generated product command"
)
public static class ProductCommandHandler implements Callable<Integer> {
private final CommandLineInterfaceProducts products;
private final Method method;
@CommandLine.Parameters(index = "0", paramLabel = "<path>")
private File file;
/**
* Reads all products from the CommandLineInterfaceProducts file and makes them accessible.
*
* @param products List of all products to add.
* @param method Handler of each product.
*/
public ProductCommandHandler(CommandLineInterfaceProducts products, Method method) {
this.products = products;
this.method = method;
this.method.setAccessible(true);
}
@Override
public Integer call() throws Exception {
method.invoke(products, file);
return 0;
}
}
@Command(name = "generated", description = "Invokes a Generated API")
void generatedMethod(
@Option(
names = { "-a", "--account" },
scope = ScopeType.LOCAL,
required = true,
paramLabel = "accountName",
description = "The name of the account"
) String accountName,
@Option(
names = { "-e", "--endpointName" },
scope = ScopeType.LOCAL,
required = true,
paramLabel = "endpointName",
description = "The name of the endpoint"
) String endpointName,
@Option(
names = { "-v", "--productVersion" },
scope = ScopeType.LOCAL,
paramLabel = "productVersion",
description = "The version of the endpoint",
defaultValue = "1"
) String productVersion,
@Option(
names = { "-m", "--parsingMode" },
description = "Whether to parse the document in synchronous mode or polling.",
scope = ScopeType.LOCAL,
defaultValue = "async"
) String parsingMode,
@Parameters(index = "0", scope = ScopeType.LOCAL, paramLabel = "<path>") File file
) throws IOException, InterruptedException {
var mindeeClient = new MindeeClient(apiKey);
Endpoint endpoint = new Endpoint(endpointName, accountName, productVersion);
if (Objects.equals(parsingMode, "sync")) {
if (cutDoc) {
PredictResponse<GeneratedV1> document = mindeeClient
.parse(GeneratedV1.class, endpoint, new LocalInputSource(file), getDefaultPageOptions());
System.out.println(document.toString());
} else {
PredictResponse<GeneratedV1> document = mindeeClient
.parse(GeneratedV1.class, endpoint, new LocalInputSource(file));
System.out.println(document.toString());
}
} else if (Objects.equals(parsingMode, "async")) {
if (cutDoc) {
AsyncPredictResponse<GeneratedV1> document = mindeeClient
.enqueueAndParse(
GeneratedV1.class,
endpoint,
new LocalInputSource(file),
PredictOptions.builder().build(),
getDefaultPageOptions(),
PollingOptions.builder().build()
);
System.out.println(document.toString());
} else {
AsyncPredictResponse<GeneratedV1> document = mindeeClient
.enqueueAndParse(GeneratedV1.class, endpoint, new LocalInputSource(file));
System.out.println(document.toString());
}
} else {
throw new MindeeException("Invalid parsing mode: " + parsingMode);
}
}
protected PageOptions getDefaultPageOptions() {
return new PageOptions.Builder()
.pageIndexes(new Integer[] { 0, 1, 2, 3, 4 })
.operation(PageOptionsOperation.KEEP_ONLY)
.build();
}
private String wordsOutput(Ocr ocr) {
StringBuilder output = new StringBuilder();
output.append("\n#############\nDocument Text\n#############\n::\n ");
output
.append(
Arrays
.stream(ocr.toString().split(String.format("%n")))
.collect(Collectors.joining(String.format("%n ")))
);
output.append("\n");
return output.toString();
}
@Override
public <T extends Inference<?, ?>> String standardProductOutput(
Class<T> productClass,
File file
) throws IOException {
var mindeeClient = new MindeeClient(apiKey);
var inputSource = new LocalInputSource(file);
PredictResponse<T> response;
PredictOptions predictOptions = PredictOptions
.builder()
.allWords(words)
.fullText(fullText)
.build();
if (cutDoc) {
response = mindeeClient
.parse(productClass, inputSource, predictOptions, getDefaultPageOptions());
} else {
response = mindeeClient.parse(productClass, inputSource, predictOptions);
}
StringBuilder output = new StringBuilder();
switch (outputType) {
case full:
output.append(response.getDocument().toString());
break;
case raw:
output.append(response.getRawResponse());
break;
default:
output.append(response.getDocument().getInference().getPrediction().toString());
}
if (words) {
output.append(wordsOutput(response.getDocument().getOcr()));
}
return output.toString();
}
@Override
public <T extends Inference<?, ?>> String standardProductAsyncOutput(
Class<T> productClass,
File file
) throws IOException, InterruptedException {
var mindeeClient = new MindeeClient(apiKey);
var inputSource = new LocalInputSource(file);
AsyncPredictResponse<T> response;
PredictOptions predictOptions = PredictOptions
.builder()
.allWords(words)
.fullText(fullText)
.build();
if (cutDoc) {
response = mindeeClient
.enqueueAndParse(productClass, inputSource, predictOptions, getDefaultPageOptions(), null);
} else {
response = mindeeClient
.enqueueAndParse(productClass, inputSource, predictOptions, null, null);
}
StringBuilder output = new StringBuilder();
switch (outputType) {
case full:
output.append(response.getDocument().toString());
break;
case raw:
output.append(response.getRawResponse());
break;
default:
output.append(response.getDocumentObj().getInference().getPrediction().toString());
}
if (words) {
output.append(wordsOutput(response.getDocumentObj().getOcr()));
}
return output.toString();
}
}