Repository navigation
Expand file tree
/
Copy pathPythonPR.java
More file actions
420 lines (343 loc) · 13 KB
/
Copy pathPythonPR.java
File metadata and controls
420 lines (343 loc) · 13 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
package gate.python;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import gate.*;
import gate.creole.AbstractLanguageAnalyser;
import gate.creole.ControllerAwarePR;
import gate.creole.ExecutionException;
import gate.creole.metadata.CreoleParameter;
import gate.creole.metadata.CreoleResource;
import gate.creole.metadata.Optional;
import gate.creole.metadata.RunTime;
import gate.util.Files;
import gate.Utils;
import gate.util.InvalidOffsetException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import com.fasterxml.jackson.core.JsonGenerationException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.commons.lang.ObjectUtils;
import org.apache.log4j.Logger;
@CreoleResource(name = "Python PR", comment = "Runs a Python script as a processing resource")
public class PythonPR extends AbstractLanguageAnalyser implements ControllerAwarePR {
private static final Logger log = Logger.getLogger(PythonPR.class);
private String pythonBinary;
private String lastPythonBinary;
private Boolean forceRestart;
private URL script;
private URL lastScript;
private String inputAS;
private String outputAS;
private FeatureMap scriptParams;
public String getPythonBinary() {
return pythonBinary;
}
@RunTime
@CreoleParameter(defaultValue = "python", comment = "Python command to use")
public void setPythonBinary(String pythonBinary) {
this.pythonBinary = pythonBinary;
}
public URL getScript() {
return script;
}
@RunTime
@CreoleParameter(defaultValue = "", comment = "Path to the Python script you want to run")
public void setScript(URL script) {
this.script = script;
}
@RunTime
@Optional
@CreoleParameter(comment = "Input annotation set to use")
public void setInputAS(String inputAS) {
this.inputAS = inputAS;
}
public String getInputAS() {
return inputAS;
}
@RunTime
@Optional
@CreoleParameter(comment = "Output annotation set to use")
public void setOutputAS(String outputAS) {
this.outputAS = outputAS;
}
public Boolean getForceRestart() {
return forceRestart;
}
@RunTime
@CreoleParameter(defaultValue="false", comment = "Force a restart on the next document. Will toggle when executed.")
public void setForceRestart(Boolean forceRestart) {
this.forceRestart = forceRestart;
}
public FeatureMap getScriptParams() {
return scriptParams;
}
@RunTime
@Optional
@CreoleParameter(comment = "Extra parameters to pass to the string")
public void setScriptParams(FeatureMap scriptParams) {
this.scriptParams = scriptParams;
}
public String getOutputAS() {
return outputAS;
}
private Process pythonProcess;
private PrintWriter pythonInput;
private JsonGenerator pythonJsonG;
private ObjectMapper pythonObjectMapper;
private BufferedReader pythonOutput;
public void execute() throws ExecutionException {
ensureProcess();
// Python is definitely running.
try {
exportDocument(getDocument(), pythonJsonG);
} catch (ExecutionException e) {
log.error("Couldn't export document",e);
cleanupProcess();
throw e;
}
try {
// Parse the reply, which should be a list of commands.
List<Command> commands = (List<Command>) pythonObjectMapper.readValue(pythonOutput,
new TypeReference<List<Command>>() {} );
transformDocument(getDocument(), commands);
} catch (IOException e) {
log.error("Unable to read JSON from python process, closing pipeline", e);
cleanupProcess();
throw new ExecutionException("Unable to read JSON from python process - " +
"perhaps process printed to stdout? (use stderr instead)", e);
} catch (InvalidOffsetException e) {
cleanupProcess();
throw new ExecutionException("Unable to apply changes requested by python script", e);
}
}
/**
* Applies the supplied list of document change commands to the given document, and returns it.
*
* @param document
* @param commands
* @return
* @throws InvalidOffsetException
*/
public static Document transformDocument(Document document, List<Command> commands) throws InvalidOffsetException {
AnnotationSet targetAnnotationSet;
Annotation targetAnnotation;
for (Command command : commands) {
switch (command.getCommand()) {
case ADD_ANNOT:
document.getAnnotations(command.getAnnotationSet()).
add(command.getStartOffset(), command.getEndOffset(),
command.getAnnotationName(), Utils.toFeatureMap(command.getFeatureMap()));
break;
case REMOVE_ANNOT:
targetAnnotationSet = document.getAnnotations(command.getAnnotationSet());
targetAnnotation = targetAnnotationSet.get(command.getAnnotationID());
targetAnnotationSet.remove(targetAnnotation);
break;
case UPDATE_FEATURE:
targetAnnotationSet = document.getAnnotations(command.getAnnotationSet());
targetAnnotation = targetAnnotationSet.get(command.getAnnotationID());
targetAnnotation.getFeatures().put(command.getFeatureName(), command.getFeatureValue());
break;
case CLEAR_FEATURES:
targetAnnotationSet = document.getAnnotations(command.getAnnotationSet());
targetAnnotation = targetAnnotationSet.get(command.getAnnotationID());
targetAnnotation.getFeatures().clear();
break;
case REMOVE_FEATURE:
targetAnnotationSet = document.getAnnotations(command.getAnnotationSet());
targetAnnotation = targetAnnotationSet.get(command.getAnnotationID());
targetAnnotation.getFeatures().remove(command.getFeatureName());
break;
}
}
return document;
}
public static void exportDocument(Document document, JsonGenerator jsonG) throws ExecutionException {
Map<String, Collection<Annotation>> allAnnotations = new TreeMap<String, Collection<Annotation>>();
Set<String> annotationSetNames = new TreeSet<String>();
annotationSetNames.add(""); // Include the default annotation set.
annotationSetNames.addAll(document.getAnnotationSetNames());
// Collect all annotations together in a format we can output directly to JSON
for (String annotationSetName : annotationSetNames) {
AnnotationSet annotationSet = document.getAnnotations(annotationSetName);
for (Annotation annotation : annotationSet) {
String type = annotation.getType();
String typeKey = (annotationSetName == null ? "" : annotationSetName) + ":" + type;
if (!allAnnotations.containsKey(typeKey)) {
allAnnotations.put(typeKey, new ArrayList<Annotation>());
}
allAnnotations.get(typeKey).add(annotation);
}
}
// Output the document in JSON format on the pipe
try {
PythonJsonUtils.writeDocument(document, 0l, document.getContent().size(), allAnnotations,
document.getFeatures(), null, "annotationID", jsonG);
jsonG.writeRaw("\n");
jsonG.flush();
} catch (InvalidOffsetException e) {
log.error("Impossible document offset exception", e);
throw new ExecutionException("Unable to write entire document span", e);
} catch (JsonGenerationException e) {
log.error("Unable to generate JSON for document", e);
throw new ExecutionException("Unable to generate JSON for document", e);
} catch (IOException e) {
log.error("Unable to flush JSON to python process, closing pipeline", e);
throw new ExecutionException("Unable to flush JSON to python process", e);
}
}
private void ensureProcess() throws ExecutionException {
boolean needNewProcess = forceRestart || (!processRunning() ||
!ObjectUtils.equals(pythonBinary, lastPythonBinary) ||
!ObjectUtils.equals(script, lastScript));
// Close the existing long-running process before opening a new one, if needed
if(pythonProcess != null && needNewProcess) {
IOUtils.closeQuietly(pythonInput);
try {
pythonProcess.waitFor();
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw new ExecutionException("Interrupted while waiting for python to exit");
}
}
// Start the fresh process as needed.
if(needNewProcess) {
// Runs python -u some_script.py (unbuffered)
ProcessBuilder builder = new ProcessBuilder(pythonBinary, "-u", Files.fileFromURL(script).getAbsolutePath());
try {
// Todo: there must be a better way to achieve this
URL pythonPath = new URL(Gate.getCreoleRegister().get(this.getClass().getName()).getXmlFileUrl(), ".");
String oldPythonPath = System.getenv("PYTHONPATH");
oldPythonPath = oldPythonPath != null ? oldPythonPath : ".";
builder.environment().put("PYTHONPATH", oldPythonPath + File.pathSeparator +
Files.fileFromURL(pythonPath).getAbsolutePath());
builder.directory(Files.fileFromURL(script).getAbsoluteFile().getParentFile());
} catch (MalformedURLException e) {
throw new ExecutionException("Couldn't form python path for running PR", e);
}
lastPythonBinary = pythonBinary;
lastScript = script;
try {
pythonProcess = builder.start();
setForceRestart(false);
report(pythonProcess.getErrorStream());
pythonInput = new PrintWriter(new OutputStreamWriter(pythonProcess.getOutputStream(), "UTF-8"));
pythonOutput = new BufferedReader(new InputStreamReader(pythonProcess.getInputStream(), "UTF-8"));
JsonFactory factory = new JsonFactory(); // Todo: maybe move this into Init if it causes problems
pythonJsonG = factory.createGenerator(pythonInput);
factory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
pythonObjectMapper = new ObjectMapper(factory);
} catch(IOException e) {
throw new ExecutionException("Could not start python", e);
}
}
}
protected boolean processRunning() {
if(pythonProcess == null) return false;
try {
pythonProcess.exitValue();
return false;
}
catch (IllegalThreadStateException e) {
return true;
}
}
protected void report(final InputStream stream) {
Thread t = new Thread() {
public void run() {
try {
IOUtils.copy(stream, System.err);
} catch(IOException e) {
log.warn("Error printing stderr output from python", e);
}
}
};
t.setDaemon(true);
t.start();
}
protected void cleanupProcess() {
if(pythonProcess != null) {
IOUtils.closeQuietly(pythonInput);
try {
IOUtils.copy(pythonOutput, (true ? System.err : NullOutputStream.NULL_OUTPUT_STREAM));
} catch(IOException e1) {
log.warn("Exception draining python output stream");
}
try {
pythonProcess.destroy();
pythonProcess.waitFor();
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while waiting for python to exit");
}
}
}
public void cleanup() {
super.cleanup();
cleanupProcess();
}
@Override
public void controllerExecutionStarted(Controller controller) throws ExecutionException {
ensureProcess();
ExecutionCommand command = new ExecutionCommand();
command.setCommand(ExecutionCommandEnum.BEGIN_EXECUTION);
HashMap<Object, Object> params = new HashMap<>();
params.put("inputAS", inputAS);
params.put("outputAS", outputAS);
if (scriptParams != null) {
params.putAll(scriptParams);
}
command.setParameterMap(Utils.toFeatureMap(params));
if (corpus != null) {
command.setCorpusName(corpus.getName());
command.setCorpusFeatures(corpus.getFeatures());
}
try {
pythonObjectMapper.writeValue(pythonJsonG, command);
pythonJsonG.writeRaw("\n");
pythonJsonG.flush();
} catch (IOException e) {
throw new ExecutionException("Unable to send begin execution command to python process");
}
}
@Override
public void controllerExecutionFinished(Controller controller) throws ExecutionException {
ensureProcess();
ExecutionCommand command = new ExecutionCommand();
command.setCommand(ExecutionCommandEnum.END_EXECUTION);
try {
pythonObjectMapper.writeValue(pythonJsonG, command);
pythonJsonG.writeRaw("\n");
pythonJsonG.flush();
// Expect python to exit at this point.
try {
pythonProcess.waitFor();
cleanupProcess();
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw new ExecutionException("Interrupted while waiting for python to exit");
}
} catch (IOException e) {
throw new ExecutionException("Unable to send end execution command to python process");
}
}
@Override
public void controllerExecutionAborted(Controller controller, Throwable throwable) throws ExecutionException {
ensureProcess();
ExecutionCommand command = new ExecutionCommand();
command.setCommand(ExecutionCommandEnum.ABORT_EXECUTION);
try {
pythonObjectMapper.writeValue(pythonJsonG, command);
pythonJsonG.writeRaw("\n");
pythonJsonG.flush();
} catch (IOException e) {
throw new ExecutionException("Unable to send abort execution command to python process");
}
}
}