import java.io.*;
import java.util.Arrays;

import opennlp.tools.util.*;
import opennlp.tools.postag.*;
import opennlp.tools.chunker.*;
import opennlp.tools.cmdline.postag.POSModelLoader;
import opennlp.tools.tokenize.*;



public class OpenNLPTaggerChunker {
	/**
	 * Returns the chunker output ofr each token in this sentence.
	 * @param s
	 * @return
	 * @throws IOException 
	 * @throws Exception 
	 */
	
	POSModel model;
	POSTaggerME tagger;
	InputStream is;
	ChunkerModel cModel;
	ChunkerME chunkerME;
	String tokens [];
	String tags [];
	String chunks [];
	String taggedResult;
	/**
	 * Constructor to load tagger and chunker models
	 * and make ready for sentence wise tagging/chunking
	 * @throws Exception
	 */
	public OpenNLPTaggerChunker() throws Exception {
	    model = new POSModelLoader().load(new File("./models/en-pos-maxent.bin"));
		tagger = new POSTaggerME(model);
		is = new FileInputStream("./models/en-chunker.bin");
		cModel = new ChunkerModel(is);
		chunkerME = new ChunkerME(cModel);
	}

	/**
	 * Tag a sentence and return the tags in the String array
	 * @param s sentence
	 * @return Array of tags
	 */
	public String [] tag (String s) {
		tokens = WhitespaceTokenizer.INSTANCE.tokenize(s);
		tags = tagger.tag(tokens);
		POSSample sample = new POSSample(tokens, tags);
		taggedResult = sample.toString();
		return tags;
	}
	/**
	 * Get the tagged output
	 * @return
	 */
	public String getTaggedSentence(){
		return taggedResult;
	}
	public String [] chunk (String s){
		chunks = chunkerME.chunk(tokens, tags);
		return chunks;
	}
	public void printChunkSpans(String s){
		Span[] span = chunkerME.chunkAsSpans(tokens, tags);
		for (Span sp : span)
			System.out.println(sp.toString());
	}

	public static void main(String a []) throws Exception {
		
		OpenNLPTaggerChunker model = new OpenNLPTaggerChunker();
		String input = "I don't want to tag this simple sentence because of PC's .";
		String tags [] = model.tag(input);
		String chunks [] = model.chunk(input);
		String tokens [] = model.tokens;
		
		System.out.println("The tokens: \n" + Arrays.asList(tokens));
		System.out.println("The tags: \n" + Arrays.asList(tags));
		System.out.println("The chunks: \n" + Arrays.asList(chunks) + "\n");
		System.out.println(model.getTaggedSentence() + "\n");
		model.printChunkSpans(input);
		 
		
		
		
	}

}
