<commit_before>/*
 * Copyright © 2017 <NAME>, 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 co.cask.mmds.manager;

import co.cask.cdap.api.common.Bytes;
import co.cask.cdap.api.data.schema.Schema;
import co.cask.cdap.api.dataset.lib.FileSet;
import co.cask.cdap.api.dataset.lib.PartitionedFileSet;
import co.cask.cdap.api.dataset.table.Table;
import co.cask.cdap.api.service.http.HttpServiceRequest;
import co.cask.cdap.api.service.http.HttpServiceResponder;
import co.cask.cdap.api.spark.service.SparkHttpServiceContext;
import co.cask.cdap.api.spark.service.SparkHttpServiceHandler;
import co.cask.cdap.api.spark.sql.DataFrames;
import co.cask.cdap.internal.io.SchemaTypeAdapter;
import co.cask.mmds.ModelLogging;
import co.cask.mmds.api.Modeler;
import co.cask.mmds.data.DataSplit;
import co.cask.mmds.data.DataSplitInfo;
import co.cask.mmds.data.DataSplitStats;
import co.cask.mmds.data.DataSplitTable;
import co.cask.mmds.data.Experiment;
import co.cask.mmds.data.ExperimentMetaTable;
import co.cask.mmds.data.ExperimentStore;
import co.cask.mmds.data.ModelKey;
import co.cask.mmds.data.ModelMeta;
import co.cask.mmds.data.ModelTable;
import co.cask.mmds.data.ModelTrainerInfo;
import co.cask.mmds.data.SplitKey;
import co.cask.mmds.manager.runner.AlgorithmSpec;
import co.cask.mmds.manager.runner.EnumStringTypeAdapterFactory;
import co.cask.mmds.manager.runner.PipelineExecutor;
import co.cask.mmds.modeler.Modelers;
import co.cask.mmds.modeler.param.spec.ParamSpec;
import co.cask.mmds.modeler.train.ModelOutput;
import co.cask.mmds.modeler.train.ModelOutputWriter;
import co.cask.mmds.modeler.train.ModelTrainer;
import co.cask.mmds.proto.BadRequestException;
import co.cask.mmds.proto.CreateModelRequest;
import co.cask.mmds.proto.EndpointException;
import co.cask.mmds.proto.TrainModelRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.types.StructType;
import org.apache.tephra.TransactionFailureException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;

/**
 * Model Service handler
 */
public class ModelManagerServiceHandler implements SparkHttpServiceHandler {
  private static final Logger LOG = LoggerFactory.getLogger(ModelManagerServiceHandler.class);
  private static final Gson GSON = new GsonBuilder()
    .registerTypeAdapter(Schema.class, new SchemaTypeAdapter())
    .registerTypeAdapterFactory(new EnumStringTypeAdapterFactory())
    .serializeSpecialFloatingPointValues()
    .create();
  private String modelMetaDataset;
  private String modelComponentsDataset;
  private String experimentMetaDataset;
  private String splitsDataset;
  private ModelOutputWriter modelOutputWriter;
  private SparkSession sparkSession;
  private SparkHttpServiceContext context;
  private PipelineExecutor pipelineExecutor;

  @Override
  public void initialize(SparkHttpServiceContext context) throws Exception {
    this.context = context;
    sparkSession = context.getSparkSession();
    Map<String, String> properties = context.getSpecification().getProperties();
    modelMetaDataset = properties.get("modelMetaDataset");
    modelComponentsDataset = properties.get("modelComponentsDataset");
    experimentMetaDataset = properties.get("experimentMetaDataset");
    splitsDataset = properties.get("splitsDataset");
    pipelineExecutor = new PipelineExecutor(context.getNamespace());
    context.execute(datasetContext -> {
      FileSet modelComponents = datasetContext.getDataset(modelComponentsDataset);
      modelOutputWriter = new ModelOutputWriter(context.getAdmin(), context,
                                                modelComponents.getBaseLocation(), true);
    });
  }

  @Override
  public void destroy() {
    // no-op
  }

