use of com.joliciel.talismane.machineLearning.features.RuntimeEnvironment in project talismane by joliciel-informatique.
the class LanguageDetector method detectLanguages.
/**
* Return a probability distribution of languages for a given text.
*/
public List<WeightedOutcome<Locale>> detectLanguages(String text) throws TalismaneException {
if (LOG.isTraceEnabled()) {
LOG.trace("Testing text: " + text);
}
text = text.toLowerCase(Locale.ENGLISH);
text = Normalizer.normalize(text, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
List<FeatureResult<?>> featureResults = new ArrayList<FeatureResult<?>>();
for (LanguageDetectorFeature<?> feature : features) {
RuntimeEnvironment env = new RuntimeEnvironment();
FeatureResult<?> featureResult = feature.check(text, env);
if (featureResult != null)
featureResults.add(featureResult);
}
if (LOG.isTraceEnabled()) {
for (FeatureResult<?> result : featureResults) {
LOG.trace(result.toString());
}
}
List<Decision> decisions = this.decisionMaker.decide(featureResults);
if (LOG.isTraceEnabled()) {
for (Decision decision : decisions) {
LOG.trace(decision.getOutcome() + ": " + decision.getProbability());
}
}
List<WeightedOutcome<Locale>> results = new ArrayList<WeightedOutcome<Locale>>();
for (Decision decision : decisions) {
Locale locale = Locale.forLanguageTag(decision.getOutcome());
results.add(new WeightedOutcome<Locale>(locale, decision.getProbability()));
}
return results;
}
use of com.joliciel.talismane.machineLearning.features.RuntimeEnvironment in project talismane by joliciel-informatique.
the class TransitionBasedParser method parseSentence.
@Override
public List<ParseConfiguration> parseSentence(List<PosTagSequence> input) throws TalismaneException, IOException {
List<PosTagSequence> posTagSequences = null;
if (this.propagatePosTaggerBeam) {
posTagSequences = input;
} else {
posTagSequences = new ArrayList<>(1);
posTagSequences.add(input.get(0));
}
long startTime = System.currentTimeMillis();
int maxAnalysisTimeMilliseconds = maxAnalysisTimePerSentence * 1000;
int minFreeMemoryBytes = minFreeMemory * KILOBYTE;
TokenSequence tokenSequence = posTagSequences.get(0).getTokenSequence();
TreeMap<Integer, PriorityQueue<ParseConfiguration>> heaps = new TreeMap<>();
PriorityQueue<ParseConfiguration> heap0 = new PriorityQueue<>();
for (PosTagSequence posTagSequence : posTagSequences) {
// add an initial ParseConfiguration for each postag sequence
ParseConfiguration initialConfiguration = new ParseConfiguration(posTagSequence);
initialConfiguration.setScoringStrategy(decisionMaker.getDefaultScoringStrategy());
heap0.add(initialConfiguration);
if (LOG.isDebugEnabled()) {
LOG.debug("Adding initial posTagSequence: " + posTagSequence);
}
}
heaps.put(0, heap0);
PriorityQueue<ParseConfiguration> backupHeap = null;
PriorityQueue<ParseConfiguration> finalHeap = null;
PriorityQueue<ParseConfiguration> terminalHeap = new PriorityQueue<>();
while (heaps.size() > 0) {
Entry<Integer, PriorityQueue<ParseConfiguration>> heapEntry = heaps.pollFirstEntry();
PriorityQueue<ParseConfiguration> currentHeap = heapEntry.getValue();
int currentHeapIndex = heapEntry.getKey();
if (LOG.isTraceEnabled()) {
LOG.trace("##### Polling next heap: " + heapEntry.getKey() + ", size: " + heapEntry.getValue().size());
}
boolean finished = false;
// systematically set the final heap here, just in case we exit
// "naturally" with no more heaps
finalHeap = heapEntry.getValue();
backupHeap = new PriorityQueue<>();
// we jump out when either (a) all tokens have been attached or
// (b) we go over the max alloted time
ParseConfiguration topConf = currentHeap.peek();
if (topConf.isTerminal()) {
LOG.trace("Exiting with terminal heap: " + heapEntry.getKey() + ", size: " + heapEntry.getValue().size());
finished = true;
}
if (earlyStop && terminalHeap.size() >= beamWidth) {
LOG.debug("Early stop activated and terminal heap contains " + beamWidth + " entries. Exiting.");
finalHeap = terminalHeap;
finished = true;
}
long analysisTime = System.currentTimeMillis() - startTime;
if (maxAnalysisTimePerSentence > 0 && analysisTime > maxAnalysisTimeMilliseconds) {
LOG.info("Parse tree analysis took too long for sentence: " + tokenSequence.getSentence().getText());
LOG.info("Breaking out after " + maxAnalysisTimePerSentence + " seconds.");
finished = true;
}
if (minFreeMemory > 0) {
long freeMemory = Runtime.getRuntime().freeMemory();
if (freeMemory < minFreeMemoryBytes) {
LOG.info("Not enough memory left to parse sentence: " + tokenSequence.getSentence().getText());
LOG.info("Min free memory (bytes):" + minFreeMemoryBytes);
LOG.info("Current free memory (bytes): " + freeMemory);
finished = true;
}
}
if (finished) {
break;
}
// limit the breadth to K
int maxSequences = currentHeap.size() > this.beamWidth ? this.beamWidth : currentHeap.size();
int j = 0;
while (currentHeap.size() > 0) {
ParseConfiguration history = currentHeap.poll();
if (LOG.isTraceEnabled()) {
LOG.trace("### Next configuration on heap " + heapEntry.getKey() + ":");
LOG.trace(history.toString());
LOG.trace("Score: " + df.format(history.getScore()));
LOG.trace(history.getPosTagSequence().toString());
}
List<Decision> decisions = new ArrayList<>();
// test the positive rules on the current configuration
boolean ruleApplied = false;
if (parserPositiveRules != null) {
for (ParserRule rule : parserPositiveRules) {
if (LOG.isTraceEnabled()) {
LOG.trace("Checking rule: " + rule.toString());
}
RuntimeEnvironment env = new RuntimeEnvironment();
FeatureResult<Boolean> ruleResult = rule.getCondition().check(history, env);
if (ruleResult != null && ruleResult.getOutcome()) {
Decision positiveRuleDecision = new Decision(rule.getTransition().getCode());
decisions.add(positiveRuleDecision);
positiveRuleDecision.addAuthority(rule.getCondition().getName());
ruleApplied = true;
if (LOG.isTraceEnabled()) {
LOG.trace("Rule applies. Setting transition to: " + rule.getTransition().getCode());
}
break;
}
}
}
if (!ruleApplied) {
// test the features on the current configuration
List<FeatureResult<?>> parseFeatureResults = new ArrayList<>();
for (ParseConfigurationFeature<?> feature : this.parseFeatures) {
RuntimeEnvironment env = new RuntimeEnvironment();
FeatureResult<?> featureResult = feature.check(history, env);
if (featureResult != null)
parseFeatureResults.add(featureResult);
}
if (LOG_FEATURES.isTraceEnabled()) {
SortedSet<String> featureResultSet = parseFeatureResults.stream().map(f -> f.toString()).collect(Collectors.toCollection(() -> new TreeSet<>()));
for (String featureResultString : featureResultSet) {
LOG_FEATURES.trace(featureResultString);
}
}
// evaluate the feature results using the decision maker
decisions = this.decisionMaker.decide(parseFeatureResults);
for (ClassificationObserver observer : this.observers) {
observer.onAnalyse(history, parseFeatureResults, decisions);
}
List<Decision> decisionShortList = new ArrayList<>(decisions.size());
for (Decision decision : decisions) {
if (decision.getProbability() > MIN_PROB_TO_STORE)
decisionShortList.add(decision);
}
decisions = decisionShortList;
// apply the negative rules
Set<String> eliminatedTransitions = new HashSet<>();
if (parserNegativeRules != null) {
for (ParserRule rule : parserNegativeRules) {
if (LOG.isTraceEnabled()) {
LOG.trace("Checking negative rule: " + rule.toString());
}
RuntimeEnvironment env = new RuntimeEnvironment();
FeatureResult<Boolean> ruleResult = rule.getCondition().check(history, env);
if (ruleResult != null && ruleResult.getOutcome()) {
for (Transition transition : rule.getTransitions()) {
eliminatedTransitions.add(transition.getCode());
if (LOG.isTraceEnabled())
LOG.trace("Rule applies. Eliminating transition: " + transition.getCode());
}
}
}
if (eliminatedTransitions.size() > 0) {
decisionShortList = new ArrayList<>();
for (Decision decision : decisions) {
if (!eliminatedTransitions.contains(decision.getOutcome())) {
decisionShortList.add(decision);
} else {
LOG.trace("Eliminating decision: " + decision.toString());
}
}
if (decisionShortList.size() > 0) {
decisions = decisionShortList;
} else {
LOG.debug("All decisions eliminated! Restoring original decisions.");
}
}
}
}
// has a positive rule been applied?
boolean transitionApplied = false;
TransitionSystem transitionSystem = TalismaneSession.get(sessionId).getTransitionSystem();
// type, we should be able to stop
for (Decision decision : decisions) {
Transition transition = transitionSystem.getTransitionForCode(decision.getOutcome());
if (LOG.isTraceEnabled())
LOG.trace("Outcome: " + transition.getCode() + ", " + decision.getProbability());
if (transition.checkPreconditions(history)) {
transitionApplied = true;
ParseConfiguration configuration = new ParseConfiguration(history);
if (decision.isStatistical())
configuration.addDecision(decision);
transition.apply(configuration);
int nextHeapIndex = parseComparisonStrategy.getComparisonIndex(configuration) * 1000;
if (configuration.isTerminal()) {
nextHeapIndex = Integer.MAX_VALUE;
} else {
while (nextHeapIndex <= currentHeapIndex) nextHeapIndex++;
}
PriorityQueue<ParseConfiguration> nextHeap = heaps.get(nextHeapIndex);
if (nextHeap == null) {
if (configuration.isTerminal())
nextHeap = terminalHeap;
else
nextHeap = new PriorityQueue<>();
heaps.put(nextHeapIndex, nextHeap);
if (LOG.isTraceEnabled())
LOG.trace("Created heap with index: " + nextHeapIndex);
}
nextHeap.add(configuration);
if (LOG.isTraceEnabled()) {
LOG.trace("Added configuration with score " + configuration.getScore() + " to heap: " + nextHeapIndex + ", total size: " + nextHeap.size());
}
configuration.clearMemory();
} else {
if (LOG.isTraceEnabled())
LOG.trace("Cannot apply transition: doesn't meet pre-conditions");
// just in case the we run out of both heaps and
// analyses, we build this backup heap
backupHeap.add(history);
}
// does transition meet pre-conditions?
}
if (transitionApplied) {
j++;
} else {
LOG.trace("No transitions could be applied: not counting this history as part of the beam");
}
// beam width test
if (j == maxSequences)
break;
}
// next history
}
// next atomic index
// return the best sequences on the heap
List<ParseConfiguration> bestConfigurations = new ArrayList<>();
int i = 0;
if (finalHeap.isEmpty())
finalHeap = backupHeap;
while (!finalHeap.isEmpty()) {
bestConfigurations.add(finalHeap.poll());
i++;
if (i >= this.getBeamWidth())
break;
}
if (LOG.isDebugEnabled()) {
for (ParseConfiguration finalConfiguration : bestConfigurations) {
LOG.debug(df.format(finalConfiguration.getScore()) + ": " + finalConfiguration.toString());
LOG.debug("Pos tag sequence: " + finalConfiguration.getPosTagSequence());
LOG.debug("Transitions: " + finalConfiguration.getTransitions());
LOG.debug("Decisions: " + finalConfiguration.getDecisions());
if (LOG.isTraceEnabled()) {
StringBuilder sb = new StringBuilder();
for (Decision decision : finalConfiguration.getDecisions()) {
sb.append(" * ");
sb.append(df.format(decision.getProbability()));
}
sb.append(" root ");
sb.append(finalConfiguration.getTransitions().size());
LOG.trace(sb.toString());
sb = new StringBuilder();
sb.append(" * PosTag sequence score ");
sb.append(df.format(finalConfiguration.getPosTagSequence().getScore()));
sb.append(" = ");
for (PosTaggedToken posTaggedToken : finalConfiguration.getPosTagSequence()) {
sb.append(" * ");
sb.append(df.format(posTaggedToken.getDecision().getProbability()));
}
sb.append(" root ");
sb.append(finalConfiguration.getPosTagSequence().size());
LOG.trace(sb.toString());
sb = new StringBuilder();
sb.append(" * Token sequence score = ");
sb.append(df.format(finalConfiguration.getPosTagSequence().getTokenSequence().getScore()));
LOG.trace(sb.toString());
}
}
}
return bestConfigurations;
}
use of com.joliciel.talismane.machineLearning.features.RuntimeEnvironment in project talismane by joliciel-informatique.
the class ParseEventStream method next.
@Override
public ClassificationEvent next() throws TalismaneException, IOException {
ClassificationEvent event = null;
if (this.hasNext()) {
eventCount++;
LOG.debug("Event " + eventCount + ": " + currentConfiguration.toString());
List<FeatureResult<?>> parseFeatureResults = new ArrayList<FeatureResult<?>>();
for (ParseConfigurationFeature<?> parseFeature : parseFeatures) {
RuntimeEnvironment env = new RuntimeEnvironment();
FeatureResult<?> featureResult = parseFeature.check(currentConfiguration, env);
if (featureResult != null) {
parseFeatureResults.add(featureResult);
}
}
if (LOG.isTraceEnabled()) {
SortedSet<String> featureResultSet = parseFeatureResults.stream().map(f -> f.toString()).collect(Collectors.toCollection(() -> new TreeSet<String>()));
for (String featureResultString : featureResultSet) {
LOG.trace(featureResultString);
}
}
Transition transition = targetConfiguration.getTransitions().get(currentIndex);
String classification = transition.getCode();
event = new ClassificationEvent(parseFeatureResults, classification);
// apply the transition and up the index
currentConfiguration = new ParseConfiguration(currentConfiguration);
transition.apply(currentConfiguration);
currentIndex++;
if (currentIndex == targetConfiguration.getTransitions().size()) {
targetConfiguration = null;
}
}
return event;
}
use of com.joliciel.talismane.machineLearning.features.RuntimeEnvironment in project talismane by joliciel-informatique.
the class SentenceDetector method detectSentences.
/**
* Detect sentences within an annotated text. Sentences are added in the form
* of an Annotation around a {@link SentenceBoundary}, with the start position
* (relative to the start of the annotated text) at the start of the sentence
* and the end position immediately after the end of the sentence. <br>
* <br>
* Sentence boundaries will not be detected within any annotation of type
* {@link RawTextNoSentenceBreakMarker}, nor will they be detected before or
* after the {@link AnnotatedText#getAnalysisStart()} and
* {@link AnnotatedText#getAnalysisEnd()} respectively. <br>
* <br>
* If the text contained existing {@link SentenceBoundary} annotations before
* analysis start, the first sentence will begin where the last existing
* annotation ended. Otherwise, the first boundary will begin at position 0.
* <br>
* <br>
* If the text's analysis end is equal to the text length, it is assumed that
* the text end is a sentence boundary. In this case, an additional sentence
* is added starting at the final detected boundary and ending at text end.
*
* @param text
* the annotated text in which we need to detect sentences.
* @return in addition to the annotations added, we return a List of integers
* marking the end position of each sentence boundary.
*/
public List<Integer> detectSentences(AnnotatedText text, String... labels) throws TalismaneException {
LOG.debug("detectSentences");
List<Annotation<RawTextNoSentenceBreakMarker>> noSentenceBreakMarkers = text.getAnnotations(RawTextNoSentenceBreakMarker.class);
Matcher matcher = possibleBoundaryPattern.matcher(text.getText());
List<Integer> possibleBoundaries = new ArrayList<>();
while (matcher.find()) {
if (matcher.start() >= text.getAnalysisStart() && matcher.start() < text.getAnalysisEnd()) {
boolean noSentences = false;
int position = matcher.start();
for (Annotation<RawTextNoSentenceBreakMarker> noSentenceBreakMarker : noSentenceBreakMarkers) {
if (noSentenceBreakMarker.getStart() <= position && position < noSentenceBreakMarker.getEnd()) {
noSentences = true;
break;
}
}
if (!noSentences)
possibleBoundaries.add(position);
}
}
// collect all deterministic sentence boundaries
List<Annotation<RawTextSentenceBreakMarker>> sentenceBreakMarkers = text.getAnnotations(RawTextSentenceBreakMarker.class);
Set<Integer> guessedBoundaries = new TreeSet<>(sentenceBreakMarkers.stream().filter(f -> f.getEnd() >= text.getAnalysisStart()).map(f -> f.getEnd()).collect(Collectors.toList()));
// Share one token sequence for all possible boundaries, to avoid tokenising
// multiple times
Sentence sentence = new Sentence(text.getText(), sessionId);
TokenSequence tokenSequence = new TokenSequence(sentence, sessionId);
List<PossibleSentenceBoundary> boundaries = new ArrayList<>();
for (int possibleBoundary : possibleBoundaries) {
PossibleSentenceBoundary boundary = new PossibleSentenceBoundary(tokenSequence, possibleBoundary);
if (LOG.isTraceEnabled()) {
LOG.trace("Testing boundary: " + boundary);
LOG.trace(" at position: " + possibleBoundary);
}
List<FeatureResult<?>> featureResults = new ArrayList<>();
for (SentenceDetectorFeature<?> feature : features) {
RuntimeEnvironment env = new RuntimeEnvironment();
FeatureResult<?> featureResult = feature.check(boundary, env);
if (featureResult != null)
featureResults.add(featureResult);
}
if (LOG.isTraceEnabled()) {
SortedSet<String> featureResultSet = featureResults.stream().map(f -> f.toString()).collect(Collectors.toCollection(() -> new TreeSet<String>()));
for (String featureResultString : featureResultSet) {
LOG.trace(featureResultString);
}
}
List<Decision> decisions = this.decisionMaker.decide(featureResults);
if (LOG.isTraceEnabled()) {
for (Decision decision : decisions) {
LOG.trace(decision.getOutcome() + ": " + decision.getProbability());
}
}
if (decisions.get(0).getOutcome().equals(SentenceDetectorOutcome.IS_BOUNDARY.name())) {
if (LOG.isTraceEnabled()) {
LOG.trace("Adding boundary: " + possibleBoundary + 1);
}
guessedBoundaries.add(possibleBoundary + 1);
boundaries.add(boundary);
}
}
if (LOG.isTraceEnabled()) {
LOG.trace("context: " + text.getText().toString().replace('\n', '¶').replace('\r', '¶'));
for (PossibleSentenceBoundary boundary : boundaries) LOG.trace("boundary: " + boundary.toString());
}
if (LOG.isDebugEnabled())
LOG.debug("guessedBoundaries : " + guessedBoundaries.toString());
List<Annotation<SentenceBoundary>> newBoundaries = new ArrayList<>();
int lastBoundary = 0;
List<Annotation<SentenceBoundary>> existingBoundaries = text.getAnnotations(SentenceBoundary.class);
if (existingBoundaries.size() > 0) {
lastBoundary = existingBoundaries.get(existingBoundaries.size() - 1).getEnd();
}
// advance boundary start until a non space character is encountered
while (lastBoundary < text.getAnalysisEnd() && Character.isWhitespace(text.getText().charAt(lastBoundary))) {
lastBoundary++;
}
for (int guessedBoundary : guessedBoundaries) {
if (guessedBoundary > lastBoundary) {
Annotation<SentenceBoundary> sentenceBoundary = new Annotation<>(lastBoundary, guessedBoundary, new SentenceBoundary(), labels);
newBoundaries.add(sentenceBoundary);
if (LOG.isTraceEnabled()) {
LOG.trace("Added boundary: " + sentenceBoundary);
}
lastBoundary = guessedBoundary;
}
}
if (text.getAnalysisEnd() == text.getText().length()) {
if (text.getAnalysisEnd() > lastBoundary) {
Annotation<SentenceBoundary> sentenceBoundary = new Annotation<>(lastBoundary, text.getAnalysisEnd(), new SentenceBoundary(), labels);
newBoundaries.add(sentenceBoundary);
if (LOG.isTraceEnabled()) {
LOG.trace("Added final boundary: " + sentenceBoundary);
}
}
}
text.addAnnotations(newBoundaries);
return new ArrayList<>(guessedBoundaries);
}
use of com.joliciel.talismane.machineLearning.features.RuntimeEnvironment in project talismane by joliciel-informatique.
the class SentenceDetectorEventStream method next.
@Override
public ClassificationEvent next() throws TalismaneException, IOException {
ClassificationEvent event = null;
if (this.hasNext()) {
int possibleBoundary = possibleBoundaries.get(currentIndex++);
String moreText = "";
int sentenceIndex = 0;
while (moreText.length() < minCharactersAfterBoundary) {
String nextSentence = "";
if (sentenceIndex < sentences.size()) {
nextSentence = sentences.get(sentenceIndex);
} else if (corpusReader.hasNextSentence()) {
nextSentence = corpusReader.nextSentence().getText().toString();
sentences.add(nextSentence);
} else {
break;
}
if (nextSentence.startsWith(" ") || nextSentence.startsWith("\n"))
moreText += sentences.get(sentenceIndex);
else
moreText += " " + sentences.get(sentenceIndex);
sentenceIndex++;
}
String text = previousSentence + currentSentence + moreText;
PossibleSentenceBoundary boundary = new PossibleSentenceBoundary(text, possibleBoundary, sessionId);
LOG.debug("next event, boundary: " + boundary);
List<FeatureResult<?>> featureResults = new ArrayList<FeatureResult<?>>();
for (SentenceDetectorFeature<?> feature : features) {
RuntimeEnvironment env = new RuntimeEnvironment();
FeatureResult<?> featureResult = feature.check(boundary, env);
if (featureResult != null)
featureResults.add(featureResult);
}
if (LOG.isTraceEnabled()) {
SortedSet<String> featureResultSet = featureResults.stream().map(f -> f.toString()).collect(Collectors.toCollection(() -> new TreeSet<String>()));
for (String featureResultString : featureResultSet) {
LOG.trace(featureResultString);
}
}
String classification = SentenceDetectorOutcome.IS_NOT_BOUNDARY.name();
if (possibleBoundary == realBoundary)
classification = SentenceDetectorOutcome.IS_BOUNDARY.name();
event = new ClassificationEvent(featureResults, classification);
if (currentIndex == possibleBoundaries.size()) {
if (currentSentence.endsWith(" "))
previousSentence = currentSentence;
else
previousSentence = currentSentence + " ";
currentSentence = null;
}
}
return event;
}
Aggregations