/*
 *
 *  * Copyright 2015 Skymind,Inc.
 *  *
 *  *    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 org.deeplearning4j.spark.text;

import org.apache.spark.api.java.function.Function;
import org.deeplearning4j.berkeley.Pair;
import org.deeplearning4j.text.tokenization.tokenizerfactory.DefaultTokenizerFactory;
import org.deeplearning4j.text.tokenization.tokenizerfactory.NGramTokenizerFactory;
import org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory;

import java.util.List;

/**
 * Tokenizer function
 * @author Adam Gibson
 */
public class TokenizerFunction implements Function<String,Pair<List<String>,Long>> {
    private  String tokenizerFactoryClazz;
    private transient TokenizerFactory tokenizerFactory;
    private int nGrams = 1;
    public TokenizerFunction(String clazz) {
        tokenizerFactoryClazz = clazz;

    }
    public TokenizerFunction(int nGrams) {
        this(DefaultTokenizerFactory.class.getName());
        this.nGrams = nGrams;
    }

    public TokenizerFunction() {
        this(DefaultTokenizerFactory.class.getName());
    }

    /**
     * Allow for customization of ngrams being returned
     * @param tokenizer
     * @param nGrams
     */
    public TokenizerFunction(String tokenizer, int nGrams) {
        this.tokenizerFactoryClazz = tokenizer;
        this.nGrams = nGrams;
    }

    @Override
    public Pair<List<String>,Long> call(String v1) throws Exception {
        if(tokenizerFactory == null)
            tokenizerFactory = getTokenizerFactory();
        List<String> tokens = tokenizerFactory.create(v1).getTokens();
        return new Pair<>(tokens, (long) tokens.size());
    }
    private TokenizerFactory getTokenizerFactory() {
        try {
            Class<? extends TokenizerFactory> clazz = (Class<? extends TokenizerFactory>) Class.forName(tokenizerFactoryClazz);
            tokenizerFactory = clazz.newInstance();
            if(nGrams > 1) {
                tokenizerFactory = new NGramTokenizerFactory(tokenizerFactory,nGrams,nGrams);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
      return tokenizerFactory;
    }

}

@@ -1045,16 +1045,41 @@
 ctory;%0A%0A
+import java.util.Arrays;%0A
 import j
@@ -2115,24 +2115,102 @@
 rFactory();%0A
+        if(v1.isEmpty())%0A            return new Pair%3C%3E(Arrays.asList(%22%22),1L);%0A
         List

add workaround for empty token