  @GET
  @Path("/algorithms")
  public void listAlgorithms(HttpServiceRequest request, HttpServiceResponder responder) {
    List<AlgorithmSpec> algorithms = new ArrayList<>();
    for (Modeler modeler : Modelers.getModelers()) {
      List<ParamSpec> paramSpecs = modeler.getParams(new HashMap<>()).getSpec();
      algorithms.add(new AlgorithmSpec(modeler.getAlgorithm(), paramSpecs));
    }
    responder.sendString(GSON.toJson(algorithms));
  }

  @GET
  @Path("/algorithms/{algorithm}")
  public void getAlgorithm(HttpServiceRequest request, HttpServiceResponder responder,
                           @PathParam("algorithm") String algorithm) {
    Modeler modeler = Modelers.getModeler(algorithm);
    if (modeler == null) {
      responder.sendError(404, "Algorithm " + algorithm + " not found.");
      return;
    }
    List<ParamSpec> paramSpecs = modeler.getParams(new HashMap<>()).getSpec();
    responder.sendString(GSON.toJson(new AlgorithmSpec(modeler.getAlgorithm(), paramSpecs)));
  }

  /**
   * Get List of {@link Experiment}s.
   *
   * @param request http request
   * @param responder http response containing list of experiments as json string
   */
  @GET
  @Path("/experiments")
  public void listExperiments(HttpServiceRequest request, HttpServiceResponder responder,
                              final @QueryParam("offset") @DefaultValue("0") int offset,
                              final @QueryParam("limit") @DefaultValue("20") int limit,
                              final @QueryParam("srcPath") @DefaultValue("") String srcPath) {
    runInTx(responder, store -> {
      validate(offset, limit);
      responder.sendString(GSON.toJson(store.listExperiments(offset, limit, e -> e.getSrcpath().equals(srcPath))));
    });
  }

