/* * Copyright 2016 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * 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. */ package de.tudarmstadt.ukp.dkpro.core.opennlp.internal; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.component.JCasConsumer_ImplBase; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import de.tudarmstadt.ukp.dkpro.core.api.parameter.ComponentParameters; import opennlp.tools.util.model.BaseModel; /** * Train a model for OpenNLP. */ public abstract class OpenNlpTrainerBase<T extends CasSampleStreamBase> extends JCasConsumer_ImplBase { public static final String PARAM_TARGET_LOCATION = ComponentParameters.PARAM_TARGET_LOCATION; @ConfigurationParameter(name = PARAM_TARGET_LOCATION, mandatory = true) private File targetLocation; private T stream; private ExecutorService executor = Executors.newSingleThreadExecutor(); private Future<? extends BaseModel> future; @Override public void initialize(UimaContext aContext) throws ResourceInitializationException { super.initialize(aContext); stream = makeSampleStream(); Callable<? extends BaseModel> trainTask = makeTrainer(); future = executor.submit(trainTask); } public abstract T makeSampleStream(); public abstract Callable<? extends BaseModel> makeTrainer(); public T getStream() { return stream; } @Override public void process(JCas aJCas) throws AnalysisEngineProcessException { if (!future.isCancelled()) { stream.send(aJCas); } } @Override public void collectionProcessComplete() throws AnalysisEngineProcessException { try { stream.close(); } catch (IOException e) { throw new AnalysisEngineProcessException(e); } BaseModel model; try { model = future.get(); } catch (InterruptedException | ExecutionException e) { throw new AnalysisEngineProcessException(e); } try (OutputStream out = new FileOutputStream(targetLocation)) { model.serialize(out); } catch (IOException e) { throw new AnalysisEngineProcessException(e); } } }