package org.deeplearning4j.spark.models.sequencevectors.functions;

import lombok.NonNull;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.broadcast.Broadcast;
import org.deeplearning4j.models.embeddings.loader.VectorsConfiguration;
import org.deeplearning4j.models.sequencevectors.sequence.Sequence;
import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement;
import org.nd4j.parameterserver.distributed.VoidParameterServer;
import org.nd4j.parameterserver.distributed.conf.VoidConfiguration;

import java.util.ArrayList;
import java.util.List;

/**
 * This function builds RDD of vocab words
 *
 * On top of that, we use this Function to launch VoidParameterServer
 *
 * @author raver119@gmail.com
 */
public class VocabRddFunction<T extends SequenceElement> implements FlatMapFunction<Sequence<T>, T> {
    protected Broadcast<VectorsConfiguration> vectorsConfigurationBroadcast;
    protected Broadcast<VoidConfiguration> paramServerConfigurationBroadcast;

    protected transient VectorsConfiguration configuration;

    public VocabRddFunction(@NonNull Broadcast<VectorsConfiguration> vectorsConfigurationBroadcast, @NonNull Broadcast<VoidConfiguration> paramServerConfigurationBroadcast) {
        this.vectorsConfigurationBroadcast = vectorsConfigurationBroadcast;
        this.paramServerConfigurationBroadcast = paramServerConfigurationBroadcast;
    }

    @Override
    public Iterable<T> call(Sequence<T> sequence) throws Exception {
        if (configuration == null)
            configuration = vectorsConfigurationBroadcast.getValue();

        // we just silently initialize server
        VoidParameterServer.getInstance().init(paramServerConfigurationBroadcast.getValue());

        // TODO: call for initializeSeqVec here

        List<T> elements = new ArrayList<>();

        elements.addAll(sequence.getElements());

        // FIXME: this is PROBABLY bad, we might want to ensure, there's no duplicates.
        if (configuration.isTrainSequenceVectors())
            if (sequence.getSequenceLabels().size() > 0)
                elements.addAll(sequence.getSequenceLabels());

        return elements;
    }
}

@@ -84,16 +84,50 @@
 onNull;%0A
+import lombok.extern.slf4j.Slf4j;%0A
 import o
@@ -173,24 +173,24 @@
 apFunction;%0A
-
 import org.a
@@ -781,16 +781,23 @@
 com%0A */%0A
+@Slf4j%0A
 public c
@@ -1437,24 +1437,75 @@
 onBroadcast;
+%0A%0A        log.info(%22VocabRDDFunction constructor%22);
 %0A    %7D%0A%0A    
@@ -1618,16 +1618,16 @@
 = null)%0A
-
         
@@ -1685,24 +1685,133 @@
 etValue();%0A%0A
+        log.info(%22Initializing VoidParameterServer...%22);%0A        System.out.println(%22Initializing VPS...%22);%0A%0A
         // w

debug info