  private void validate(int offset, int limit) {
    if (offset < 0) {<commit_msg>Fixing a minor bug in filter<commit_after>/*
 * Copyright © 2017 <NAME>, 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 co.cask.mmds.manager;

import co.cask.cdap.api.common.Bytes;
import co.cask.cdap.api.data.schema.Schema;
import co.cask.cdap.api.dataset.lib.FileSet;
import co.cask.cdap.api.dataset.lib.PartitionedFileSet;
import co.cask.cdap.api.dataset.table.Table;
import co.cask.cdap.api.service.http.HttpServiceRequest;
import co.cask.cdap.api.service.http.HttpServiceResponder;
import co.cask.cdap.api.spark.service.SparkHttpServiceContext;
import co.cask.cdap.api.spark.service.SparkHttpServiceHandler;
import co.cask.cdap.api.spark.sql.DataFrames;
import co.cask.cdap.internal.io.SchemaTypeAdapter;
import co.cask.mmds.ModelLogging;
import co.cask.mmds.api.Modeler;
import co.cask.mmds.data.DataSplit;
import co.cask.mmds.data.DataSplitInfo;
import co.cask.mmds.data.DataSplitStats;
import co.cask.mmds.data.DataSplitTable;
import co.cask.mmds.data.Experiment;
import co.cask.mmds.data.ExperimentMetaTable;
import co.cask.mmds.data.ExperimentStore;
import co.cask.mmds.data.ModelKey;
import co.cask.mmds.data.ModelMeta;
import co.cask.mmds.data.ModelTable;
import co.cask.mmds.data.ModelTrainerInfo;
import co.cask.mmds.data.SplitKey;
import co.cask.mmds.manager.runner.AlgorithmSpec;
import co.cask.mmds.manager.runner.EnumStringTypeAdapterFactory;
import co.cask.mmds.manager.runner.PipelineExecutor;
import co.cask.mmds.modeler.Modelers;
import co.cask.mmds.modeler.param.spec.ParamSpec;
import co.cask.mmds.modeler.train.ModelOutput;
import co.cask.mmds.modeler.train.ModelOutputWriter;
import co.cask.mmds.modeler.train.ModelTrainer;
import co.cask.mmds.proto.BadRequestException;
import co.cask.mmds.proto.CreateModelRequest;
import co.cask.mmds.proto.EndpointException;
import co.cask.mmds.proto.TrainModelRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.types.StructType;
import org.apache.tephra.TransactionFailureException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;

/**
 * Model Service handler
 */
public class ModelManagerServiceHandler implements SparkHttpServiceHandler {
  private static final Logger LOG = LoggerFactory.getLogger(ModelManagerServiceHandler.class);
  private static final Gson GSON = new GsonBuilder()
    .registerTypeAdapter(Schema.class, new SchemaTypeAdapter())
    .registerTypeAdapterFactory(new EnumStringTypeAdapterFactory())
    .serializeSpecialFloatingPointValues()
    .create();
  private String modelMetaDataset;
  private String modelComponentsDataset;
  private String experimentMetaDataset;
  private String splitsDataset;
  private ModelOutputWriter modelOutputWriter;
  private SparkSession sparkSession;
  private SparkHttpServiceContext context;
  private PipelineExecutor pipelineExecutor;

  @Override
  public void initialize(SparkHttpServiceContext context) throws Exception {
    this.context = context;
    sparkSession = context.getSparkSession();
    Map<String, String> properties = context.getSpecification().getProperties();
    modelMetaDataset = properties.get("modelMetaDataset");
    modelComponentsDataset = properties.get("modelComponentsDataset");
    experimentMetaDataset = properties.get("experimentMetaDataset");
    splitsDataset = properties.get("splitsDataset");
    pipelineExecutor = new PipelineExecutor(context.getNamespace());
    context.execute(datasetContext -> {
      FileSet modelComponents = datasetContext.getDataset(modelComponentsDataset);
      modelOutputWriter = new ModelOutputWriter(context.getAdmin(), context,
                                                modelComponents.getBaseLocation(), true);
    });
  }

  @Override
  public void destroy() {
    // no-op
  }

  @GET
  @Path("/algorithms")
  public void listAlgorithms(HttpServiceRequest request, HttpServiceResponder responder) {
    List<AlgorithmSpec> algorithms = new ArrayList<>();
    for (Modeler modeler : Modelers.getModelers()) {
      List<ParamSpec> paramSpecs = modeler.getParams(new HashMap<>()).getSpec();
      algorithms.add(new AlgorithmSpec(modeler.getAlgorithm(), paramSpecs));
    }
    responder.sendString(GSON.toJson(algorithms));
  }

  @GET
  @Path("/algorithms/{algorithm}")
  public void getAlgorithm(HttpServiceRequest request, HttpServiceResponder responder,
                           @PathParam("algorithm") String algorithm) {
    Modeler modeler = Modelers.getModeler(algorithm);
    if (modeler == null) {
      responder.sendError(404, "Algorithm " + algorithm + " not found.");
      return;
    }
    List<ParamSpec> paramSpecs = modeler.getParams(new HashMap<>()).getSpec();
    responder.sendString(GSON.toJson(new AlgorithmSpec(modeler.getAlgorithm(), paramSpecs)));
  }

  /**
   * Get List of {@link Experiment}s.
   *
   * @param request http request
   * @param responder http response containing list of experiments as json string
   */
  @GET
  @Path("/experiments")
  public void listExperiments(HttpServiceRequest request, HttpServiceResponder responder,
                              final @QueryParam("offset") @DefaultValue("0") int offset,
                              final @QueryParam("limit") @DefaultValue("20") int limit,
                              final @QueryParam("srcPath") @DefaultValue("") String srcPath) {
    runInTx(responder, store -> {
      validate(offset, limit);
      Predicate<Experiment> predicate = srcPath.isEmpty() ? null : e -> e.getSrcpath().equals(srcPath);
      responder.sendString(GSON.toJson(store.listExperiments(offset, limit, predicate)));
    });
  }

  private void validate(int offset, int limit) {
    if (offset < 0) {
{'fraction_non_alphanumeric': 0.10924677608440797, 'fraction_numerical': 0.0024912075029308325, 'mean_word_length': 4.442185007974482, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4942489', 'n_tokens_mistral': 4151, 'n_tokens_neox': 4064, 'n_words': 854}