index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/distribution
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/distribution/output/DistributionOutput.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.distribution.output; import ai.djl.ndarray.NDList; import ai.djl.timeseries.distribution.Distribution; import ai.djl.util.PairList; /** A class to construct a distribution given the output of a network. */ public abstract class DistributionOutput { protected PairList<String, Integer> argsDim; private float valueInSupport; /** * A float that will have a valid numeric value when computing the log-loss of the corresponding * distribution. * * <p>By default {@code 0f}. This value will be used when padding data series. * * @return the valueInSupport */ public float getValueInSupport() { return valueInSupport; } /** * Return the corresponding projection block based on the arguments dimension of different * distributions. * * @return the corresponding projection block */ public ArgProj getArgsProj() { return ArgProj.builder().setArgsDim(argsDim).setDomainMap(this::domainMap).build(); } /** * Return the corresponding projection block based on the arguments dimension of different * ditributions. * * @param prefix the prefix string of projection layer block * @return the corresponding projection block */ public ArgProj getArgsProj(String prefix) { return ArgProj.builder() .setArgsDim(argsDim) .setDomainMap(this::domainMap) .optPrefix(prefix) .build(); } /** * Return an array containing all the argument names. * * @return an array containing all the argument names */ public String[] getArgsArray() { return argsDim.keyArray(new String[argsDim.size()]); } /** * Convert arguments to the right shape and domain. The domain depends on the type of * distribution, while the correct shape is obtained by reshaping the trailing axis in such a * way that the returned tensors define a distribution of the right event_shape. * * <p>This function is usually used as the lambda of the Lambda block. * * @param arrays the arguments * @return converted arguments */ public abstract NDList domainMap(NDList arrays); /** * Return the associated {@code DistributionBuilder}, given the collection of constructor * arguments and, optionally, a scale tensor. * * @return the associated {@code DistributionBuilder} */ public abstract Distribution.DistributionBuilder<?> distributionBuilder(); }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/distribution
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/distribution/output/NegativeBinomialOutput.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.distribution.output; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.timeseries.distribution.Distribution; import ai.djl.timeseries.distribution.NegativeBinomial; import ai.djl.util.PairList; /** * {@code NegativeBinomialOutput} is a {@link DistributionOutput} for the negative binomial * distribution. */ public final class NegativeBinomialOutput extends DistributionOutput { /** * Construct a negative binomial output with two arguments, {@code total_count} and {@code * logits}. */ public NegativeBinomialOutput() { argsDim = new PairList<>(2); argsDim.add("total_count", 1); argsDim.add("logits", 1); } /** {@inheritDoc} */ @Override public NDList domainMap(NDList arrays) { NDArray totalCount = arrays.get(0); NDArray logits = arrays.get(1); totalCount = totalCount.getNDArrayInternal().softPlus().squeeze(-1); logits = logits.squeeze(-1); totalCount.setName("total_count"); logits.setName("logits"); return new NDList(totalCount, logits); } /** {@inheritDoc} */ @Override public Distribution.DistributionBuilder<?> distributionBuilder() { return NegativeBinomial.builder(); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/distribution
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/distribution/output/StudentTOutput.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.distribution.output; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.timeseries.distribution.Distribution; import ai.djl.timeseries.distribution.StudentT; import ai.djl.util.PairList; /** {@code StudentTOutput} is a {@link DistributionOutput} for the Student's t-test distribution. */ public class StudentTOutput extends DistributionOutput { /** Construct a negative binomial output with two arguments, {@code mu} and {@code sigma}. */ public StudentTOutput() { argsDim = new PairList<>(3); argsDim.add("mu", 1); argsDim.add("sigma", 1); argsDim.add("nu", 1); } /** {@inheritDoc} */ @Override public NDList domainMap(NDList arrays) { NDArray mu = arrays.get(0); NDArray sigma = arrays.get(1); NDArray nu = arrays.get(2); mu = mu.squeeze(-1); sigma = sigma.getNDArrayInternal().softPlus().squeeze(-1); nu = nu.getNDArrayInternal().softPlus().add(2.).squeeze(-1); // TODO: make setName() must be implemented mu.setName("mu"); sigma.setName("sigma"); nu.setName("nu"); return new NDList(mu, sigma, nu); } /** {@inheritDoc} */ @Override public Distribution.DistributionBuilder<?> distributionBuilder() { return StudentT.builder(); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/distribution
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/distribution/output/package-info.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains classes to support construct distribution and project arguments. */ package ai.djl.timeseries.distribution.output;
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/evaluator/Rmsse.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.evaluator; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; import ai.djl.ndarray.NDList; import ai.djl.timeseries.distribution.output.DistributionOutput; import ai.djl.training.evaluator.Evaluator; import ai.djl.util.Pair; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** A class used to calculate Root Mean Squared Scaled Error. */ public class Rmsse extends Evaluator { private DistributionOutput distributionOutput; private int axis; private Map<String, Float> totalLoss; /** * Creates an evaluator that computes Root Mean Squared Scaled Error across axis 1. * * <p>Please referring <a * href=https://www.kaggle.com/competitions/m5-forecasting-accuracy/overview/evaluation>https://www.kaggle.com/competitions/m5-forecasting-accuracy/overview/evaluation</a> * for more details. * * @param distributionOutput the {@link DistributionOutput} to construct the target distribution */ public Rmsse(DistributionOutput distributionOutput) { this("RMSSE", 1, distributionOutput); } /** * Creates an evaluator that computes Root Mean Squared Scaled Error across axis 1. * * <p>Please referring <a * href=https://www.kaggle.com/competitions/m5-forecasting-accuracy/overview/evaluation>https://www.kaggle.com/competitions/m5-forecasting-accuracy/overview/evaluation</a> * for more details. * * @param name the name of the evaluator, default is "RMSSE" * @param axis the axis that represent time length in prediction, default 1 * @param distributionOutput the {@link DistributionOutput} to construct the target distribution */ public Rmsse(String name, int axis, DistributionOutput distributionOutput) { super(name); this.axis = axis; this.distributionOutput = distributionOutput; totalLoss = new ConcurrentHashMap<>(); } protected Pair<Long, NDArray> evaluateHelper(NDList labels, NDList predictions) { NDArray label = labels.head(); NDArray prediction = distributionOutput.distributionBuilder().setDistrArgs(predictions).build().mean(); checkLabelShapes(label, prediction); NDArray meanSquare = label.sub(prediction).square().mean(new int[] {axis}); NDArray scaleDenom = label.get(":, 1:").sub(label.get(":, :-1")).square().mean(new int[] {axis}); NDArray rmsse = meanSquare.div(scaleDenom).sqrt(); rmsse = NDArrays.where(scaleDenom.eq(0), rmsse.onesLike(), rmsse); long total = rmsse.countNonzero().getLong(); return new Pair<>(total, rmsse); } /** {@inheritDoc} */ @Override public NDArray evaluate(NDList labels, NDList predictions) { return evaluateHelper(labels, predictions).getValue(); } /** {@inheritDoc} */ @Override public void addAccumulator(String key) { totalInstances.put(key, 0L); totalLoss.put(key, 0f); } /** {@inheritDoc} */ @Override public void updateAccumulator(String key, NDList labels, NDList predictions) { updateAccumulators(new String[] {key}, labels, predictions); } /** {@inheritDoc} */ @Override public void updateAccumulators(String[] keys, NDList labels, NDList predictions) { Pair<Long, NDArray> update = evaluateHelper(labels, predictions); for (String key : keys) { totalInstances.compute(key, (k, v) -> v + update.getKey()); totalLoss.compute( key, (k, v) -> { try (NDArray array = update.getValue().sum()) { return v + array.getFloat(); } }); } } /** {@inheritDoc} */ @Override public void resetAccumulator(String key) { totalInstances.compute(key, (k, v) -> 0L); totalLoss.compute(key, (k, v) -> 0f); } /** {@inheritDoc} */ @Override public float getAccumulator(String key) { Long total = totalInstances.get(key); if (total == null || total == 0) { return Float.NaN; } return (float) totalLoss.get(key) / totalInstances.get(key); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/evaluator/package-info.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains the evaluator classes. */ package ai.djl.timeseries.evaluator;
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/model
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/model/deepar/DeepARNetwork.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.model.deepar; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.nn.AbstractBlock; import ai.djl.nn.Block; import ai.djl.nn.recurrent.LSTM; import ai.djl.timeseries.block.FeatureEmbedder; import ai.djl.timeseries.block.MeanScaler; import ai.djl.timeseries.block.NopScaler; import ai.djl.timeseries.block.Scaler; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.distribution.output.DistributionOutput; import ai.djl.timeseries.distribution.output.StudentTOutput; import ai.djl.timeseries.timefeature.Lag; import ai.djl.timeseries.timefeature.TimeFeature; import ai.djl.timeseries.transform.ExpectedNumInstanceSampler; import ai.djl.timeseries.transform.InstanceSampler; import ai.djl.timeseries.transform.PredictionSplitSampler; import ai.djl.timeseries.transform.TimeSeriesTransform; import ai.djl.timeseries.transform.convert.AsArray; import ai.djl.timeseries.transform.convert.VstackFeatures; import ai.djl.timeseries.transform.feature.AddAgeFeature; import ai.djl.timeseries.transform.feature.AddObservedValuesIndicator; import ai.djl.timeseries.transform.feature.AddTimeFeature; import ai.djl.timeseries.transform.field.RemoveFields; import ai.djl.timeseries.transform.field.SelectField; import ai.djl.timeseries.transform.field.SetField; import ai.djl.timeseries.transform.split.InstanceSplit; import ai.djl.training.ParameterStore; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Implements the deepar model. * * <p>This closely follows the <a * href="https://linkinghub.elsevier.com/retrieve/pii/S0169207019301888">Salinas et al. 2020</a> and * its <a href="https://github.com/awslabs/gluonts">gluonts</a> implementation. */ public abstract class DeepARNetwork extends AbstractBlock { private static final String[] TRAIN_INPUT_FIELDS = { FieldName.FEAT_STATIC_CAT.name(), FieldName.FEAT_STATIC_REAL.name(), "PAST_" + FieldName.FEAT_TIME.name(), "PAST_" + FieldName.TARGET.name(), "PAST_" + FieldName.OBSERVED_VALUES.name(), "PAST_" + FieldName.IS_PAD.name(), "FUTURE_" + FieldName.FEAT_TIME.name(), "FUTURE_" + FieldName.TARGET.name(), "FUTURE_" + FieldName.OBSERVED_VALUES.name() }; private static final String[] PRED_INPUT_FIELDS = { FieldName.FEAT_STATIC_CAT.name(), FieldName.FEAT_STATIC_REAL.name(), "PAST_" + FieldName.FEAT_TIME.name(), "PAST_" + FieldName.TARGET.name(), "PAST_" + FieldName.OBSERVED_VALUES.name(), "FUTURE_" + FieldName.FEAT_TIME.name(), "PAST_" + FieldName.IS_PAD.name() }; protected String freq; protected int historyLength; protected int contextLength; protected int predictionLength; protected boolean useFeatDynamicReal; protected boolean useFeatStaticCat; protected boolean useFeatStaticReal; protected DistributionOutput distrOutput; protected List<Integer> cardinality; protected List<Integer> embeddingDimension; protected List<Integer> lagsSeq; protected int numParallelSamples; protected FeatureEmbedder embedder; protected Block paramProj; protected LSTM rnn; protected Scaler scaler; DeepARNetwork(Builder builder) { freq = builder.freq; predictionLength = builder.predictionLength; contextLength = builder.contextLength != 0 ? builder.contextLength : predictionLength; distrOutput = builder.distrOutput; cardinality = builder.cardinality; useFeatStaticReal = builder.useFeatStaticReal; useFeatDynamicReal = builder.useFeatDynamicReal; useFeatStaticCat = builder.useFeatStaticCat; numParallelSamples = builder.numParallelSamples; paramProj = addChildBlock("param_proj", distrOutput.getArgsProj()); if (builder.embeddingDimension != null || builder.cardinality == null) { embeddingDimension = builder.embeddingDimension; } else { embeddingDimension = new ArrayList<>(); for (int cat : cardinality) { embeddingDimension.add(Math.min(50, (cat + 1) / 2)); } } lagsSeq = builder.lagsSeq == null ? Lag.getLagsForFreq(builder.freq) : builder.lagsSeq; historyLength = contextLength + lagsSeq.stream().max(Comparator.naturalOrder()).get(); embedder = addChildBlock( "feature_embedder", FeatureEmbedder.builder() .setCardinalities(cardinality) .setEmbeddingDims(embeddingDimension) .build()); if (builder.scaling) { scaler = addChildBlock( "scaler", MeanScaler.builder() .setDim(1) .optKeepDim(true) .optMinimumScale(1e-10f) .build()); } else { scaler = addChildBlock("scaler", NopScaler.builder().setDim(1).optKeepDim(true).build()); } rnn = addChildBlock( "rnn_lstm", LSTM.builder() .setNumLayers(builder.numLayers) .setStateSize(builder.hiddenSize) .optDropRate(builder.dropRate) .optBatchFirst(true) .optReturnState(true) .build()); } /** {@inheritDoc} */ @Override protected void initializeChildBlocks( NDManager manager, DataType dataType, Shape... inputShapes) { Shape targetShape = inputShapes[3].slice(2); Shape contextShape = new Shape(1, contextLength).addAll(targetShape); scaler.initialize(manager, dataType, contextShape, contextShape); long scaleSize = scaler.getOutputShapes(new Shape[] {contextShape, contextShape})[1].get(1); embedder.initialize(manager, dataType, inputShapes[0]); long embeddedCatSize = embedder.getOutputShapes(new Shape[] {inputShapes[0]})[0].get(1); Shape inputShape = new Shape(1, contextLength * 2L - 1).addAll(targetShape); Shape lagsShape = inputShape.add(lagsSeq.size()); long featSize = inputShapes[2].get(2) + embeddedCatSize + inputShapes[1].get(1) + scaleSize; Shape rnnInputShape = lagsShape.slice(0, lagsShape.dimension() - 1).add(lagsShape.tail() + featSize); rnn.initialize(manager, dataType, rnnInputShape); Shape rnnOutShape = rnn.getOutputShapes(new Shape[] {rnnInputShape})[0]; paramProj.initialize(manager, dataType, rnnOutShape); } /** * Applies the underlying RNN to the provided target data and covariates. * * @param ps the parameter store * @param inputs the input NDList * @param training true for a training forward pass * @return a {@link NDList} containing arguments of the output distribution, scaling factor, raw * output of rnn, static input of rnn, output state of rnn */ protected NDList unrollLaggedRnn(ParameterStore ps, NDList inputs, boolean training) { try (NDManager scope = inputs.getManager().newSubManager()) { scope.tempAttachAll(inputs); NDArray featStaticCat = inputs.get(0); NDArray featStaticReal = inputs.get(1); NDArray pastTimeFeat = inputs.get(2); NDArray pastTarget = inputs.get(3); NDArray pastObservedValues = inputs.get(4); NDArray futureTimeFeat = inputs.get(5); NDArray futureTarget = inputs.size() > 6 ? inputs.get(6) : null; NDArray context = pastTarget.get(":,{}:", -contextLength); NDArray observedContext = pastObservedValues.get(":,{}:", -contextLength); NDArray scale = scaler.forward(ps, new NDList(context, observedContext), training).get(1); NDArray priorSequence = pastTarget.get(":,:{}", -contextLength).div(scale); NDArray sequence = futureTarget != null ? context.concat(futureTarget.get(":, :-1"), 1).div(scale) : context.div(scale); NDArray embeddedCat = embedder.forward(ps, new NDList(featStaticCat), training).singletonOrThrow(); NDArray staticFeat = NDArrays.concat(new NDList(embeddedCat, featStaticReal, scale.log()), 1); NDArray expandedStaticFeat = staticFeat.expandDims(1).repeat(1, sequence.getShape().get(1)); NDArray timeFeat = futureTimeFeat != null ? pastTimeFeat .get(":, {}:", -contextLength + 1) .concat(futureTimeFeat, 1) : pastTimeFeat.get(":, {}:", -contextLength + 1); NDArray features = expandedStaticFeat.concat(timeFeat, -1); NDArray lags = laggedSequenceValues(lagsSeq, priorSequence, sequence); NDArray rnnInput = lags.concat(features, -1); NDList outputs = rnn.forward(ps, new NDList(rnnInput), training); NDArray output = outputs.get(0); NDArray hiddenState = outputs.get(1); NDArray cellState = outputs.get(2); NDList params = paramProj.forward(ps, new NDList(output), training); scale.setName("scale"); output.setName("output"); staticFeat.setName("static_feat"); hiddenState.setName("hidden_state"); cellState.setName("cell_state"); return scope.ret( params.addAll(new NDList(scale, output, staticFeat, hiddenState, cellState))); } } /** * Construct an {@link NDArray} of lagged values from a given sequence. * * @param indices indices of lagged observations * @param priorSequence the input sequence prior to the time range for which the output is * required * @param sequence the input sequence in the time range where the output is required * @return the lagged values */ protected NDArray laggedSequenceValues( List<Integer> indices, NDArray priorSequence, NDArray sequence) { if (Collections.max(indices) > (int) priorSequence.getShape().get(1)) { throw new IllegalArgumentException( String.format( "lags cannot go further than prior sequence length, found lag %d while" + " prior sequence is only %d-long", Collections.max(indices), priorSequence.getShape().get(1))); } try (NDManager scope = NDManager.subManagerOf(priorSequence)) { scope.tempAttachAll(priorSequence, sequence); NDArray fullSequence = priorSequence.concat(sequence, 1); NDList lagsValues = new NDList(indices.size()); for (int lagIndex : indices) { long begin = -lagIndex - sequence.getShape().get(1); long end = -lagIndex; lagsValues.add( end < 0 ? fullSequence.get(":, {}:{}", begin, end) : fullSequence.get(":, {}:", begin)); } NDArray lags = NDArrays.stack(lagsValues, -1); return scope.ret(lags.reshape(lags.getShape().get(0), lags.getShape().get(1), -1)); } } /** * Return the context length. * * @return the context length */ public int getContextLength() { return contextLength; } /** * Return the history length. * * @return the history length */ public int getHistoryLength() { return historyLength; } /** * Construct a training transformation of deepar model. * * @param manager the {@link NDManager} to create value * @return the transformation */ public List<TimeSeriesTransform> createTrainingTransformation(NDManager manager) { List<TimeSeriesTransform> transformation = createTransformation(manager); InstanceSampler sampler = new ExpectedNumInstanceSampler(0, 0, predictionLength, 1.0); transformation.add( new InstanceSplit( FieldName.TARGET, FieldName.IS_PAD, FieldName.START, FieldName.FORECAST_START, sampler, historyLength, predictionLength, new FieldName[] {FieldName.FEAT_TIME, FieldName.OBSERVED_VALUES}, distrOutput.getValueInSupport())); transformation.add(new SelectField(TRAIN_INPUT_FIELDS)); return transformation; } /** * Construct a prediction transformation of deepar model. * * @param manager the {@link NDManager} to create value * @return the transformation */ public List<TimeSeriesTransform> createPredictionTransformation(NDManager manager) { List<TimeSeriesTransform> transformation = createTransformation(manager); InstanceSampler sampler = PredictionSplitSampler.newValidationSplitSampler(); transformation.add( new InstanceSplit( FieldName.TARGET, FieldName.IS_PAD, FieldName.START, FieldName.FORECAST_START, sampler, historyLength, predictionLength, new FieldName[] {FieldName.FEAT_TIME, FieldName.OBSERVED_VALUES}, distrOutput.getValueInSupport())); transformation.add(new SelectField(PRED_INPUT_FIELDS)); return transformation; } private List<TimeSeriesTransform> createTransformation(NDManager manager) { List<TimeSeriesTransform> transformation = new ArrayList<>(); List<FieldName> removeFieldNames = new ArrayList<>(); removeFieldNames.add(FieldName.FEAT_DYNAMIC_CAT); if (!useFeatStaticReal) { removeFieldNames.add(FieldName.FEAT_STATIC_REAL); } if (!useFeatDynamicReal) { removeFieldNames.add(FieldName.FEAT_DYNAMIC_REAL); } transformation.add(new RemoveFields(removeFieldNames)); if (!useFeatStaticCat) { transformation.add( new SetField(FieldName.FEAT_STATIC_CAT, manager.zeros(new Shape(1)))); } if (!useFeatDynamicReal) { transformation.add( new SetField(FieldName.FEAT_STATIC_REAL, manager.zeros(new Shape(1)))); } transformation.add(new AsArray(FieldName.FEAT_STATIC_CAT, 1, DataType.INT32)); transformation.add(new AsArray(FieldName.FEAT_STATIC_REAL, 1)); transformation.add( new AddObservedValuesIndicator(FieldName.TARGET, FieldName.OBSERVED_VALUES)); transformation.add( new AddTimeFeature( FieldName.START, FieldName.TARGET, FieldName.FEAT_TIME, TimeFeature.timeFeaturesFromFreqStr(freq), predictionLength, freq)); transformation.add( new AddAgeFeature(FieldName.TARGET, FieldName.FEAT_AGE, predictionLength, true)); FieldName[] inputFields; if (!useFeatDynamicReal) { inputFields = new FieldName[] {FieldName.FEAT_TIME, FieldName.FEAT_AGE}; } else { inputFields = new FieldName[] { FieldName.FEAT_TIME, FieldName.FEAT_AGE, FieldName.FEAT_DYNAMIC_REAL }; } transformation.add(new VstackFeatures(FieldName.FEAT_TIME, inputFields)); return transformation; } /** * Create a builder to build a {@code DeepARTrainingNetwork} or {@code DeepARPredictionNetwork}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** * The builder to construct a {@code DeepARTrainingNetwork} or {@code DeepARPredictionNetwork}. * type of {@link ai.djl.nn.Block}. */ public static final class Builder { private String freq; private int contextLength; private int predictionLength; private int numParallelSamples = 100; private int numLayers = 2; private int hiddenSize = 40; private float dropRate = 0.1f; private boolean useFeatDynamicReal; private boolean useFeatStaticCat; private boolean useFeatStaticReal; private boolean scaling = true; private DistributionOutput distrOutput = new StudentTOutput(); private List<Integer> cardinality; private List<Integer> embeddingDimension; private List<Integer> lagsSeq; /** * Set the prediction frequency. * * @param freq the frequency * @return this builder */ public Builder setFreq(String freq) { this.freq = freq; return this; } /** * Set the prediction length. * * @param predictionLength the prediction length * @return this builder */ public Builder setPredictionLength(int predictionLength) { this.predictionLength = predictionLength; return this; } /** * Set the cardinality for static categorical feature. * * @param cardinality the cardinality * @return this builder */ public Builder setCardinality(List<Integer> cardinality) { this.cardinality = cardinality; return this; } /** * Set the optional {@link DistributionOutput} default {@link StudentTOutput}. * * @param distrOutput the {@link DistributionOutput} * @return this builder */ public Builder optDistrOutput(DistributionOutput distrOutput) { this.distrOutput = distrOutput; return this; } /** * Set the optional context length. * * @param contextLength the context length * @return this builder */ public Builder optContextLength(int contextLength) { this.contextLength = contextLength; return this; } /** * Set the optional number parallel samples. * * @param numParallelSamples the num parallel samples * @return this builder */ public Builder optNumParallelSamples(int numParallelSamples) { this.numParallelSamples = numParallelSamples; return this; } /** * Set the optional number of rnn layers. * * @param numLayers the number of rnn layers * @return this builder */ public Builder optNumLayers(int numLayers) { this.numLayers = numLayers; return this; } /** * Set the optional number of rnn hidden size. * * @param hiddenSize the number of rnn hidden size * @return this builder */ public Builder optHiddenSize(int hiddenSize) { this.hiddenSize = hiddenSize; return this; } /** * Set the optional number of rnn drop rate. * * @param dropRate the number of rnn drop rate * @return this builder */ public Builder optDropRate(float dropRate) { this.dropRate = dropRate; return this; } /** * Set the optional embedding dimension. * * @param embeddingDimension the embedding dimension * @return this builder */ public Builder optEmbeddingDimension(List<Integer> embeddingDimension) { this.embeddingDimension = embeddingDimension; return this; } /** * Set the optional lags sequence, default generate from frequency. * * @param lagsSeq the lags sequence * @return this builder */ public Builder optLagsSeq(List<Integer> lagsSeq) { this.lagsSeq = lagsSeq; return this; } /** * Set whether to use dynamic real feature. * * @param useFeatDynamicReal whether to use dynamic real feature * @return this builder */ public Builder optUseFeatDynamicReal(boolean useFeatDynamicReal) { this.useFeatDynamicReal = useFeatDynamicReal; return this; } /** * Set whether to use static categorical feature. * * @param useFeatStaticCat whether to use static categorical feature * @return this builder */ public Builder optUseFeatStaticCat(boolean useFeatStaticCat) { this.useFeatStaticCat = useFeatStaticCat; return this; } /** * Set whether to use static real feature. * * @param useFeatStaticReal whether to use static real feature * @return this builder */ public Builder optUseFeatStaticReal(boolean useFeatStaticReal) { this.useFeatStaticReal = useFeatStaticReal; return this; } /** * Build a {@link DeepARTrainingNetwork} block. * * @return the {@link DeepARTrainingNetwork} block. */ public DeepARTrainingNetwork buildTrainingNetwork() { return new DeepARTrainingNetwork(this); } /** * Build a {@link DeepARPredictionNetwork} block. * * @return the {@link DeepARPredictionNetwork} block. */ public DeepARPredictionNetwork buildPredictionNetwork() { return new DeepARPredictionNetwork(this); } } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/model
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/model/deepar/DeepARPredictionNetwork.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.model.deepar; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; import ai.djl.ndarray.NDList; import ai.djl.ndarray.types.Shape; import ai.djl.timeseries.distribution.Distribution; import ai.djl.training.ParameterStore; import ai.djl.util.PairList; /** A deepar implements for prediction. */ public class DeepARPredictionNetwork extends DeepARNetwork { DeepARPredictionNetwork(Builder builder) { super(builder); } /** {@inheritDoc} */ @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList<String, Object> params) { NDList unrollInputs = new NDList( inputs.get(0), // feat_static_cat inputs.get(1), // feat_static_real inputs.get(2), // past_time_feat inputs.get(3), // past_target inputs.get(4), // past_observed_value inputs.get(5).get(":, :1") // future_time_feat ); NDList unrollOutput = unrollLaggedRnn(parameterStore, unrollInputs, training); NDList state = new NDList(unrollOutput.get("hidden_state"), unrollOutput.get("cell_state")); String[] argNames = distrOutput.getArgsArray(); NDList repeatedArgs = new NDList(argNames.length); for (String argName : distrOutput.getArgsArray()) { NDArray repeatedArg = unrollOutput.get(argName).repeat(0, numParallelSamples); repeatedArg.setName(argName); repeatedArgs.add(repeatedArg); } NDArray repeatedScale = unrollOutput.get("scale").repeat(0, numParallelSamples); NDArray repeatedStaticFeat = unrollOutput.get("static_feat").repeat(0, numParallelSamples).expandDims(1); NDArray repeatedPastTarget = inputs.get(3).repeat(0, numParallelSamples).div(repeatedScale); NDArray repeatedTimeFeat = inputs.get(5).repeat(0, numParallelSamples); NDList repeatedState = new NDList(state.size()); for (NDArray s : state) { repeatedState.add(s.repeat(1, numParallelSamples)); } Distribution distr = outputDistribution(repeatedArgs, repeatedScale, 1); NDArray nextSample = distr.sample(); NDList futureSamples = new NDList(predictionLength); futureSamples.add(nextSample); for (int k = 1; k < predictionLength; k++) { NDArray scaledNextSample = nextSample.div(repeatedScale); NDArray nextFeatures = repeatedStaticFeat.concat(repeatedTimeFeat.get(":, {}:{}", k, k + 1), -1); NDArray nextLags = laggedSequenceValues(lagsSeq, repeatedPastTarget, scaledNextSample); NDArray rnnInput = nextLags.concat(nextFeatures, -1); NDList outputs = rnn.forward( parameterStore, new NDList(rnnInput).addAll(repeatedState), training); NDArray output = outputs.get(0); repeatedState = outputs.subNDList(1); repeatedPastTarget = repeatedPastTarget.concat(scaledNextSample, 1); repeatedArgs = paramProj.forward(parameterStore, new NDList(output), training); distr = outputDistribution(repeatedArgs, repeatedScale, 0); nextSample = distr.sample(); futureSamples.add(nextSample); } NDArray futureSamplesConcat = NDArrays.concat(futureSamples, 1); return new NDList(futureSamplesConcat.reshape(-1, numParallelSamples, predictionLength)); } /** {@inheritDoc} */ @Override public Shape[] getOutputShapes(Shape[] inputShapes) { long batchSize = inputShapes[0].head(); return new Shape[] {new Shape(batchSize, numParallelSamples, predictionLength)}; } private Distribution outputDistribution(NDList params, NDArray scale, int trailingN) { NDList slicedParams = params; if (trailingN > 0) { slicedParams = new NDList(params.size()); for (NDArray p : params) { NDArray slicedP = p.get(":, {}:", -trailingN); slicedP.setName(p.getName()); slicedParams.add(slicedP); } } return distrOutput.distributionBuilder().setDistrArgs(slicedParams).optScale(scale).build(); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/model
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/model/deepar/DeepARTrainingNetwork.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.model.deepar; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.types.Shape; import ai.djl.training.ParameterStore; import ai.djl.util.PairList; /** A deepar implements for training. */ public final class DeepARTrainingNetwork extends DeepARNetwork { DeepARTrainingNetwork(Builder builder) { super(builder); } /** {@inheritDoc} */ @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList<String, Object> params) { NDArray featStaticCat = inputs.get(0); NDArray featStaticReal = inputs.get(1); NDArray pastTimeFeat = inputs.get(2); NDArray pastTarget = inputs.get(3); NDArray pastObservedValues = inputs.get(4); // NDArray pastIsPad = inputs.get(5); NDArray futureTimeFeat = inputs.get(6); NDArray futureTarget = inputs.get(7); NDArray futureObservedValues = inputs.get(8); NDList unrollOutput = unrollLaggedRnn( parameterStore, new NDList( featStaticCat, featStaticReal, pastTimeFeat, pastTarget, pastObservedValues, futureTimeFeat, futureTarget), training); NDArray observedValues = pastObservedValues .get(":, {}:", -contextLength + 1) .concat(futureObservedValues, 1); observedValues.setName("loss_weights"); String[] argNames = distrOutput.getArgsArray(); NDList ret = new NDList(argNames.length + 2); // args + scale + loss_weights for (String argName : argNames) { ret.add(unrollOutput.get(argName)); } ret.add(unrollOutput.get("scale")); ret.add(observedValues); return ret; } /** {@inheritDoc} */ @Override public Shape[] getOutputShapes(Shape[] inputShapes) { Shape targetShape = inputShapes[3].slice(2); Shape contextShape = new Shape(1, contextLength).addAll(targetShape); Shape scaleShape = scaler.getOutputShapes(new Shape[] {contextShape, contextShape})[1]; long scaleSize = scaleShape.get(1); long embeddedCatSize = embedder.getOutputShapes(new Shape[] {inputShapes[0]})[0].get(1); Shape inputShape = new Shape(1, contextLength * 2L - 1).addAll(targetShape); Shape lagsShape = inputShape.add(lagsSeq.size()); long featSize = inputShapes[2].get(2) + embeddedCatSize + inputShapes[1].get(1) + scaleSize; Shape rnnInputShape = lagsShape.slice(0, lagsShape.dimension() - 1).add(lagsShape.tail() + featSize); Shape rnnOutShape = rnn.getOutputShapes(new Shape[] {rnnInputShape})[0]; Shape[] argShapes = paramProj.getOutputShapes(new Shape[] {rnnOutShape}); long[] observedValueShape = new long[inputShapes[8].dimension()]; System.arraycopy( inputShapes[8].getShape(), 0, observedValueShape, 0, observedValueShape.length); observedValueShape[1] += contextLength - 1; Shape lossWeightsShape = new Shape(observedValueShape); Shape[] ret = new Shape[argShapes.length + 2]; System.arraycopy(argShapes, 0, ret, 0, argShapes.length); ret[argShapes.length] = scaleShape; ret[argShapes.length + 1] = lossWeightsShape; return ret; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/model
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/model/deepar/package-info.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains blocks for deepar models. */ package ai.djl.timeseries.model.deepar;
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/timefeature/Lag.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.timefeature; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** This class contains static method for get lags from frequency. */ public final class Lag { private Lag() {} /** * Generates a list of lags that are appropriate for the given frequency string. * * <p>By default all frequencies have the following lags: [1, 2, 3, 4, 5, 6, 7]. Remaining lags * correspond to the same `season` (+/- `delta`) in previous `k` cycles. Here `delta` and `k` * are chosen according to the existing code. * * @param freqStr Frequency string of the form [multiple][granularity] such as "12H", "1D", "6T" * etc. * @param lagUb The maximum value for a lag * @return a list of lags */ public static List<Integer> getLagsForFreq(String freqStr, int lagUb) { List<List<Integer>> lags; TimeOffset timeOffset = TimeOffset.toOffset(freqStr); switch (timeOffset.getName()) { case "Q": if (timeOffset.getMultipleOfTimeOffset() != 1) { throw new IllegalArgumentException( "Only multiple 1 is supported for quarterly. Use x month instead."); } lags = makeLagsForTimeStep(3, 12, 1, 3. * timeOffset.getMultipleOfTimeOffset()); break; case "M": lags = makeLagsForTimeStep(3, 12, 1, timeOffset.getMultipleOfTimeOffset()); break; case "W": lags = makeLagsForTimeStep(3, 52, 1, timeOffset.getMultipleOfTimeOffset()); break; case "D": lags = makeLagsForTimeStep(4, 7, 1, timeOffset.getMultipleOfTimeOffset()); lags.addAll( makeLagsForTimeStep(3, 52, 1, timeOffset.getMultipleOfTimeOffset() / 7.)); break; case "H": lags = makeLagsForTimeStep(7, 24, 1, timeOffset.getMultipleOfTimeOffset()); lags.addAll( makeLagsForTimeStep(4, 7, 1, timeOffset.getMultipleOfTimeOffset() / 24.)); lags.addAll( makeLagsForTimeStep( 3, 52, 1, (timeOffset.getMultipleOfTimeOffset() / (24. * 7.)))); break; case "min": case "T": lags = makeLagsForTimeStep(3, 60, 2, timeOffset.getMultipleOfTimeOffset()); lags.addAll( makeLagsForTimeStep(7, 24, 1, timeOffset.getMultipleOfTimeOffset() / 60.)); lags.addAll( makeLagsForTimeStep( 4, 7, 1, timeOffset.getMultipleOfTimeOffset() / (60. * 24.))); lags.addAll( makeLagsForTimeStep( 3, 52, 1, timeOffset.getMultipleOfTimeOffset() / (60. * 24. * 7.))); break; case "S": lags = makeLagsForTimeStep(3, 60, 2, timeOffset.getMultipleOfTimeOffset()); lags.addAll( makeLagsForTimeStep(3, 60, 2, timeOffset.getMultipleOfTimeOffset() / 60.)); lags.addAll( makeLagsForTimeStep( 7, 24, 1, timeOffset.getMultipleOfTimeOffset() / (60. * 60.))); break; default: throw new IllegalArgumentException("invalid frequency"); } List<Integer> ret = new ArrayList<>(); for (List<Integer> subList : lags) { for (Integer lag : subList) { if (lag > 7 && lag <= lagUb) { ret.add(lag); } } } ret = ret.stream().distinct().collect(Collectors.toList()); ret.sort(Comparator.naturalOrder()); List<Integer> list = new ArrayList<>(); for (int i = 1; i < 8; i++) { list.add(i); } ret.addAll(0, list); return ret; } /** * Generates a list of lags that are appropriate for the given frequency string. Set the lagUb * to default value 1200. * * @param freqStr Frequency string of the form [multiple][granularity] such as "12H", "1D" etc * @return a list of lags */ public static List<Integer> getLagsForFreq(String freqStr) { return getLagsForFreq(freqStr, 1200); } private static List<List<Integer>> makeLagsForTimeStep( int numCycles, int multiplier, int delta, double multiple) { List<List<Integer>> ret = new ArrayList<>(); for (int i = 1; i < numCycles + 1; i++) { ret.add(makeLags((int) (i * multiplier / multiple), delta)); } if (multiplier == 7) { ret.add(makeLags((int) (30 / multiple), 1)); } else if (multiplier == 52) { ret.add( Arrays.asList( (int) (4. / multiple), (int) (8. / multiple), (int) (12. / multiple))); } return ret; } /** * Creates a set of lags around a middle point including +/- delta. * * @param middle the middle point * @param delta the delta * @return a range between [middle - delta, middle + delta] */ private static List<Integer> makeLags(int middle, int delta) { List<Integer> ret = new ArrayList<>(); for (int i = middle - delta; i < middle + delta + 1; i++) { ret.add(i); } return ret; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/timefeature/TimeFeature.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.timefeature; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import java.time.LocalDateTime; import java.time.temporal.ChronoField; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; import java.util.function.Function; /** this is a class to generate time feature by frequency. */ public final class TimeFeature { private static final Map<String, List<BiFunction<NDManager, List<LocalDateTime>, NDArray>>> FEATURES_BY_OFFSETS = init(); private TimeFeature() {} /** * Computes feature by seconds. * * @param manager default {@link NDManager}. * @param index time data * @return the result feature */ public static NDArray secondOfMinute(NDManager manager, List<LocalDateTime> index) { float[] data = getFeature(index, LocalDateTime::getSecond); return manager.create(data).divi(59f).subi(0.5); } /** * Computes feature by minutes. * * @param manager default {@link NDManager}. * @param index time data * @return the result feature */ public static NDArray minuteOfHour(NDManager manager, List<LocalDateTime> index) { float[] data = getFeature(index, LocalDateTime::getMinute); return manager.create(data).divi(59f).subi(0.5); } /** * Computes feature by hours. * * @param manager default {@link NDManager}. * @param index time data * @return the result feature */ public static NDArray hourOfDay(NDManager manager, List<LocalDateTime> index) { float[] data = getFeature(index, LocalDateTime::getHour); return manager.create(data).divi(23f).subi(0.5); } /** * Computes feature by days of the week. * * @param manager default {@link NDManager}. * @param index time data * @return the result feature */ public static NDArray dayOfWeek(NDManager manager, List<LocalDateTime> index) { float[] data = getFeature(index, a -> a.getDayOfWeek().ordinal()); return manager.create(data).divi(6f).subi(0.5); } /** * Computes feature by days fo the month. * * @param manager default {@link NDManager}. * @param index time data * @return the result feature */ public static NDArray dayOfMonth(NDManager manager, List<LocalDateTime> index) { float[] data = getFeature(index, LocalDateTime::getDayOfMonth); return manager.create(data).subi(1f).divi(30f).subi(0.5f); } /** * Computes feature by days of the year. * * @param manager default {@link NDManager}. * @param index time data * @return the result feature */ public static NDArray dayOfYear(NDManager manager, List<LocalDateTime> index) { float[] data = getFeature(index, LocalDateTime::getDayOfYear); return manager.create(data).subi(1f).divi(365f).subi(0.5f); } /** * Computes feature by months of the year. * * @param manager default {@link NDManager}. * @param index time data * @return the result feature */ public static NDArray monthOfYear(NDManager manager, List<LocalDateTime> index) { float[] data = getFeature(index, LocalDateTime::getMonthValue); return manager.create(data).subi(1f).divi(11f).subi(0.5); } /** * Computes feature by weeks of the year. * * @param manager default {@link NDManager}. * @param index time data * @return the result feature */ public static NDArray weekOfYear(NDManager manager, List<LocalDateTime> index) { float[] data = getFeature(index, a -> a.get(ChronoField.ALIGNED_WEEK_OF_YEAR)); return manager.create(data).sub(1f).div(52f).sub(0.5f); } private static float[] getFeature( List<LocalDateTime> index, Function<LocalDateTime, Number> function) { float[] data = new float[index.size()]; int i = 0; for (LocalDateTime time : index) { data[i++] = function.apply(time).floatValue(); } return data; } /** * Returns a list of time features that will be appropriate for the given frequency string. * * @param freqStr Frequency string of the form [multiple][granularity] such as "12H", "1D" * @return time features */ public static List<BiFunction<NDManager, List<LocalDateTime>, NDArray>> timeFeaturesFromFreqStr( String freqStr) { TimeOffset timeOffset = TimeOffset.toOffset(freqStr); return FEATURES_BY_OFFSETS.get(timeOffset.getName()); } private static Map<String, List<BiFunction<NDManager, List<LocalDateTime>, NDArray>>> init() { Map<String, List<BiFunction<NDManager, List<LocalDateTime>, NDArray>>> map = new ConcurrentHashMap<>(); map.put("Y", Collections.emptyList()); map.put("Q", Collections.singletonList(TimeFeature::monthOfYear)); map.put("M", Collections.singletonList(TimeFeature::monthOfYear)); map.put("W", Arrays.asList(TimeFeature::dayOfMonth, TimeFeature::weekOfYear)); map.put( "D", Arrays.asList( TimeFeature::dayOfWeek, TimeFeature::dayOfMonth, TimeFeature::dayOfYear)); map.put( "H", Arrays.asList( TimeFeature::hourOfDay, TimeFeature::dayOfWeek, TimeFeature::dayOfMonth, TimeFeature::dayOfYear)); map.put( "T", Arrays.asList( TimeFeature::minuteOfHour, TimeFeature::hourOfDay, TimeFeature::dayOfWeek, TimeFeature::dayOfMonth, TimeFeature::dayOfYear)); map.put( "S", Arrays.asList( TimeFeature::secondOfMinute, TimeFeature::minuteOfHour, TimeFeature::hourOfDay, TimeFeature::dayOfWeek, TimeFeature::dayOfMonth, TimeFeature::dayOfYear)); return map; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/timefeature/TimeOffset.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.timefeature; import java.util.regex.Matcher; import java.util.regex.Pattern; /** This is a class use to get multiple and granularity from frequency string. */ public class TimeOffset { private static String oPattern = "(?<multiple>\\d*)(?<granularity>\\w+)"; private String name; private int offsetValue; /** * Constructs a new {@code TimeOffset} instance. * * @param name offset granularity including "D", "M" etc * @param offsetValue offset multiple */ public TimeOffset(String name, int offsetValue) { this.name = name; this.offsetValue = offsetValue; } /** * Return {@code TimeOffset} object from frequency string. * * @param frequencyString Frequency string of the form [multiple][granularity] such as "12H", * "1D" etc. * @return a TimeOffset containing multiple and granularity */ public static TimeOffset toOffset(String frequencyString) { Matcher matcher = Pattern.compile(oPattern).matcher(frequencyString); matcher.find(); String name = matcher.group("granularity"); if ("".equals(name)) { throw new IllegalArgumentException("Invalid frequency"); } name = "min".equals(name) ? "T" : name; String multiple = matcher.group("multiple"); if ("".equals(multiple)) { multiple = "1"; } int n = Integer.parseInt(multiple); return new TimeOffset(name, n); } /** * Return the granularity name of {@code TimeOffset}. * * @return the granularity name of {@code TimeOffset}. */ public String getName() { return name; } /** * Return the multiple of {@code TimeOffset}. * * @return the multiple of {@code TimeOffset} */ public double getMultipleOfTimeOffset() { return offsetValue; } /** * Return the formatted frequency string. * * @return the formatted frequency string */ public String toFreqStr() { return offsetValue + name; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/timefeature/package-info.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains utils to get time feature from prediction frequency. */ package ai.djl.timeseries.timefeature;
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/ExpectedNumInstanceSampler.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform; import ai.djl.ndarray.NDArray; import ai.djl.util.RandomUtils; import java.util.ArrayList; import java.util.List; /** * Keeps track of the average time series length and adjusts the probability per time point such * that on average `num_instances` training examples are generated per time series. */ public class ExpectedNumInstanceSampler extends InstanceSampler { private double numInstances; private int totalLength; private int n; /** * Construct a new instance of {@code ExpectedNumInstanceSampler}. * * @param axis the axis of the time series length * @param minPast minimal pastime length * @param minFuture minimal future time length * @param numInstances number of training examples generated per time series on average */ public ExpectedNumInstanceSampler(int axis, int minPast, int minFuture, double numInstances) { super(axis, minPast, minFuture); this.numInstances = numInstances; } /** {@inheritDoc} */ @Override public List<Integer> call(NDArray ts) { int[] bound = getBounds(ts); int windowSize = bound[1] - bound[0] + 1; if (windowSize <= 0) { return new ArrayList<>(); } n += 1; totalLength += windowSize; int avgLength = totalLength / n; if (avgLength <= 0) { return new ArrayList<>(); } double prob = numInstances / avgLength; List<Integer> indices = new ArrayList<>(); while (indices.isEmpty()) { for (int i = 0; i < windowSize; i++) { if (RandomUtils.RANDOM.nextDouble() < prob) { indices.add(i + bound[0]); } } } return indices; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/InstanceSampler.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform; import ai.djl.ndarray.NDArray; import java.util.List; /** * An InstanceSampler is called with the time series ``ts``, and returns a set of indices at which * training instances will be generated. * * <p>The sampled indices ``i`` satisfy ``a &lt;= i &lt;= b``, where ``a = min_past`` and ``b = * ts.shape[axis] - min_future``. */ public abstract class InstanceSampler { protected int axis; protected int minPast; protected int minFuture; /** * Constructs a new instance of {@code InstanceSampler}. * * @param axis the axis of the time series length * @param minPast minimal pastime length * @param minFuture minimal future time length */ public InstanceSampler(int axis, int minPast, int minFuture) { this.axis = axis; this.minPast = minPast; this.minFuture = minFuture; } /** * Returns the sampled indices bounds. * * @param ts the time series * @return the indices bound */ public int[] getBounds(NDArray ts) { int start = minPast; int posAxis = axis < 0 ? ts.getShape().dimension() + axis : axis; int end = (int) ts.getShape().get(posAxis) - minFuture; return new int[] {start, end}; } /** * Call the sample process. * * @param ts the time series * @return list of indices */ public abstract List<Integer> call(NDArray ts); }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/PredictionSplitSampler.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform; import ai.djl.ndarray.NDArray; import java.util.ArrayList; import java.util.List; /** Sampler used for prediction. */ public class PredictionSplitSampler extends InstanceSampler { private boolean allowEmptyInterval; /** * Constructs a new instance of {@code PredictionSplitSampler}. * * @param axis the axis of the time series length * @param minPast minimal pastime length * @param minFuture minimal future time length * @param allowEmptyInterval whether allow to output an empty {@link NDArray} */ public PredictionSplitSampler( int axis, int minPast, int minFuture, boolean allowEmptyInterval) { super(axis, minPast, minFuture); this.allowEmptyInterval = allowEmptyInterval; } /** {@inheritDoc} * */ @Override public List<Integer> call(NDArray ts) { int[] bound = getBounds(ts); List<Integer> ret = new ArrayList<>(); if (bound[0] < bound[1]) { ret.add(bound[1]); } else if (!allowEmptyInterval) { throw new IllegalArgumentException("The start >= end while allowEmptyInterval = False"); } return ret; } /** * Creates a new instance {@code PredictionSplitSampler} for test. * * @return a {@code PredictionSplitSampler} */ public static PredictionSplitSampler newTestSplitSampler() { return new PredictionSplitSampler(-1, 0, 0, false); } /** * Creates a new instance {@code PredictionSplitSampler} for validation. * * @return a {@link PredictionSplitSampler} */ public static PredictionSplitSampler newValidationSplitSampler() { return new PredictionSplitSampler(-1, 0, 0, true); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/TimeSeriesTransform.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.Shape; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import java.util.ArrayList; import java.util.List; /** This interface is used for data transformation on the {@link TimeSeriesData}. */ public interface TimeSeriesTransform { /** * Transform process on TimeSeriesData. * * @param manager The default manager for data process * @param data The data to be operated on * @param isTrain Whether it is training * @return The result {@link TimeSeriesData}. */ TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain); /** * Construct a list of {@link TimeSeriesTransform} that performs identity function. * * @return a list of identity {@link TimeSeriesTransform} */ static List<TimeSeriesTransform> identityTransformation() { List<TimeSeriesTransform> ret = new ArrayList<>(); ret.add(new IdentityTransform()); return ret; } /** An identity transformation. */ class IdentityTransform implements TimeSeriesTransform { /** {@inheritDoc} */ @Override public TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain) { data.setField("PAST_" + FieldName.TARGET, data.get(FieldName.TARGET)); data.setField("FUTURE_" + FieldName.TARGET, manager.create(new Shape(0))); return data; } } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/package-info.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains transform classes. */ package ai.djl.timeseries.transform;
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/convert/AsArray.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.convert; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.transform.TimeSeriesTransform; /** Convert the data type of {@link NDArray} and check its dimension. */ public class AsArray implements TimeSeriesTransform { private FieldName field; private DataType dataType; private int expectedDim; /** * Constructs a {@link AsArray}. * * @param field the output field name * @param expectedDim expected number of dimensions * @param dataType {@link DataType} to use */ public AsArray(FieldName field, int expectedDim, DataType dataType) { this.field = field; this.dataType = dataType; this.expectedDim = expectedDim; } /** * Constructs a {@link AsArray}. * * @param field the output field name * @param expectedDim expected number of dimensions */ public AsArray(FieldName field, int expectedDim) { this(field, expectedDim, DataType.FLOAT32); } /** {@inheritDoc} */ @Override public TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain) { Convert.asArray(field, expectedDim, dataType, data); return data; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/convert/Convert.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.convert; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; import ai.djl.ndarray.NDList; import ai.djl.ndarray.types.DataType; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; /** A class used to convert the shape of {@link NDArray} in {@link TimeSeriesData}. */ public final class Convert { private Convert() {} /** * Stacks fields together using {@link NDArrays#concat(NDList)}. when hStack = false, axis = 0 * Otherwise axis = 1. * * @param outputField the field names to use for the output * @param inputFields the fields to stack together * @param dropInputs the input fields will be dropped if set to true * @param hStack to stack horizontally instead of vertically * @param data the {@link TimeSeriesData} to operate on */ public static void vstackFeatures( FieldName outputField, FieldName[] inputFields, boolean dropInputs, boolean hStack, TimeSeriesData data) { NDList ndList = new NDList(); for (FieldName fieldName : inputFields) { NDArray temp = data.get(fieldName); if (temp != null) { ndList.add(data.get(fieldName)); } } NDArray output = NDArrays.concat(ndList, hStack ? 1 : 0); data.setField(outputField, output); if (dropInputs) { for (FieldName fieldName : inputFields) { if (fieldName != outputField) { data.remove(fieldName); } } } } /** * Stacks fields together using {@link NDArrays#concat(NDList)}. * * <p>set hStack = false, dropInputs = true * * @param outputField the field names to use for the output * @param inputFields the fields to stack together * @param data the {@link TimeSeriesData} to operate on */ public static void vstackFeatures( FieldName outputField, FieldName[] inputFields, TimeSeriesData data) { vstackFeatures(outputField, inputFields, true, false, data); } /** * Converts the data type of {@link NDArray} and check its dimension. * * @param field aim field * @param expectedDim expected number of dimensions * @param dataType {@link DataType} to use * @param data the {@link TimeSeriesData} to operate on */ public static void asArray( FieldName field, int expectedDim, DataType dataType, TimeSeriesData data) { NDArray value = data.get(field); if (value == null) { throw new IllegalArgumentException(String.format("%s don't map to any NDArray", field)); } value = value.toType(dataType, true); if (value.getShape().dimension() != expectedDim) { throw new IllegalArgumentException( String.format( "Input for field \"%s\" does not have the required dimension (field:" + " %s, dim: %d, expected: %d)", field, field, value.getShape().dimension(), expectedDim)); } data.setField(field, value); } /** * Converts the data type of {@link NDArray} and check its dimension. * * @param field aim field * @param expectedDim expected number of dimensions * @param data the {@link TimeSeriesData} to operate on */ public static void asArray(FieldName field, int expectedDim, TimeSeriesData data) { asArray(field, expectedDim, DataType.FLOAT32, data); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/convert/VstackFeatures.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.convert; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.transform.TimeSeriesTransform; /** Use the {@link ai.djl.ndarray.NDArrays#concat(NDList)} to vstack data. */ public class VstackFeatures implements TimeSeriesTransform { private FieldName outputField; private FieldName[] inputFields; private boolean dropInputs; private boolean hStack; /** * Constructs a {@link VstackFeatures}. * * @param outputField output field name * @param inputFields input field names * @param dropInputs whether to remove the input fields * @param hStack use hStack */ public VstackFeatures( FieldName outputField, FieldName[] inputFields, boolean dropInputs, boolean hStack) { this.outputField = outputField; this.inputFields = inputFields; this.dropInputs = dropInputs; this.hStack = hStack; } /** * Constructs a {@link VstackFeatures}. * * @param outputField output field name * @param inputFields input field names */ public VstackFeatures(FieldName outputField, FieldName[] inputFields) { this(outputField, inputFields, true, false); } /** {@inheritDoc} */ @Override public TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain) { Convert.vstackFeatures(outputField, inputFields, dropInputs, hStack, data); return data; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/convert/package-info.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** * Contains transform for {@link ai.djl.timeseries.TimeSeriesData} to convert {@link * ai.djl.ndarray.NDArray}. */ package ai.djl.timeseries.transform.convert;
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/feature/AddAgeFeature.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.feature; import ai.djl.ndarray.NDManager; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.transform.TimeSeriesTransform; /** Add age feature through the prediction length. */ public class AddAgeFeature implements TimeSeriesTransform { private FieldName targetField; private FieldName outputField; private int predictionLength; private boolean logScale; /** * Constructs a {@link AddAgeFeature}. * * @param targetField target field name * @param outputField output field name * @param predictionLength time series prediction length */ public AddAgeFeature(FieldName targetField, FieldName outputField, int predictionLength) { this(targetField, outputField, predictionLength, true); } /** * Constructs a {@link AddAgeFeature}. * * @param targetField target field name * @param outputField output field name * @param predictionLength time series prediction length * @param logScale whether to use log data */ public AddAgeFeature( FieldName targetField, FieldName outputField, int predictionLength, boolean logScale) { this.targetField = targetField; this.outputField = outputField; this.predictionLength = predictionLength; this.logScale = logScale; } /** {@inheritDoc} */ @Override public TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain) { return Feature.addAgeFeature( manager, targetField, outputField, predictionLength, logScale, data); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/feature/AddObservedValuesIndicator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.feature; import ai.djl.ndarray.NDManager; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.transform.TimeSeriesTransform; /** Add observed value for the target data. */ public class AddObservedValuesIndicator implements TimeSeriesTransform { private FieldName targetField; private FieldName outputField; /** * Constructs a {@link AddObservedValuesIndicator}. * * @param targetField target field name to be observed * @param outputField output field name */ public AddObservedValuesIndicator(FieldName targetField, FieldName outputField) { this.targetField = targetField; this.outputField = outputField; } /** {@inheritDoc} */ @Override public TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain) { Feature.addObservedValuesIndicator(manager, targetField, outputField, data); return data; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/feature/AddTimeFeature.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.feature; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.transform.TimeSeriesTransform; import java.time.LocalDateTime; import java.util.List; import java.util.function.BiFunction; /** Add time feature by frequency. */ public class AddTimeFeature implements TimeSeriesTransform { private FieldName startField; private FieldName targetField; private FieldName outputField; private List<BiFunction<NDManager, List<LocalDateTime>, NDArray>> timeFeatures; private int predictionLength; String freq; /** * Constructs a {@link AddTimeFeature}. * * @param startField start field name containing start time * @param targetField target field name * @param outputField output value field name * @param timeFeatures functions to generate time features * @param predictionLength prediction length * @param freq prediction frequency */ public AddTimeFeature( FieldName startField, FieldName targetField, FieldName outputField, List<BiFunction<NDManager, List<LocalDateTime>, NDArray>> timeFeatures, int predictionLength, String freq) { this.startField = startField; this.targetField = targetField; this.outputField = outputField; this.timeFeatures = timeFeatures; this.predictionLength = predictionLength; this.freq = freq; } /** {@inheritDoc} */ @Override public TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain) { Feature.addTimeFeature( manager, startField, targetField, outputField, timeFeatures, predictionLength, freq, data); return data; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/feature/Feature.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.feature; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.Shape; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import java.time.Duration; import java.time.LocalDateTime; import java.time.Period; import java.time.temporal.TemporalAmount; import java.util.ArrayList; import java.util.List; import java.util.function.BiFunction; /** this is a class use to add feature in {@link TimeSeriesData}. */ public final class Feature { private Feature() {} /** * Replaces missing values in a {@link NDArray} (NaNs) with a dummy value and adds an * "observed"-indicator that is "1" when values are observed and "0" when values are missing. * * @param manager default {@link NDManager} * @param targetField Field for which missing values will be replaced * @param outputField Field name to use for the indicator * @param data the {@link TimeSeriesData} to operate on */ public static void addObservedValuesIndicator( NDManager manager, FieldName targetField, FieldName outputField, TimeSeriesData data) { NDArray value = data.get(targetField); data.setField(targetField, dummyValueImputation(manager, value, 0f)); NDArray nanEntries = value.isNaN(); data.setField(outputField, nanEntries.logicalNot().toType(value.getDataType(), false)); } /** * Adds a set of time features. * * @param manager default {@link NDManager} * @param startField Field with the start time stamp of the time series * @param targetField Field with the array containing the time series values * @param outputField Field name for result * @param timeFeatures list of time features to use * @param predictionLength Prediction length * @param freq Prediction time frequency * @param data the {@link TimeSeriesData} to operate on */ public static void addTimeFeature( NDManager manager, FieldName startField, FieldName targetField, FieldName outputField, List<BiFunction<NDManager, List<LocalDateTime>, NDArray>> timeFeatures, int predictionLength, String freq, TimeSeriesData data) { addTimeFeature( manager, startField, targetField, outputField, timeFeatures, predictionLength, freq, data, false); } /** * Adds a set of time features. * * @param manager default {@link NDManager} * @param startField Field with the start time stamp of the time series * @param targetField Field with the array containing the time series values * @param outputField Field name for result * @param timeFeatures list of time features to use * @param predictionLength Prediction length * @param freq Prediction time frequency * @param data the {@link TimeSeriesData} to operate on * @param isTrain Whether it is training */ public static void addTimeFeature( NDManager manager, FieldName startField, FieldName targetField, FieldName outputField, List<BiFunction<NDManager, List<LocalDateTime>, NDArray>> timeFeatures, int predictionLength, String freq, TimeSeriesData data, boolean isTrain) { if (timeFeatures.isEmpty()) { data.setField(outputField, null); } LocalDateTime start = data.getStartTime(); int length = targetTransformationLength(data.get(targetField), predictionLength, isTrain); StringBuilder sb = new StringBuilder(); sb.append(freq); if (!freq.matches("\\d+.*")) { sb.insert(0, 1); } TemporalAmount timeFreq; if (freq.endsWith("H") || freq.endsWith("T") || freq.endsWith("S")) { sb.insert(0, "PT"); timeFreq = Duration.parse(sb.toString()); } else { sb.insert(0, "P"); timeFreq = Period.parse(sb.toString()); } List<LocalDateTime> index = new ArrayList<>(); LocalDateTime temp = start; for (int i = 0; i < length; i++) { index.add(temp); temp = temp.plus(timeFreq); } NDList outputs = new NDList(timeFeatures.size()); for (BiFunction<NDManager, List<LocalDateTime>, NDArray> f : timeFeatures) { outputs.add(f.apply(manager, index)); } data.setField(outputField, NDArrays.stack(outputs)); } /** * Adds on 'age' feature to the {@link TimeSeriesData}. * * <p>The age feature starts with a small value at the start of the time series and grows over * time. * * @param manager default {@link NDManager} * @param targetField Field with target values (array) of time series * @param outputField Field name to use for the output * @param predictionLength Prediction length * @param logScale If set to true the age feature grows logarithmically otherwise linearly over * time. * @param data the {@link TimeSeriesData} to operate on * @return the result {@link TimeSeriesData} */ public static TimeSeriesData addAgeFeature( NDManager manager, FieldName targetField, FieldName outputField, int predictionLength, boolean logScale, TimeSeriesData data) { return addAgeFeature( manager, targetField, outputField, predictionLength, logScale, data, false); } /** * Adds on 'age' feature to the {@link TimeSeriesData}. * * <p>The age feature starts with a small value at the start of the time series and grows over * time. * * @param manager default {@link NDManager} * @param targetField Field with target values (array) of time series * @param outputField Field name to use for the output * @param predictionLength Prediction length * @param logScale If set to true the age feature grows logarithmically otherwise linearly over * time. * @param data the {@link TimeSeriesData} to operate on * @param isTrain Whether it is training * @return the result {@link TimeSeriesData} */ public static TimeSeriesData addAgeFeature( NDManager manager, FieldName targetField, FieldName outputField, int predictionLength, boolean logScale, TimeSeriesData data, boolean isTrain) { NDArray targetData = data.get(targetField); int length = targetTransformationLength(targetData, predictionLength, isTrain); NDArray age = manager.arange(0, length, 1, targetData.getDataType()); if (logScale) { age = age.add(2f).log10(); } age = age.reshape(new Shape(1, length)); data.setField(outputField, age); return data; } /** * Adds on 'age' feature to the {@link TimeSeriesData}, set logScale = ture * * <p>The age feature starts with a small value at the start of the time series and grows over * time. * * @param manager default {@link NDManager} * @param targetField Field with target values (array) of time series * @param outputField Field name to use for the output * @param predictionLength Prediction length * @param data the {@link TimeSeriesData} to operate on */ public static void addAgeFeature( NDManager manager, FieldName targetField, FieldName outputField, int predictionLength, TimeSeriesData data) { addAgeFeature(manager, targetField, outputField, predictionLength, true, data); } private static int targetTransformationLength( NDArray target, int predictionLength, boolean isTrain) { return (int) target.getShape().tail() + (isTrain ? 0 : predictionLength); } private static NDArray dummyValueImputation( NDManager manager, NDArray value, float dummyValue) { NDArray dummyArray = manager.full(value.getShape(), dummyValue); return NDArrays.where(value.isNaN(), dummyArray, value); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/feature/package-info.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains transform for {@link ai.djl.timeseries.TimeSeriesData} to generate time feature. */ package ai.djl.timeseries.transform.feature;
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/field/Field.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.field; import ai.djl.ndarray.NDArray; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** A utility class that used to operate field name in {@link TimeSeriesData}. */ public final class Field { private Field() {} /** * Remove fields names if present. * * @param fieldNames List of names of the fields that will be removed * @param data the {@link TimeSeriesData} to operate on */ public static void removeFields(List<FieldName> fieldNames, TimeSeriesData data) { for (FieldName k : fieldNames) { data.remove(k); } } /** * Sets a field in the dictionary with the given value. * * @param outputField Name of the field that will be set * @param value Value to be set * @param data the {@link TimeSeriesData} to operate on */ public static void setField(FieldName outputField, NDArray value, TimeSeriesData data) { data.remove(outputField); data.add(outputField, value); } /** * Only keep the listed fields. * * @param inputFields List of fields to keep * @param data the {@link TimeSeriesData} to operate on * @return the result {@link TimeSeriesData} */ public static TimeSeriesData selectField(String[] inputFields, TimeSeriesData data) { List<String> keys = Arrays.asList(inputFields); List<NDArray> values = new ArrayList<>(keys.size()); for (String field : inputFields) { values.add(data.get(field)); } return new TimeSeriesData(keys, values); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/field/RemoveFields.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.field; import ai.djl.ndarray.NDManager; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.transform.TimeSeriesTransform; import java.util.List; /** Remove the field names. */ public class RemoveFields implements TimeSeriesTransform { private final List<FieldName> fieldNames; /** * Constructs a {@code RemoveFields} instance. * * @param fieldNames field name to be removed */ public RemoveFields(List<FieldName> fieldNames) { this.fieldNames = fieldNames; } /** {@inheritDoc} */ @Override public TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain) { Field.removeFields(fieldNames, data); return data; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/field/SelectField.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.field; import ai.djl.ndarray.NDManager; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.transform.TimeSeriesTransform; /** Select preset field names. */ public class SelectField implements TimeSeriesTransform { private String[] inputFields; /** * Constructs a {@code SelectField} instance. * * @param inputFields field names to select from */ public SelectField(String[] inputFields) { this.inputFields = inputFields; } /** {@inheritDoc} */ @Override public TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain) { return Field.selectField(inputFields, data); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/field/SetField.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.field; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.transform.TimeSeriesTransform; /** Use the preset value for input field names. */ public class SetField implements TimeSeriesTransform { private final FieldName outputField; private final NDArray value; /** * Constructs a {@link SetField}. * * @param outputField output field name to be set * @param value value to be set */ public SetField(FieldName outputField, NDArray value) { this.outputField = outputField; this.value = value; } /** {@inheritDoc} */ @Override public TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain) { NDArray copyValue = value.duplicate(); Field.setField(outputField, copyValue, data); return data; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/field/package-info.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains transform for {@link ai.djl.timeseries.TimeSeriesData} to CRUD name field. */ package ai.djl.timeseries.transform.field;
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/split/InstanceSplit.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.split; import ai.djl.ndarray.NDManager; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.transform.InstanceSampler; import ai.djl.timeseries.transform.TimeSeriesTransform; /** * Use the {@link ai.djl.timeseries.transform.InstanceSampler} to split the time series data into * past and future part. */ public class InstanceSplit implements TimeSeriesTransform { private FieldName targetField; private FieldName isPadField; private FieldName startField; private FieldName forecastStartField; private InstanceSampler instanceSampler; private int pastLength; private int futureLength; private int leadTime; private boolean outputNTC; private FieldName[] timeSeriesFields; private float dummyValue; /** * Constructs a {@link InstanceSplit}. * * @param targetField target field name * @param isPadField is_pad field name * @param startField start time field name * @param forecastStartField forecast time field name * @param instanceSampler Sampler to generate indices for splitting * @param pastLength past target data length * @param futureLength future target data length * @param leadTime lead time * @param outputNTC whether to lay out as "NTC" * @param timeSeriesFields time series field names to be split * @param dummyValue value for padding */ public InstanceSplit( FieldName targetField, FieldName isPadField, FieldName startField, FieldName forecastStartField, InstanceSampler instanceSampler, int pastLength, int futureLength, int leadTime, boolean outputNTC, FieldName[] timeSeriesFields, float dummyValue) { this.targetField = targetField; this.isPadField = isPadField; this.startField = startField; this.forecastStartField = forecastStartField; this.instanceSampler = instanceSampler; this.pastLength = pastLength; this.futureLength = futureLength; this.leadTime = leadTime; this.outputNTC = outputNTC; this.timeSeriesFields = timeSeriesFields; this.dummyValue = dummyValue; } /** * Constructs a {@link InstanceSplit}. * * @param targetField target field name * @param isPadField is_pad field name * @param startField start time field name * @param forecastStartField forecast time field name * @param instanceSampler Sampler to generate indices for splitting * @param pastLength past target data length * @param futureLength future target data length * @param timeSeriesFields time series field names to be split * @param dummyValue value for padding */ public InstanceSplit( FieldName targetField, FieldName isPadField, FieldName startField, FieldName forecastStartField, InstanceSampler instanceSampler, int pastLength, int futureLength, FieldName[] timeSeriesFields, float dummyValue) { this( targetField, isPadField, startField, forecastStartField, instanceSampler, pastLength, futureLength, 0, true, timeSeriesFields, dummyValue); } /** {@inheritDoc}. */ @Override public TimeSeriesData transform(NDManager manager, TimeSeriesData data, boolean isTrain) { Split.instanceSplit( manager, targetField, isPadField, startField, forecastStartField, instanceSampler, pastLength, futureLength, leadTime, outputNTC, timeSeriesFields, dummyValue, data); return data; } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/split/Split.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.transform.split; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.index.NDIndex; import ai.djl.ndarray.types.Shape; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.transform.InstanceSampler; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** this is a class use to split the time series data of {@link TimeSeriesData}. */ public final class Split { private Split() {} /** * Selects training instances, by slicing the target and other time series like arrays at random * points in training mode or at the last time point in prediction mode. Assumption is that all * time like arrays start at the same time point. * * <p>The target and each time_series_field is removed and instead two corresponding fields with * prefix `past_` and `future_` are included. E.g. * * <p>If the target array is one-dimensional, the resulting instance has shape (len_target). In * the multi-dimensional case, the instance has shape (dim, len_target). * * <p>target -&gt; past_target and future_target * * <p>The transformation also adds a field 'past_is_pad' that indicates whether values where * padded or not. Convention: time axis is always the last axis. * * @param manager the default {@link NDManager} * @param targetField {@link FieldName} containing the target * @param isPadField output {@link FieldName} indicating whether padding happened * @param startField field containing the start date of the time series * @param forecastStartField output field that will contain the time point where the forecast * starts * @param instanceSampler {@link InstanceSampler} that provides sampling indices given a * time-series * @param pastLength length of the target seen before making prediction * @param futureLength length of the target that must be predicted * @param leadTime gap between the past and future windows (default 0) * @param outputNTC whether to have time series output in (time, dimension) or in (dimension, * time) layout (default True) * @param timeSeriesFields fields that contains time-series, they are split in the same interval * as the target (default None) * @param dummyValue Value to use for padding (default 0.0) * @param data the {@link TimeSeriesData} to operate on */ public static void instanceSplit( NDManager manager, FieldName targetField, FieldName isPadField, FieldName startField, FieldName forecastStartField, InstanceSampler instanceSampler, int pastLength, int futureLength, int leadTime, boolean outputNTC, FieldName[] timeSeriesFields, float dummyValue, TimeSeriesData data) { List<FieldName> sliceCols = new ArrayList<>(timeSeriesFields.length + 1); sliceCols.addAll(Arrays.asList(timeSeriesFields)); sliceCols.add(targetField); NDArray target = data.get(targetField); List<Integer> sampledIndices = instanceSampler.call(target); // TODO: add yield method for (int i : sampledIndices.subList(0, 1)) { int padLength = Math.max(pastLength - i, 0); for (FieldName tsField : sliceCols) { NDArray pastPiece; NDArray tsData = data.get(tsField); if (i > pastLength) { pastPiece = tsData.get("..., {}:{}", i - pastLength, i); } else if (i < pastLength) { Shape shape = tsData.getShape(); int dims = shape.dimension(); shape = shape.slice(0, dims - 1).add(padLength); NDArray padBlock = manager.full(shape, dummyValue, tsData.getDataType()); pastPiece = i == 0 ? padBlock : padBlock.concat(tsData.get("..., :{}", i), -1); } else { pastPiece = tsData.get("..., :{}", i); } data.setField(past(tsField), pastPiece); NDArray futureData; if (i + leadTime >= (int) tsData.getShape().tail()) { // Only for the inference. if create the NDArray by slice the tsData, an unknown // error occur Shape shape = tsData.getShape(); shape = shape.slice(0, shape.dimension() - 1).add(0); futureData = manager.create(shape); } else { futureData = tsData.get("..., {}:{}", i + leadTime, i + leadTime + futureLength); } data.setField(future(tsField), futureData); data.remove(tsField); } NDArray padIndicator = manager.zeros(new Shape(pastLength), target.getDataType()); if (padLength > 0) { padIndicator.set(new NDIndex(":{}", padLength), 1); } if (outputNTC) { for (FieldName tsField : sliceCols) { NDArray past = data.get(past(tsField)); data.setField(past(tsField), past.transpose()); NDArray future = data.get(future(tsField)); data.setField(future(tsField), future.transpose()); } } data.setField(past(isPadField), padIndicator); // only for freq "D" now data.setForecastStartTime(data.getStartTime().plusDays(i + leadTime)); } } /** * Selects training instances, by slicing the target and other time series like arrays at random * points in training mode or at the last time point in prediction mode. Assumption is that all * time like arrays start at the same time point. * * <p>The target and each time_series_field is removed and instead two corresponding fields with * prefix `past_` and `future_` are included. E.g. * * <p>If the target array is one-dimensional, the resulting instance has shape (len_target). In * the multi-dimensional case, the instance has shape (dim, len_target). * * <p>target -&gt; past_target and future_target * * <p>The transformation also adds a field 'past_is_pad' that indicates whether values where * padded or not. Convention: time axis is always the last axis. * * @param manager the default {@link NDManager} * @param targetField {@link FieldName} containing the target * @param isPadField output {@link FieldName} indicating whether padding happened * @param startField field containing the start date of the time series * @param forecastStartField output field that will contain the time point where the forecast * starts * @param instanceSampler {@link InstanceSampler} that provides sampling indices given a * time-series * @param pastLength length of the target seen before making prediction * @param futureLength length of the target that must be predicted (time, dimension) or in * (dimension, time) layout (default True) * @param timeSeriesFields fields that contains time-series, they are split in the same interval * as the target (default None) * @param dummyValue Value to use for padding (default 0.0) * @param data the {@link TimeSeriesData} to operate on */ public static void instanceSplit( NDManager manager, FieldName targetField, FieldName isPadField, FieldName startField, FieldName forecastStartField, InstanceSampler instanceSampler, int pastLength, int futureLength, FieldName[] timeSeriesFields, float dummyValue, TimeSeriesData data) { instanceSplit( manager, targetField, isPadField, startField, forecastStartField, instanceSampler, pastLength, futureLength, 0, true, timeSeriesFields, dummyValue, data); } private static String past(FieldName name) { return "PAST_" + name.name(); } private static String future(FieldName name) { return "FUTURE_" + name.name(); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/transform/split/package-info.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** * Contains transform for {@link ai.djl.timeseries.TimeSeriesData} to split time feature for * inference and train. */ package ai.djl.timeseries.transform.split;
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/translator/BaseTimeSeriesTranslator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.translator; import ai.djl.timeseries.Forecast; import ai.djl.timeseries.TimeSeriesData; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.Batchifier; import ai.djl.translate.Translator; import java.util.Map; /** Built-in {@code Translator} that provides default TimeSeriesTranslator config process. */ public abstract class BaseTimeSeriesTranslator implements Translator<TimeSeriesData, Forecast> { protected int predictionLength; protected int contextLength; protected String freq; private Batchifier batchifier; /** * Constructs a new {@code TimeSeriesTranslator} instance with the provided builder. * * @param builder the data to build with */ protected BaseTimeSeriesTranslator(BaseBuilder<?> builder) { this.batchifier = builder.batchifier; this.freq = builder.freq; this.predictionLength = builder.predictionLength; this.contextLength = builder.contextLength; } /** {@inheritDoc} */ @Override public Batchifier getBatchifier() { return batchifier; } /** * A builder to extend for all classes extend the {@link BaseTimeSeriesTranslator}. * * @param <T> the concrete builder type */ public abstract static class BaseBuilder<T extends BaseBuilder<T>> { protected Batchifier batchifier = Batchifier.STACK; protected int predictionLength; protected int contextLength; protected String freq; /** * Sets the {@link Batchifier} for the {@link Translator}. * * @param batchifier the {@link Batchifier} to be set * @return this builder */ public T optBachifier(Batchifier batchifier) { this.batchifier = batchifier; return self(); } protected abstract T self(); protected void validate() {} protected void configPreProcess(Map<String, ?> arguments) { this.freq = ArgumentsUtil.stringValue(arguments, "freq", "D"); this.predictionLength = ArgumentsUtil.intValue(arguments, "prediction_length"); if (predictionLength <= 0) { throw new IllegalArgumentException( "The value of `prediction_length` should be > 0"); } this.contextLength = ArgumentsUtil.intValue(arguments, "context_length", predictionLength); if (arguments.containsKey("batchifier")) { batchifier = Batchifier.fromString((String) arguments.get("batchifier")); } } protected void configPostProcess(Map<String, ?> arguments) {} } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/translator/DeepARTranslator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.translator; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.timeseries.Forecast; import ai.djl.timeseries.SampleForecast; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.timefeature.Lag; import ai.djl.timeseries.timefeature.TimeFeature; import ai.djl.timeseries.transform.InstanceSampler; import ai.djl.timeseries.transform.PredictionSplitSampler; import ai.djl.timeseries.transform.convert.Convert; import ai.djl.timeseries.transform.feature.Feature; import ai.djl.timeseries.transform.field.Field; import ai.djl.timeseries.transform.split.Split; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.BiFunction; /** The {@link Translator} for DeepAR time series forecasting tasks. */ public class DeepARTranslator extends BaseTimeSeriesTranslator { private boolean useFeatDynamicReal; private boolean useFeatStaticReal; private boolean useFeatStaticCat; private int historyLength; private static final String[] PRED_INPUT_FIELDS = { FieldName.FEAT_STATIC_CAT.name(), FieldName.FEAT_STATIC_REAL.name(), "PAST_" + FieldName.FEAT_TIME.name(), "PAST_" + FieldName.TARGET.name(), "PAST_" + FieldName.OBSERVED_VALUES.name(), "FUTURE_" + FieldName.FEAT_TIME.name() }; private static final FieldName[] TIME_SERIES_FIELDS = { FieldName.FEAT_TIME, FieldName.OBSERVED_VALUES }; private List<BiFunction<NDManager, List<LocalDateTime>, NDArray>> timeFeatures; private InstanceSampler instanceSampler; private String[] predictInputFields; /** * Constructs a new {@code DeepARTranslator} instance. * * @param builder the data to build with */ public DeepARTranslator(Builder builder) { super(builder); this.useFeatDynamicReal = builder.useFeatDynamicReal; this.useFeatStaticReal = builder.useFeatStaticReal; this.useFeatStaticCat = builder.useFeatStaticCat; List<Integer> lagsSeq = Lag.getLagsForFreq(freq); this.timeFeatures = TimeFeature.timeFeaturesFromFreqStr(freq); this.historyLength = contextLength + lagsSeq.get(lagsSeq.size() - 1); this.instanceSampler = PredictionSplitSampler.newTestSplitSampler(); if (builder.useIsPad) { int len = PRED_INPUT_FIELDS.length; predictInputFields = new String[len + 1]; System.arraycopy(PRED_INPUT_FIELDS, 0, predictInputFields, 0, len); predictInputFields[len] = "PAST_" + FieldName.IS_PAD.name(); } else { predictInputFields = PRED_INPUT_FIELDS; } } /** {@inheritDoc} */ @Override public Forecast processOutput(TranslatorContext ctx, NDList list) { NDArray outputs = list.singletonOrThrow(); TimeSeriesData data = (TimeSeriesData) ctx.getAttachment("input"); outputs.attach((NDManager) ctx.getAttachment("manager")); return new SampleForecast(outputs, data.getStartTime(), this.freq); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, TimeSeriesData input) { NDManager manager = ctx.getNDManager(); ctx.setAttachment("input", input); ctx.setAttachment("manager", input.get(FieldName.TARGET).getManager()); List<FieldName> removeFieldNames = new ArrayList<>(); removeFieldNames.add(FieldName.FEAT_DYNAMIC_CAT); if (!useFeatStaticReal) { removeFieldNames.add(FieldName.FEAT_STATIC_REAL); } if (!useFeatDynamicReal) { removeFieldNames.add(FieldName.FEAT_DYNAMIC_REAL); } Field.removeFields(removeFieldNames, input); if (!useFeatStaticCat) { Field.setField(FieldName.FEAT_STATIC_CAT, manager.zeros(new Shape(1)), input); } if (!useFeatStaticReal) { Field.setField(FieldName.FEAT_STATIC_REAL, manager.zeros(new Shape(1)), input); } Convert.asArray(FieldName.FEAT_STATIC_CAT, 1, DataType.INT32, input); Convert.asArray(FieldName.FEAT_STATIC_REAL, 1, input); Feature.addObservedValuesIndicator( manager, FieldName.TARGET, FieldName.OBSERVED_VALUES, input); Feature.addTimeFeature( manager, FieldName.START, FieldName.TARGET, FieldName.FEAT_TIME, timeFeatures, predictionLength, freq, input); Feature.addAgeFeature( manager, FieldName.TARGET, FieldName.FEAT_AGE, predictionLength, input); FieldName[] inputFields; if (useFeatDynamicReal) { inputFields = new FieldName[3]; inputFields[2] = FieldName.FEAT_DYNAMIC_REAL; } else { inputFields = new FieldName[2]; } inputFields[0] = FieldName.FEAT_TIME; inputFields[1] = FieldName.FEAT_AGE; Convert.vstackFeatures(FieldName.FEAT_TIME, inputFields, input); Split.instanceSplit( manager, FieldName.TARGET, FieldName.IS_PAD, FieldName.START, FieldName.FORECAST_START, instanceSampler, historyLength, predictionLength, TIME_SERIES_FIELDS, 0, input); input = Field.selectField(predictInputFields, input); return input.toNDList(); } /** * Creates a builder to build a {@code DeepARTranslator}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** * Creates a builder to build a {@code DeepARTranslator}. * * @param arguments the models' arguments * @return a new builder */ public static Builder builder(Map<String, ?> arguments) { Builder builder = new Builder(); builder.configPreProcess(arguments); builder.configPostProcess(arguments); return builder; } /** The builder for DeepAR translator. */ public static class Builder extends BaseBuilder<Builder> { // preProcess args boolean useFeatDynamicReal; boolean useFeatStaticReal; boolean useFeatStaticCat; boolean useIsPad; Builder() {} @Override protected Builder self() { return this; } /** {@inheritDoc} */ @Override protected void configPreProcess(Map<String, ?> arguments) { super.configPreProcess(arguments); useFeatDynamicReal = ArgumentsUtil.booleanValue( arguments, "use_" + FieldName.FEAT_DYNAMIC_REAL.name().toLowerCase(), false); useFeatStaticCat = ArgumentsUtil.booleanValue( arguments, "use_" + FieldName.FEAT_STATIC_CAT.name().toLowerCase(), false); useFeatStaticReal = ArgumentsUtil.booleanValue( arguments, "use_" + FieldName.FEAT_STATIC_REAL.name().toLowerCase(), false); useIsPad = ArgumentsUtil.booleanValue(arguments, "use_is_pad", true); } /** * Builds the translator. * * @return the new translator */ public DeepARTranslator build() { validate(); return new DeepARTranslator(this); } } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/translator/DeepARTranslatorFactory.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.translator; import ai.djl.Model; import ai.djl.timeseries.Forecast; import ai.djl.timeseries.TimeSeriesData; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorFactory; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map; import java.util.Set; /** A {@link TranslatorFactory} that creates a {@link DeepARTranslator} instance. */ public class DeepARTranslatorFactory implements TranslatorFactory { /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { return Collections.singleton(new Pair<>(TimeSeriesData.class, Forecast.class)); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) { if (!isSupported(input, output)) { throw new IllegalArgumentException("Unsupported input/output types."); } return (Translator<I, O>) DeepARTranslator.builder(arguments).build(); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/translator/TransformerTranslator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.translator; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.Shape; import ai.djl.timeseries.Forecast; import ai.djl.timeseries.SampleForecast; import ai.djl.timeseries.TimeSeriesData; import ai.djl.timeseries.dataset.FieldName; import ai.djl.timeseries.timefeature.Lag; import ai.djl.timeseries.timefeature.TimeFeature; import ai.djl.timeseries.transform.InstanceSampler; import ai.djl.timeseries.transform.PredictionSplitSampler; import ai.djl.timeseries.transform.convert.Convert; import ai.djl.timeseries.transform.feature.Feature; import ai.djl.timeseries.transform.field.Field; import ai.djl.timeseries.transform.split.Split; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.BiFunction; /** The {@link Translator} for Transformer time series forecasting tasks. */ public class TransformerTranslator extends BaseTimeSeriesTranslator { private final boolean useFeatDynamicReal; private final boolean useFeatStaticCat; private int historyLength; private static final String[] PRED_INPUT_FIELDS = { FieldName.FEAT_STATIC_CAT.name(), "PAST_" + FieldName.FEAT_TIME.name(), "PAST_" + FieldName.TARGET.name(), "PAST_" + FieldName.OBSERVED_VALUES.name(), "FUTURE_" + FieldName.FEAT_TIME.name() }; private static final FieldName[] TIME_SERIES_FIELDS = { FieldName.FEAT_TIME, FieldName.OBSERVED_VALUES }; private final List<BiFunction<NDManager, List<LocalDateTime>, NDArray>> timeFeatures; private final InstanceSampler instanceSampler; /** * Constructs a {@link TransformerTranslator} with {@link Builder}. * * @param builder the data to build with */ public TransformerTranslator(Builder builder) { super(builder); this.useFeatDynamicReal = builder.useFeatDynamicReal; this.useFeatStaticCat = builder.useFeatStaticCat; List<Integer> lagsSeq = Lag.getLagsForFreq(freq); this.timeFeatures = TimeFeature.timeFeaturesFromFreqStr(freq); this.historyLength = contextLength + lagsSeq.get(lagsSeq.size() - 1); this.instanceSampler = PredictionSplitSampler.newTestSplitSampler(); } /** {@inheritDoc} */ @Override public Forecast processOutput(TranslatorContext ctx, NDList list) { NDArray outputs = list.singletonOrThrow(); TimeSeriesData data = (TimeSeriesData) ctx.getAttachment("input"); outputs.attach((NDManager) ctx.getAttachment("manager")); return new SampleForecast(outputs, data.getStartTime(), this.freq); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, TimeSeriesData input) { NDManager manager = ctx.getNDManager(); ctx.setAttachment("input", input); ctx.setAttachment("manager", input.get(FieldName.TARGET).getManager()); List<FieldName> removeFieldNames = new ArrayList<>(); removeFieldNames.add(FieldName.FEAT_DYNAMIC_CAT); removeFieldNames.add(FieldName.FEAT_STATIC_REAL); if (!useFeatDynamicReal) { removeFieldNames.add(FieldName.FEAT_DYNAMIC_REAL); } Field.removeFields(removeFieldNames, input); if (!useFeatStaticCat) { Field.setField(FieldName.FEAT_STATIC_CAT, manager.zeros(new Shape(1)), input); } Feature.addObservedValuesIndicator( manager, FieldName.TARGET, FieldName.OBSERVED_VALUES, input); Feature.addTimeFeature( manager, FieldName.START, FieldName.TARGET, FieldName.FEAT_TIME, timeFeatures, predictionLength, freq, input); Feature.addAgeFeature( manager, FieldName.TARGET, FieldName.FEAT_AGE, predictionLength, input); FieldName[] inputFields; if (useFeatDynamicReal) { inputFields = new FieldName[3]; inputFields[2] = FieldName.FEAT_DYNAMIC_REAL; } else { inputFields = new FieldName[2]; } inputFields[0] = FieldName.FEAT_TIME; inputFields[1] = FieldName.FEAT_AGE; Convert.vstackFeatures(FieldName.FEAT_TIME, inputFields, input); Split.instanceSplit( manager, FieldName.TARGET, FieldName.IS_PAD, FieldName.START, FieldName.FORECAST_START, instanceSampler, historyLength, predictionLength, TIME_SERIES_FIELDS, 0, input); input = Field.selectField(PRED_INPUT_FIELDS, input); return input.toNDList(); } /** * Creates a builder to build a {@code TransformerTranslator}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** * Creates a builder to build a {@code TransformerTranslator}. * * @param arguments the models' arguments * @return a new builder */ public static Builder builder(Map<String, ?> arguments) { Builder builder = new Builder(); builder.configPreProcess(arguments); builder.configPostProcess(arguments); return builder; } /** The builder for Transformer translator. */ public static class Builder extends BaseBuilder<Builder> { // preProcess args private boolean useFeatDynamicReal; private boolean useFeatStaticCat; // postProcess args Builder() {} @Override protected Builder self() { return this; } /** {@inheritDoc} */ @Override protected void configPreProcess(Map<String, ?> arguments) { super.configPreProcess(arguments); this.useFeatDynamicReal = ArgumentsUtil.booleanValue( arguments, "use_" + FieldName.FEAT_DYNAMIC_REAL.name().toLowerCase(), false); this.useFeatStaticCat = ArgumentsUtil.booleanValue( arguments, "use_" + FieldName.FEAT_STATIC_CAT.name().toLowerCase(), false); } /** * Builds the translator. * * @return the new translator */ public TransformerTranslator build() { validate(); return new TransformerTranslator(this); } } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/translator/TransformerTranslatorFactory.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.timeseries.translator; import ai.djl.Model; import ai.djl.timeseries.Forecast; import ai.djl.timeseries.TimeSeriesData; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorFactory; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map; import java.util.Set; /** A {@link TranslatorFactory} that creates a {@link DeepARTranslator} instance. */ public class TransformerTranslatorFactory implements TranslatorFactory { /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { return Collections.singleton(new Pair<>(TimeSeriesData.class, Forecast.class)); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) { if (!isSupported(input, output)) { throw new IllegalArgumentException("Unsupported input/output types."); } return (Translator<I, O>) TransformerTranslator.builder(arguments).build(); } }
0
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries
java-sources/ai/djl/timeseries/timeseries/0.34.0/ai/djl/timeseries/translator/package-info.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains translators for TimeSeries models inference. */ package ai.djl.timeseries.translator;
0
java-sources/ai/doorstep/com/doorstepai-dropoff-sdk/1.0.17/com/doorstepai/sdks
java-sources/ai/doorstep/com/doorstepai-dropoff-sdk/1.0.17/com/doorstepai/sdks/tracking/BuildConfig.java
/** * Automatically generated file. DO NOT MODIFY */ package com.doorstepai.sdks.tracking; public final class BuildConfig { public static final boolean DEBUG = false; public static final String LIBRARY_PACKAGE_NAME = "com.doorstepai.sdks.tracking"; public static final String BUILD_TYPE = "release"; public static final String FLAVOR = "prod"; // Field from product flavor: prod public static final String DATA_COLLECTION_API = "https://collection.api.track.doorstep.ai"; // Field from default config. public static final int SDK_VERSION_CODE = 1; // Field from default config. public static final String SDK_VERSION_NAME = "1.0.17"; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/config/DebugConfig.java
package ai.driftkit.audio.config; import lombok.Data; /** * Configuration for debug and development features. */ @Data public class DebugConfig { /** * Enable debug mode. * Default: false */ private boolean enabled = false; /** * Path for saving debug audio files. * Default: "./debug/audio" */ private String outputPath = "./debug/audio"; /** * Save raw PCM audio chunks. * Default: false */ private boolean saveRawAudio = false; /** * Save processed/converted audio. * Default: true */ private boolean saveProcessedAudio = true; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/converter/AudioConverter.java
package ai.driftkit.audio.converter; import ai.driftkit.audio.core.config.CoreAudioConfig; import ai.driftkit.audio.core.AudioFormatType; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import ws.schild.jave.*; import ws.schild.jave.encode.AudioAttributes; import ws.schild.jave.encode.EncodingAttributes; import javax.sound.sampled.*; import javax.sound.sampled.AudioFormat.Encoding; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.text.SimpleDateFormat; import java.util.Date; /** * Service for converting audio formats using Java libraries and FFmpeg fallback */ @Slf4j @AllArgsConstructor public class AudioConverter { private final CoreAudioConfig config; /** * Convert raw PCM audio data to MP3 format using ffmpeg */ public File convertRawToMp3WithFfmpeg(byte[] rawPcmData, String sessionPrefix) throws IOException, InterruptedException { File debugDir = new File(config.getDebug().getOutputPath()); if (!debugDir.exists()) { debugDir.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); String timestamp = sdf.format(new Date()); File rawFile = new File(debugDir, sessionPrefix + "temp_raw_" + timestamp + ".pcm"); File mp3File = new File(debugDir, sessionPrefix + "audio_" + timestamp + ".mp3"); // Write raw PCM data to file try (FileOutputStream fos = new FileOutputStream(rawFile)) { fos.write(rawPcmData); } // Build ffmpeg command ProcessBuilder pb = new ProcessBuilder( "ffmpeg", "-y", "-f", "s16be", "-ar", String.valueOf(config.getSampleRate()), "-ac", "1", "-i", rawFile.getAbsolutePath(), "-codec:a", "mp3", "-b:a", "64k", // 64 kbps for smaller file size "-ar", "16000", // Keep same sample rate mp3File.getAbsolutePath() ); Process process = pb.start(); int exitCode = process.waitFor(); // Clean up raw file if (!rawFile.delete()) { // Log warning if needed } if (exitCode == 0 && mp3File.exists()) { return mp3File; } else { throw new IOException("ffmpeg conversion failed with exit code: " + exitCode); } } /** * Convert raw PCM audio data to specified format using Java libraries. * Falls back to FFmpeg if Java conversion fails. * * @param rawPcmData Raw PCM audio data * @param sampleRate Sample rate of the audio * @param audioFormat Target format enum * @return Converted audio data */ public byte[] convertToFormat(byte[] rawPcmData, int sampleRate, AudioFormatType audioFormat) throws IOException, InterruptedException { log.debug("Converting audio to {} format using {}", audioFormat.getDisplayName(), audioFormat.getPreferredMethod()); try { // Try optimal conversion method based on format return switch (audioFormat.getPreferredMethod()) { case JAVA_SOUND -> convertWithJavaSound(rawPcmData, sampleRate, audioFormat); case JAVE -> convertWithJave(rawPcmData, sampleRate, audioFormat); case FFMPEG -> convertWithFFmpeg(rawPcmData, sampleRate, audioFormat); }; } catch (Exception e) { log.warn("Primary conversion method failed, falling back to FFmpeg", e); // Fallback to FFmpeg return convertWithFFmpeg(rawPcmData, sampleRate, audioFormat); } } /** * Convert audio using Java Sound API. */ private byte[] convertWithJavaSound(byte[] rawPcmData, int sampleRate, AudioFormatType audioFormat) throws IOException { return switch (audioFormat) { case WAV -> convertToWav(rawPcmData, sampleRate); case AU -> convertToAu(rawPcmData, sampleRate); case AIFF -> convertToAiff(rawPcmData, sampleRate); default -> throw new UnsupportedOperationException( "Java Sound API not supported for format: " + audioFormat.getDisplayName()); }; } /** * Convert audio using JAVE library. */ private byte[] convertWithJave(byte[] rawPcmData, int sampleRate, AudioFormatType audioFormat) throws IOException { String extension = audioFormat.getExtension(); Path tempDir = Files.createTempDirectory("jave-conversion"); Path inputWav = tempDir.resolve("input.wav"); Path outputFile = tempDir.resolve("output." + extension); try { // First convert raw PCM to WAV (JAVE input format) byte[] wavData = convertToWav(rawPcmData, sampleRate); Files.write(inputWav, wavData); // Set up JAVE conversion MultimediaObject source = new MultimediaObject(inputWav.toFile()); // Configure audio attributes based on format AudioAttributes audioAttributes = new AudioAttributes(); audioAttributes.setSamplingRate(sampleRate); audioAttributes.setChannels(1); // Mono switch (audioFormat) { case MP3: audioAttributes.setCodec("libmp3lame"); audioAttributes.setBitRate(64000); // 64 kbps break; case OGG: audioAttributes.setCodec("libvorbis"); audioAttributes.setBitRate(128000); // 128 kbps break; case FLAC: audioAttributes.setCodec("flac"); // No bitrate for lossless break; case AAC: audioAttributes.setCodec("aac"); audioAttributes.setBitRate(128000); // 128 kbps break; default: throw new IllegalArgumentException("Unsupported format for JAVE: " + audioFormat.getDisplayName()); } // Set encoding attributes EncodingAttributes encodingAttributes = new EncodingAttributes(); encodingAttributes.setInputFormat("wav"); encodingAttributes.setOutputFormat(extension); encodingAttributes.setAudioAttributes(audioAttributes); // Perform conversion Encoder encoder = new Encoder(); encoder.encode(source, outputFile.toFile(), encodingAttributes); if (!Files.exists(outputFile)) { throw new IOException("JAVE conversion failed - output file not created"); } return Files.readAllBytes(outputFile); } catch (EncoderException e) { throw new IOException("JAVE encoding failed", e); } finally { // Clean up temporary files try { Files.deleteIfExists(inputWav); Files.deleteIfExists(outputFile); Files.deleteIfExists(tempDir); } catch (IOException e) { log.warn("Failed to clean up JAVE temporary files", e); } } } /** * Convert raw PCM to WAV format using Java Sound API. */ private byte[] convertToWav(byte[] rawPcmData, int sampleRate) throws IOException { // Create audio format AudioFormat audioFormat = new AudioFormat( Encoding.PCM_SIGNED, sampleRate, 16, // bits per sample 1, // channels (mono) 2, // frame size (16 bits = 2 bytes) sampleRate, false // little endian ); // Create audio input stream from raw data ByteArrayInputStream rawInputStream = new ByteArrayInputStream(rawPcmData); AudioInputStream audioInputStream = new AudioInputStream( rawInputStream, audioFormat, rawPcmData.length / audioFormat.getFrameSize()); // Convert to WAV format ByteArrayOutputStream wavOutputStream = new ByteArrayOutputStream(); AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, wavOutputStream); audioInputStream.close(); return wavOutputStream.toByteArray(); } /** * Convert raw PCM to AU format using Java Sound API. */ private byte[] convertToAu(byte[] rawPcmData, int sampleRate) throws IOException { AudioFormat audioFormat = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, sampleRate, 16, 1, 2, sampleRate, true // big endian for AU ); ByteArrayInputStream rawInputStream = new ByteArrayInputStream(rawPcmData); AudioInputStream audioInputStream = new AudioInputStream( rawInputStream, audioFormat, rawPcmData.length / audioFormat.getFrameSize()); ByteArrayOutputStream auOutputStream = new ByteArrayOutputStream(); AudioSystem.write(audioInputStream, AudioFileFormat.Type.AU, auOutputStream); audioInputStream.close(); return auOutputStream.toByteArray(); } /** * Convert raw PCM to AIFF format using Java Sound API. */ private byte[] convertToAiff(byte[] rawPcmData, int sampleRate) throws IOException { AudioFormat audioFormat = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, sampleRate, 16, 1, 2, sampleRate, true // big endian for AIFF ); ByteArrayInputStream rawInputStream = new ByteArrayInputStream(rawPcmData); AudioInputStream audioInputStream = new AudioInputStream( rawInputStream, audioFormat, rawPcmData.length / audioFormat.getFrameSize()); ByteArrayOutputStream aiffOutputStream = new ByteArrayOutputStream(); AudioSystem.write(audioInputStream, AudioFileFormat.Type.AIFF, aiffOutputStream); audioInputStream.close(); return aiffOutputStream.toByteArray(); } /** * Fallback conversion using FFmpeg for formats not supported by Java. */ private byte[] convertWithFFmpeg(byte[] rawPcmData, int sampleRate, AudioFormatType audioFormat) throws IOException, InterruptedException { String extension = audioFormat.getExtension(); Path tempDir = Files.createTempDirectory("audio-conversion"); Path rawFile = tempDir.resolve("input.pcm"); Path convertedFile = tempDir.resolve("output." + extension); try { // Write raw PCM data to temporary file Files.write(rawFile, rawPcmData); // Build ffmpeg command based on format ProcessBuilder pb = buildFFmpegCommand( rawFile.toString(), convertedFile.toString(), sampleRate, audioFormat ); Process process = pb.start(); int exitCode = process.waitFor(); if (exitCode != 0) { throw new IOException("FFmpeg conversion failed with exit code: " + exitCode); } if (!Files.exists(convertedFile)) { throw new IOException("Converted audio file was not created"); } return Files.readAllBytes(convertedFile); } finally { // Clean up temporary files try { Files.deleteIfExists(rawFile); Files.deleteIfExists(convertedFile); Files.deleteIfExists(tempDir); } catch (IOException e) { log.warn("Failed to clean up temporary files", e); } } } private ProcessBuilder buildFFmpegCommand( String inputFile, String outputFile, int sampleRate, AudioFormatType audioFormat) { return switch (audioFormat) { case WAV -> new ProcessBuilder( "ffmpeg", "-y", "-f", "s16le", // Little-endian 16-bit PCM "-ar", String.valueOf(sampleRate), "-ac", "1", // Mono "-i", inputFile, "-f", "wav", outputFile ); case MP3 -> new ProcessBuilder( "ffmpeg", "-y", "-f", "s16le", "-ar", String.valueOf(sampleRate), "-ac", "1", "-i", inputFile, "-codec:a", "mp3", "-b:a", "64k", outputFile ); case FLAC -> new ProcessBuilder( "ffmpeg", "-y", "-f", "s16le", "-ar", String.valueOf(sampleRate), "-ac", "1", "-i", inputFile, "-codec:a", "flac", outputFile ); case OGG -> new ProcessBuilder( "ffmpeg", "-y", "-f", "s16le", "-ar", String.valueOf(sampleRate), "-ac", "1", "-i", inputFile, "-codec:a", "libvorbis", "-b:a", "128k", outputFile ); case AAC -> new ProcessBuilder( "ffmpeg", "-y", "-f", "s16le", "-ar", String.valueOf(sampleRate), "-ac", "1", "-i", inputFile, "-codec:a", "aac", "-b:a", "128k", outputFile ); case M4A -> new ProcessBuilder( "ffmpeg", "-y", "-f", "s16le", "-ar", String.valueOf(sampleRate), "-ac", "1", "-i", inputFile, "-codec:a", "aac", "-f", "mp4", outputFile ); default -> throw new IllegalArgumentException("Unsupported audio format for FFmpeg: " + audioFormat.getDisplayName()); }; } /** * Get available conversion methods for a format. * * @param format Audio format * @return Information about conversion method */ public ConversionInfo getConversionInfo(String format) { String formatLower = format.toLowerCase(); boolean javaSupported = switch (formatLower) { case "wav", "au", "aiff" -> true; // Java Sound API case "mp3", "ogg", "flac" -> true; // JAVE library default -> false; }; boolean ffmpegSupported = switch (formatLower) { case "wav", "mp3", "flac", "ogg", "aac", "m4a" -> true; default -> false; }; return new ConversionInfo(formatLower, javaSupported, ffmpegSupported); } /** * Information about conversion capabilities for a format. */ public static class ConversionInfo { private final String format; private final boolean javaSupported; private final boolean ffmpegSupported; public ConversionInfo(String format, boolean javaSupported, boolean ffmpegSupported) { this.format = format; this.javaSupported = javaSupported; this.ffmpegSupported = ffmpegSupported; } public String getFormat() { return format; } public boolean isJavaSupported() { return javaSupported; } public boolean isFFmpegSupported() { return ffmpegSupported; } public boolean isSupported() { return javaSupported || ffmpegSupported; } public String getPreferredMethod() { if (javaSupported) return "Java libraries (JAVE/Sound API)"; if (ffmpegSupported) return "FFmpeg"; return "Not supported"; } @Override public String toString() { return String.format("ConversionInfo{format='%s', java=%s, ffmpeg=%s, preferred='%s'}", format, javaSupported, ffmpegSupported, getPreferredMethod()); } } /** * Fast conversion to WAV format optimized for memory usage. * This method is optimized for real-time processing. */ public byte[] convertToWavFast(byte[] rawPcmData, int sampleRate) { try { return convertToWav(rawPcmData, sampleRate); } catch (IOException e) { log.error("Fast WAV conversion failed", e); throw new RuntimeException("WAV conversion failed", e); } } /** * Check if a format can be converted purely in Java without external dependencies. */ public boolean isPureJavaSupported(String format) { return switch (format.toLowerCase()) { case "wav", "au", "aiff" -> true; // Pure Java Sound API default -> false; // JAVE and FFmpeg require native binaries }; } /** * Get performance characteristics for a conversion method. */ public PerformanceInfo getPerformanceInfo(String format) { ConversionInfo conversionInfo = getConversionInfo(format); if (conversionInfo.isJavaSupported()) { boolean pureJava = isPureJavaSupported(format); return new PerformanceInfo( pureJava ? "Fastest" : "Fast", pureJava ? "Very Low" : "Low", pureJava ? "None" : "Native libraries required" ); } else if (conversionInfo.isFFmpegSupported()) { return new PerformanceInfo("Slower", "High", "FFmpeg binary required"); } else { return new PerformanceInfo("Not supported", "N/A", "Format not supported"); } } /** * Performance characteristics for conversion methods. */ public static class PerformanceInfo { private final String speed; private final String resourceUsage; private final String dependencies; public PerformanceInfo(String speed, String resourceUsage, String dependencies) { this.speed = speed; this.resourceUsage = resourceUsage; this.dependencies = dependencies; } public String getSpeed() { return speed; } public String getResourceUsage() { return resourceUsage; } public String getDependencies() { return dependencies; } @Override public String toString() { return String.format("Performance{speed='%s', resources='%s', deps='%s'}", speed, resourceUsage, dependencies); } } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/AudioFormatType.java
package ai.driftkit.audio.core; import lombok.Getter; /** * Enumeration of supported audio formats for conversion. */ @Getter public enum AudioFormatType { // Java Sound API supported formats (fastest) WAV("wav", "WAVE", true, false), AU("au", "AU", true, false), AIFF("aiff", "AIFF", true, false), // JAVE library supported formats (medium speed) MP3("mp3", "MP3", false, true), OGG("ogg", "OGG", false, true), FLAC("flac", "FLAC", false, true), AAC("aac", "AAC", false, true), // FFmpeg fallback formats (slower but comprehensive) WMA("wma", "WMA", false, false), M4A("m4a", "M4A", false, false), OPUS("opus", "OPUS", false, false), AC3("ac3", "AC3", false, false); private final String extension; private final String displayName; private final boolean javaSoundSupported; private final boolean javeSupported; AudioFormatType(String extension, String displayName, boolean javaSoundSupported, boolean javeSupported) { this.extension = extension; this.displayName = displayName; this.javaSoundSupported = javaSoundSupported; this.javeSupported = javeSupported; } /** * Get the file extension for this format. */ public String getExtension() { return extension; } /** * Get the display name for this format. */ public String getDisplayName() { return displayName; } /** * Check if this format is supported by Java Sound API. */ public boolean isJavaSoundSupported() { return javaSoundSupported; } /** * Check if this format is supported by JAVE library. */ public boolean isJaveSupported() { return javeSupported; } /** * Get AudioFormat from string extension. * * @param extension File extension (with or without dot) * @return AudioFormat enum value * @throws IllegalArgumentException if format is not supported */ public static AudioFormatType fromExtension(String extension) { if (extension == null) { throw new IllegalArgumentException("Extension cannot be null"); } // Remove dot if present String cleanExtension = extension.startsWith(".") ? extension.substring(1) : extension; for (AudioFormatType format : values()) { if (format.extension.equalsIgnoreCase(cleanExtension)) { return format; } } throw new IllegalArgumentException("Unsupported audio format: " + extension); } /** * Check if the format is supported by any conversion method. */ public boolean isSupported() { return javaSoundSupported || javeSupported; } /** * Get the preferred conversion method for this format. */ public ConversionMethod getPreferredMethod() { if (javaSoundSupported) { return ConversionMethod.JAVA_SOUND; } else if (javeSupported) { return ConversionMethod.JAVE; } else { return ConversionMethod.FFMPEG; } } /** * Enumeration of conversion methods. */ public enum ConversionMethod { JAVA_SOUND("Java Sound API - Fastest, native Java"), JAVE("JAVE Library - Fast, embedded FFmpeg"), FFMPEG("FFmpeg - Slower, external dependency but most comprehensive"); private final String description; ConversionMethod(String description) { this.description = description; } public String getDescription() { return description; } } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/AudioSessionManager.java
package ai.driftkit.audio.core; import ai.driftkit.audio.converter.AudioConverter; import ai.driftkit.audio.core.config.CoreAudioConfig; import ai.driftkit.audio.engine.TranscriptionEngine; import ai.driftkit.audio.engine.TranscriptionEngineFactory; import ai.driftkit.audio.model.TranscriptionResult; import ai.driftkit.audio.processor.AudioAnalyzer; import ai.driftkit.audio.processor.BatchAudioProcessor; import lombok.extern.slf4j.Slf4j; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Consumer; /** * Audio session manager that supports multiple transcription engines * and both batch and streaming processing modes. */ @Slf4j public class AudioSessionManager { private final CoreAudioConfig config; private final TranscriptionEngine engine; private final AudioConverter audioConverter; // For batch mode processing private final ConcurrentMap<String, BatchAudioProcessor> batchProcessors = new ConcurrentHashMap<>(); // For streaming mode - callbacks are managed by the engine private final ConcurrentMap<String, Consumer<TranscriptionResult>> streamingCallbacks = new ConcurrentHashMap<>(); public AudioSessionManager( CoreAudioConfig config, TranscriptionEngineFactory engineFactory, AudioConverter audioConverter) { this.config = config; this.audioConverter = audioConverter; // Create engine based on configuration this.engine = engineFactory.createEngine(); log.info("Enhanced audio session manager initialized with {} engine in {} mode", engine.getName(), config.getProcessingMode()); } /** * Create a new audio processing session. * * @param sessionId Unique session identifier * @param resultCallback Callback for transcription results */ public void createSession(String sessionId, Consumer<TranscriptionResult> resultCallback) { if (hasSession(sessionId)) { throw new IllegalArgumentException("Session already exists: " + sessionId); } switch (config.getProcessingMode()) { case STREAMING: // For streaming mode, start a streaming session with the engine streamingCallbacks.put(sessionId, resultCallback); engine.startStreamingSession( sessionId, config.getSampleRate(), getLanguageCode(), resultCallback ); log.debug("Created streaming session: {}", sessionId); break; case BATCH: // For batch mode, create a batch processor with its own AudioAnalyzer AudioAnalyzer sessionAnalyzer = new AudioAnalyzer(config); BatchAudioProcessor processor = new BatchAudioProcessor( sessionId, config, sessionAnalyzer, audioConverter, engine, resultCallback); batchProcessors.put(sessionId, processor); log.debug("Created batch session: {}", sessionId); break; } } /** * Process audio chunk for a session. * * @param sessionId Session identifier * @param audioData Audio data to process */ public void processAudioChunk(String sessionId, byte[] audioData) { switch (config.getProcessingMode()) { case STREAMING: // For streaming mode, send directly to engine engine.sendStreamingAudio(sessionId, audioData); break; case BATCH: // For batch mode, use the batch processor BatchAudioProcessor processor = batchProcessors.get(sessionId); if (processor == null) { throw new IllegalArgumentException("No active session found: " + sessionId); } processor.processAudioChunk(audioData); break; } } /** * Check if a session exists. * * @param sessionId Session identifier * @return true if session exists */ public boolean hasSession(String sessionId) { return batchProcessors.containsKey(sessionId) || engine.isStreamingSessionActive(sessionId); } /** * Close a session. * * @param sessionId Session identifier */ public void closeSession(String sessionId) { // Close streaming session if exists if (engine.isStreamingSessionActive(sessionId)) { engine.stopStreamingSession(sessionId); streamingCallbacks.remove(sessionId); log.debug("Closed streaming session: {}", sessionId); } // Close batch processor if exists BatchAudioProcessor processor = batchProcessors.remove(sessionId); if (processor != null) { processor.close(); log.debug("Closed batch session: {}", sessionId); } } /** * Get all active session IDs. * * @return Set of active session IDs */ public Set<String> getActiveSessions() { Set<String> sessions = new java.util.HashSet<>(); sessions.addAll(batchProcessors.keySet()); sessions.addAll(streamingCallbacks.keySet()); return sessions; } /** * Close all active sessions. */ public void closeAllSessions() { // Close all batch sessions batchProcessors.forEach((id, processor) -> processor.close()); batchProcessors.clear(); // Close all streaming sessions streamingCallbacks.keySet().forEach(engine::stopStreamingSession); streamingCallbacks.clear(); log.info("All audio sessions closed"); } public void shutdown() { closeAllSessions(); engine.shutdown(); log.info("Enhanced audio session manager shut down"); } private String getLanguageCode() { // Get language code based on engine type switch (config.getEngine()) { case ASSEMBLYAI: return config.getAssemblyai().getLanguageCode().getValue(); case DEEPGRAM: return config.getDeepgram().getLanguage().getValue(); default: return "en"; // Default } } /** * Get session statistics (placeholder for future implementation). */ public SessionStats getSessionStats(String sessionId) { // TODO: Implement session statistics return new SessionStats(); } public static class SessionStats { // Placeholder for session statistics private long chunksProcessed; private long bytesProcessed; private long transcriptionsReceived; // Getters/setters would be here } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/ProcessingMode.java
package ai.driftkit.audio.core; /** * Enumeration of supported processing modes. */ public enum ProcessingMode { BATCH("batch"), STREAMING("streaming"); private final String value; ProcessingMode(String value) { this.value = value; } public String getValue() { return value; } public static ProcessingMode fromValue(String value) { for (ProcessingMode mode : values()) { if (mode.value.equals(value)) { return mode; } } throw new IllegalArgumentException("Unknown processing mode: " + value); } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/config/AssemblyAIConfig.java
package ai.driftkit.audio.core.config; import lombok.Data; /** * Configuration for AssemblyAI transcription service. */ @Data public class AssemblyAIConfig { /** * AssemblyAI API key. */ private String apiKey; /** * Language code for transcription. * Default: ENGLISH */ private LanguageCode languageCode = LanguageCode.ENGLISH; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/config/CoreAudioConfig.java
package ai.driftkit.audio.core.config; import ai.driftkit.audio.core.ProcessingMode; import lombok.Data; /** * Core configuration for audio processing without Spring dependencies. * This is a simple POJO that can be used by the core module. */ @Data public class CoreAudioConfig { /** * Transcription engine to use. * Default: ASSEMBLYAI */ private EngineType engine = EngineType.ASSEMBLYAI; /** * Processing mode for transcription. * Default: BATCH */ private ProcessingMode processingMode = ProcessingMode.BATCH; // Engine Configuration private AssemblyAIConfig assemblyai = new AssemblyAIConfig(); private CoreDeepgramConfig deepgram = new CoreDeepgramConfig(); // Audio Format Settings private int sampleRate = 16000; private int bufferSize = 4096; private int bufferSizeMs = 100; // Chunk Duration Settings private int maxChunkDurationSeconds = 60; private int minChunkDurationSeconds = 2; // Voice Activity Detection private VadConfig vad = new VadConfig(); // Debug Settings private DebugConfig debug = new DebugConfig(); // Performance and Resource Settings private int maxChunkSizeKb = 1024; private int maxBufferSizeMb = 10; private int processingTimeoutMs = 30000; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/config/CoreDeepgramConfig.java
package ai.driftkit.audio.core.config; import lombok.Data; /** * Core configuration for Deepgram transcription service without Spring dependencies. */ @Data public class CoreDeepgramConfig { /** * Deepgram API key. */ private String apiKey; /** * Language code for transcription. * Default: ENGLISH */ private LanguageCode language = LanguageCode.ENGLISH; /** * Deepgram model to use. * Options: "nova-2", "nova", "enhanced", "base" * Default: "nova-2" */ private String model = "nova-2"; /** * Whether to add punctuation to transcriptions. * Default: true */ private boolean punctuate = true; /** * Whether to enable interim results for streaming. * Default: true */ private boolean interimResults = true; /** * Whether to enable automatic language detection. * Default: false */ private boolean detectLanguage = false; /** * Whether to enable speaker diarization. * Default: false */ private boolean diarize = false; /** * Number of speakers to detect if diarization is enabled. * Default: 2 */ private int diarizeVersion = 2; /** * Whether to enable profanity filtering. * Default: false */ private boolean profanityFilter = false; /** * Whether to enable redaction of sensitive information. * Default: false */ private boolean redact = false; /** * Smart formatting options. * Default: false */ private boolean smartFormat = false; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/config/DebugConfig.java
package ai.driftkit.audio.core.config; import lombok.Data; /** * Configuration for debug and development features. */ @Data public class DebugConfig { /** * Enable debug mode. * Default: false */ private boolean enabled = false; /** * Path for saving debug audio files. * Default: "./debug/audio" */ private String outputPath = "./debug/audio"; /** * Save raw PCM audio chunks. * Default: false */ private boolean saveRawAudio = false; /** * Save processed/converted audio. * Default: true */ private boolean saveProcessedAudio = true; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/config/DeepgramConfig.java
package ai.driftkit.audio.core.config; import lombok.Data; /** * Configuration properties for Deepgram transcription service. */ @Data public class DeepgramConfig { /** * Deepgram API key. */ private String apiKey; /** * Language code for transcription. * Default: ENGLISH */ private LanguageCode language = LanguageCode.ENGLISH; /** * Deepgram model to use. * Options: "nova-2", "nova", "enhanced", "base" * Default: "nova-2" */ private String model = "nova-2"; /** * Whether to add punctuation to transcriptions. * Default: true */ private boolean punctuate = true; /** * Whether to enable interim results for streaming. * Default: true */ private boolean interimResults = true; /** * Whether to enable automatic language detection. * Default: false */ private boolean detectLanguage = false; /** * Whether to enable speaker diarization. * Default: false */ private boolean diarize = false; /** * Number of speakers to detect if diarization is enabled. * Default: 2 */ private int diarizeVersion = 2; /** * Whether to enable profanity filtering. * Default: false */ private boolean profanityFilter = false; /** * Whether to enable redaction of sensitive information. * Default: false */ private boolean redact = false; /** * Smart formatting options. * Default: false */ private boolean smartFormat = false; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/config/EngineType.java
package ai.driftkit.audio.core.config; /** * Enumeration of supported transcription engines. */ public enum EngineType { ASSEMBLYAI("assemblyai"), DEEPGRAM("deepgram"); private final String value; EngineType(String value) { this.value = value; } public String getValue() { return value; } public static EngineType fromValue(String value) { for (EngineType engine : values()) { if (engine.value.equals(value)) { return engine; } } throw new IllegalArgumentException("Unknown transcription engine: " + value); } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/config/LanguageCode.java
package ai.driftkit.audio.core.config; /** * Enumeration of supported language codes for transcription. */ public enum LanguageCode { ENGLISH("en"), SPANISH("es"), FRENCH("fr"), GERMAN("de"), ITALIAN("it"), PORTUGUESE("pt"), DUTCH("nl"), RUSSIAN("ru"), CHINESE("zh"), JAPANESE("ja"), KOREAN("ko"), ARABIC("ar"), HINDI("hi"), TURKISH("tr"), POLISH("pl"), SWEDISH("sv"), NORWEGIAN("no"), DANISH("da"), FINNISH("fi"), CZECH("cs"), HUNGARIAN("hu"), ROMANIAN("ro"), BULGARIAN("bg"), CROATIAN("hr"), SLOVAK("sk"), SLOVENIAN("sl"), ESTONIAN("et"), LATVIAN("lv"), LITHUANIAN("lt"), UKRAINIAN("uk"), VIETNAMESE("vi"), THAI("th"), INDONESIAN("id"), MALAY("ms"), TAMIL("ta"), BENGALI("bn"), GUJARATI("gu"), MARATHI("mr"), TELUGU("te"), KANNADA("kn"), MALAYALAM("ml"), PUNJABI("pa"), URDU("ur"), HEBREW("he"), PERSIAN("fa"), GREEK("el"), CATALAN("ca"), BASQUE("eu"), GALICIAN("gl"), WELSH("cy"), IRISH("ga"), SCOTTISH_GAELIC("gd"), ICELANDIC("is"), MALTESE("mt"), AFRIKAANS("af"), SWAHILI("sw"), YORUBA("yo"), HAUSA("ha"), IGBO("ig"), AMHARIC("am"), SOMALI("so"), MULTI("multi"); private final String value; LanguageCode(String value) { this.value = value; } public String getValue() { return value; } public static LanguageCode fromValue(String value) { if (value == null) { return ENGLISH; // Default } for (LanguageCode language : values()) { if (language.value.equals(value)) { return language; } } throw new IllegalArgumentException("Unknown language code: " + value); } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/config/ProcessingMode.java
package ai.driftkit.audio.core.config; /** * Enumeration of supported processing modes. */ public enum ProcessingMode { BATCH("batch"), STREAMING("streaming"); private final String value; ProcessingMode(String value) { this.value = value; } public String getValue() { return value; } public static ProcessingMode fromValue(String value) { for (ProcessingMode mode : values()) { if (mode.value.equals(value)) { return mode; } } throw new IllegalArgumentException("Unknown processing mode: " + value); } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/core/config/VadConfig.java
package ai.driftkit.audio.core.config; import lombok.Data; /** * Configuration for Voice Activity Detection (VAD). */ @Data public class VadConfig { /** * Enable/disable VAD. * Default: true */ private boolean enabled = true; /** * Energy threshold for speech detection (0.0-1.0). * Lower values are more sensitive. * Default: 0.005 */ private double threshold = 0.005; /** * Minimum duration of speech to consider (milliseconds). * Default: 250ms */ private int minSpeechDurationMs = 250; /** * Duration of silence before finalizing chunk (milliseconds). * Default: 1000ms */ private int silenceDurationMs = 1000; /** * Enable adaptive threshold adjustment. * Default: true */ private boolean adaptiveThreshold = true; /** * Base noise level for adaptive threshold. * Default: 0.001 */ private double noiseLevel = 0.001; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/engine/AbstractTranscriptionEngine.java
package ai.driftkit.audio.engine; import ai.driftkit.audio.core.config.CoreAudioConfig; import lombok.extern.slf4j.Slf4j; import ai.driftkit.audio.model.TranscriptionResult; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; /** * Abstract base class for transcription engines providing common functionality. */ @Slf4j public abstract class AbstractTranscriptionEngine implements TranscriptionEngine { protected final CoreAudioConfig config; protected final Map<String, StreamingSession> streamingSessions = new ConcurrentHashMap<>(); protected AbstractTranscriptionEngine(CoreAudioConfig config) { this.config = config; } @Override public CompletableFuture<TranscriptionResult> transcribeBatch( byte[] audioData, int sampleRate, String languageCode) { if (!supportsBatchMode()) { throw new UnsupportedOperationException( getName() + " does not support batch transcription mode"); } return doTranscribeBatch(audioData, sampleRate, languageCode); } @Override public void startStreamingSession( String sessionId, int sampleRate, String languageCode, Consumer<TranscriptionResult> resultCallback) { if (!supportsStreamingMode()) { throw new UnsupportedOperationException( getName() + " does not support streaming transcription mode"); } if (streamingSessions.containsKey(sessionId)) { throw new IllegalStateException( "Streaming session already exists: " + sessionId); } StreamingSession session = createStreamingSession( sessionId, sampleRate, languageCode, resultCallback); streamingSessions.put(sessionId, session); log.debug("Started streaming session {} for engine {}", sessionId, getName()); } @Override public void sendStreamingAudio(String sessionId, byte[] audioData) { if (!supportsStreamingMode()) { throw new UnsupportedOperationException( getName() + " does not support streaming transcription mode"); } StreamingSession session = streamingSessions.get(sessionId); if (session == null) { throw new IllegalStateException( "No active streaming session found: " + sessionId); } session.sendAudio(audioData); } @Override public void stopStreamingSession(String sessionId) { if (!supportsStreamingMode()) { throw new UnsupportedOperationException( getName() + " does not support streaming transcription mode"); } StreamingSession session = streamingSessions.remove(sessionId); if (session != null) { session.close(); log.debug("Stopped streaming session {} for engine {}", sessionId, getName()); } } @Override public boolean isStreamingSessionActive(String sessionId) { StreamingSession session = streamingSessions.get(sessionId); return session != null && session.isActive(); } @Override public void shutdown() { // Close all active streaming sessions streamingSessions.values().forEach(StreamingSession::close); streamingSessions.clear(); doShutdown(); log.info("{} engine shut down", getName()); } /** * Perform batch transcription implementation. */ protected abstract CompletableFuture<TranscriptionResult> doTranscribeBatch( byte[] audioData, int sampleRate, String languageCode); /** * Create a new streaming session implementation. */ protected abstract StreamingSession createStreamingSession( String sessionId, int sampleRate, String languageCode, Consumer<TranscriptionResult> resultCallback); /** * Perform engine-specific shutdown tasks. */ protected abstract void doShutdown(); /** * Interface for streaming session implementations. */ protected interface StreamingSession { void sendAudio(byte[] audioData); void close(); boolean isActive(); } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/engine/EngineConfiguration.java
package ai.driftkit.audio.engine; import lombok.Builder; import lombok.Data; import java.util.Map; /** * Configuration metadata for transcription engines. */ @Data @Builder public class EngineConfiguration { /** * Engine type identifier. */ private String engineType; /** * Required configuration keys and their descriptions. */ private Map<String, String> requiredConfig; /** * Optional configuration keys and their descriptions. */ private Map<String, String> optionalConfig; /** * Supported audio formats. */ private AudioFormat supportedFormats; /** * Processing mode capabilities. */ private ProcessingMode processingMode; /** * Maximum audio chunk size for streaming (in bytes). */ private Integer maxStreamingChunkSize; /** * Recommended buffer size for streaming (in milliseconds). */ private Integer recommendedBufferSizeMs; /** * Whether the engine requires audio format conversion. */ private boolean requiresConversion; @Data @Builder public static class AudioFormat { private int[] supportedSampleRates; private int[] supportedChannels; private int[] supportedBitsPerSample; private String[] supportedEncodings; } public enum ProcessingMode { BATCH_ONLY, STREAMING_ONLY, BOTH } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/engine/TranscriptionEngine.java
package ai.driftkit.audio.engine; import ai.driftkit.audio.model.TranscriptionResult; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; /** * Interface for transcription engines supporting both batch and streaming modes. * Implementations can provide either batch processing, streaming, or both. */ public interface TranscriptionEngine { /** * Get the name of this transcription engine. * @return Engine name (e.g., "AssemblyAI", "Deepgram") */ String getName(); /** * Check if this engine supports batch transcription. * @return true if batch mode is supported */ boolean supportsBatchMode(); /** * Check if this engine supports streaming transcription. * @return true if streaming mode is supported */ boolean supportsStreamingMode(); /** * Initialize the engine with configuration. * Called once when the engine is created. */ void initialize(); /** * Shutdown the engine and release resources. */ void shutdown(); /** * Transcribe audio data in batch mode. * * @param audioData Audio data to transcribe * @param sampleRate Sample rate of the audio * @param languageCode Language code for transcription * @return CompletableFuture with transcription result * @throws UnsupportedOperationException if batch mode is not supported */ CompletableFuture<TranscriptionResult> transcribeBatch( byte[] audioData, int sampleRate, String languageCode); /** * Start a streaming transcription session. * * @param sessionId Unique session identifier * @param sampleRate Sample rate of the audio stream * @param languageCode Language code for transcription * @param resultCallback Callback for transcription results * @throws UnsupportedOperationException if streaming mode is not supported */ void startStreamingSession( String sessionId, int sampleRate, String languageCode, Consumer<TranscriptionResult> resultCallback); /** * Send audio data to an active streaming session. * * @param sessionId Session identifier * @param audioData Audio data chunk * @throws IllegalStateException if session doesn't exist * @throws UnsupportedOperationException if streaming mode is not supported */ void sendStreamingAudio(String sessionId, byte[] audioData); /** * Stop a streaming transcription session. * * @param sessionId Session identifier * @throws UnsupportedOperationException if streaming mode is not supported */ void stopStreamingSession(String sessionId); /** * Check if a streaming session is active. * * @param sessionId Session identifier * @return true if session is active */ boolean isStreamingSessionActive(String sessionId); /** * Get configuration requirements for this engine. * @return Configuration metadata */ EngineConfiguration getConfiguration(); }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/engine/TranscriptionEngineFactory.java
package ai.driftkit.audio.engine; import ai.driftkit.audio.core.config.CoreAudioConfig; import ai.driftkit.audio.core.config.EngineType; import ai.driftkit.audio.engine.impl.AssemblyAIEngine; import ai.driftkit.audio.engine.impl.DeepgramEngine; import lombok.extern.slf4j.Slf4j; import java.util.HashMap; import java.util.Map; /** * Factory for creating transcription engine instances based on configuration. */ @Slf4j public class TranscriptionEngineFactory { private final CoreAudioConfig config; public TranscriptionEngineFactory(CoreAudioConfig config) { this.config = config; } /** * Create a transcription engine based on the configured engine type. * * @return Configured transcription engine * @throws IllegalArgumentException if engine type is not supported */ public TranscriptionEngine createEngine() { EngineType engineType = config.getEngine(); TranscriptionEngine engine; switch (engineType) { case ASSEMBLYAI: engine = new AssemblyAIEngine(config); break; case DEEPGRAM: engine = new DeepgramEngine(config); break; default: throw new IllegalArgumentException("Unsupported transcription engine: " + engineType); } // Validate processing mode compatibility switch (config.getProcessingMode()) { case STREAMING: if (!engine.supportsStreamingMode()) { throw new IllegalStateException( String.format("Engine '%s' does not support streaming mode", engine.getName())); } break; case BATCH: if (!engine.supportsBatchMode()) { throw new IllegalStateException( String.format("Engine '%s' does not support batch mode", engine.getName())); } break; } engine.initialize(); log.info("Created {} transcription engine in {} mode", engine.getName(), config.getProcessingMode()); return engine; } /** * Get the supported engines and their capabilities. * * @return Map of engine names to their configurations */ public static Map<EngineType, EngineConfiguration> getSupportedEngines() { Map<EngineType, EngineConfiguration> engines = new HashMap<>(); // Add AssemblyAI CoreAudioConfig dummyConfig = new CoreAudioConfig(); AssemblyAIEngine assemblyAI = new AssemblyAIEngine(dummyConfig); engines.put(EngineType.ASSEMBLYAI, assemblyAI.getConfiguration()); // Add Deepgram DeepgramEngine deepgram = new DeepgramEngine(dummyConfig); engines.put(EngineType.DEEPGRAM, deepgram.getConfiguration()); return engines; } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/engine
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/engine/impl/AssemblyAIEngine.java
package ai.driftkit.audio.engine.impl; import com.assemblyai.api.AssemblyAI; import com.assemblyai.api.resources.files.types.UploadedFile; import com.assemblyai.api.resources.transcripts.types.*; import lombok.extern.slf4j.Slf4j; import ai.driftkit.audio.core.config.CoreAudioConfig; import ai.driftkit.audio.engine.AbstractTranscriptionEngine; import ai.driftkit.audio.engine.EngineConfiguration; import ai.driftkit.audio.model.TranscriptionResult; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; /** * AssemblyAI transcription engine implementation. * Supports batch transcription mode only. */ @Slf4j public class AssemblyAIEngine extends AbstractTranscriptionEngine { private static final String ENGINE_NAME = "AssemblyAI"; private AssemblyAI client; public AssemblyAIEngine(CoreAudioConfig config) { super(config); } @Override public String getName() { return ENGINE_NAME; } @Override public boolean supportsBatchMode() { return true; } @Override public boolean supportsStreamingMode() { return false; // AssemblyAI supports real-time streaming, but English only } @Override public void initialize() { String apiKey = config.getAssemblyai().getApiKey(); if (apiKey == null || apiKey.trim().isEmpty()) { throw new IllegalStateException("AssemblyAI API key is not configured"); } this.client = AssemblyAI.builder() .apiKey(apiKey) .build(); log.info("AssemblyAI engine initialized"); } @Override protected CompletableFuture<TranscriptionResult> doTranscribeBatch( byte[] audioData, int sampleRate, String languageCode) { return CompletableFuture.supplyAsync(() -> { try { // Upload audio data directly UploadedFile uploadedFile = client.files().upload(audioData); // Configure transcription String effectiveLanguage = languageCode != null ? languageCode : config.getAssemblyai().getLanguageCode().getValue(); TranscriptOptionalParams params = TranscriptOptionalParams.builder() .languageCode(TranscriptLanguageCode.valueOf(effectiveLanguage.toUpperCase())) .build(); // Submit transcription and wait for completion Transcript transcript = client.transcripts().transcribe(uploadedFile.getUploadUrl(), params); // Build result return buildTranscriptionResult(transcript); } catch (Exception e) { log.error("AssemblyAI transcription failed", e); return TranscriptionResult.builder() .error(true) .errorMessage("Transcription failed: " + e.getMessage()) .timestamp(System.currentTimeMillis()) .build(); } }); } @Override protected StreamingSession createStreamingSession( String sessionId, int sampleRate, String languageCode, Consumer<TranscriptionResult> resultCallback) { throw new UnsupportedOperationException( "AssemblyAI does not support streaming transcription"); } @Override protected void doShutdown() { // AssemblyAI client doesn't require explicit shutdown } @Override public EngineConfiguration getConfiguration() { Map<String, String> requiredConfig = new HashMap<>(); requiredConfig.put("audio.processing.assemblyai.api-key", "AssemblyAI API key"); Map<String, String> optionalConfig = new HashMap<>(); optionalConfig.put("audio.processing.assemblyai.language-code", "Language code (default: en)"); return EngineConfiguration.builder() .engineType(ENGINE_NAME) .requiredConfig(requiredConfig) .optionalConfig(optionalConfig) .processingMode(EngineConfiguration.ProcessingMode.BATCH_ONLY) .supportedFormats(EngineConfiguration.AudioFormat.builder() .supportedSampleRates(new int[]{8000, 16000, 22050, 44100, 48000}) .supportedChannels(new int[]{1, 2}) .supportedBitsPerSample(new int[]{16}) .supportedEncodings(new String[]{"PCM", "WAV", "MP3", "M4A"}) .build()) .requiresConversion(true) .build(); } private TranscriptionResult buildTranscriptionResult(Transcript transcript) { if (transcript.getStatus() == TranscriptStatus.ERROR) { return TranscriptionResult.builder() .error(true) .errorMessage(transcript.getError().orElse("Unknown error")) .timestamp(System.currentTimeMillis()) .build(); } return TranscriptionResult.builder() .text(transcript.getText().orElse("")) .confidence(transcript.getConfidence().orElse(0.0)) .language(transcript.getLanguageCode().map(Object::toString).orElse("unknown")) .timestamp(System.currentTimeMillis()) .error(false) .metadata(buildMetadata(transcript)) .build(); } private Map<String, Object> buildMetadata(Transcript transcript) { Map<String, Object> metadata = new HashMap<>(); metadata.put("transcriptId", transcript.getId()); metadata.put("duration", transcript.getAudioDuration()); metadata.put("words", transcript.getWords()); return metadata; } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/engine
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/engine/impl/DeepgramEngine.java
package ai.driftkit.audio.engine.impl; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import ai.driftkit.audio.core.config.CoreAudioConfig; import ai.driftkit.audio.engine.AbstractTranscriptionEngine; import ai.driftkit.audio.engine.EngineConfiguration; import ai.driftkit.audio.model.TranscriptionResult; import ai.driftkit.audio.model.WordBuffer; import ai.driftkit.audio.model.WordInfo; import ai.driftkit.audio.model.SegmentResult; import ai.driftkit.audio.model.deepgram.DeepgramResponse; import ai.driftkit.audio.model.deepgram.DeepgramAlternative; import ai.driftkit.audio.model.deepgram.DeepgramWord; import okhttp3.*; import okio.ByteString; import org.apache.commons.lang3.StringUtils; import javax.net.ssl.SSLSocketFactory; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; /** * Deepgram transcription engine implementation. * Supports both batch and streaming transcription modes. */ @Slf4j public class DeepgramEngine extends AbstractTranscriptionEngine { private static final String ENGINE_NAME = "Deepgram"; private static final String DEEPGRAM_API_URL = "https://api.deepgram.com/v1/listen"; private static final String DEEPGRAM_WS_URL = "wss://api.deepgram.com/v1/listen"; private OkHttpClient httpClient; private final ObjectMapper objectMapper = new ObjectMapper(); private final ScheduledExecutorService reconnectExecutor = Executors.newSingleThreadScheduledExecutor(); public DeepgramEngine(CoreAudioConfig config) { super(config); } @Override public String getName() { return ENGINE_NAME; } @Override public boolean supportsBatchMode() { return true; } @Override public boolean supportsStreamingMode() { return true; } @Override public void initialize() { String apiKey = config.getDeepgram().getApiKey(); if (apiKey == null || apiKey.trim().isEmpty()) { throw new IllegalStateException("Deepgram API key is not configured"); } this.httpClient = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .build(); log.info("Deepgram engine initialized"); } @Override protected CompletableFuture<TranscriptionResult> doTranscribeBatch( byte[] audioData, int sampleRate, String languageCode) { return CompletableFuture.supplyAsync(() -> { try { String url = buildBatchUrl(sampleRate, languageCode); RequestBody body = RequestBody.create( audioData, MediaType.parse("audio/wav") ); Request request = new Request.Builder() .url(url) .header("Authorization", "Token " + config.getDeepgram().getApiKey()) .header("Content-Type", "audio/wav") .post(body) .build(); try (Response response = httpClient.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("Unexpected response: " + response); } String responseBody = response.body().string(); return parseDeepgramResponse(responseBody); } } catch (Exception e) { log.error("Deepgram batch transcription failed", e); return TranscriptionResult.builder() .error(true) .errorMessage("Transcription failed: " + e.getMessage()) .timestamp(System.currentTimeMillis()) .build(); } }); } @Override protected StreamingSession createStreamingSession( String sessionId, int sampleRate, String languageCode, Consumer<TranscriptionResult> resultCallback) { return new DeepgramStreamingSession(sessionId, sampleRate, languageCode, resultCallback); } @Override protected void doShutdown() { if (httpClient != null) { httpClient.dispatcher().executorService().shutdown(); httpClient.connectionPool().evictAll(); } if (reconnectExecutor != null && !reconnectExecutor.isShutdown()) { reconnectExecutor.shutdown(); } } @Override public EngineConfiguration getConfiguration() { Map<String, String> requiredConfig = new HashMap<>(); requiredConfig.put("audio.processing.deepgram.api-key", "Deepgram API key"); Map<String, String> optionalConfig = new HashMap<>(); optionalConfig.put("audio.processing.deepgram.language", "Language code (default: en)"); optionalConfig.put("audio.processing.deepgram.model", "Model to use (default: nova-2)"); optionalConfig.put("audio.processing.deepgram.punctuate", "Add punctuation (default: true)"); optionalConfig.put("audio.processing.deepgram.interim-results", "Enable interim results for streaming (default: true)"); return EngineConfiguration.builder() .engineType(ENGINE_NAME) .requiredConfig(requiredConfig) .optionalConfig(optionalConfig) .processingMode(EngineConfiguration.ProcessingMode.BOTH) .supportedFormats(EngineConfiguration.AudioFormat.builder() .supportedSampleRates(new int[]{8000, 16000, 24000, 48000}) .supportedChannels(new int[]{1, 2}) .supportedBitsPerSample(new int[]{16}) .supportedEncodings(new String[]{"linear16", "flac", "mulaw", "amr", "opus"}) .build()) .maxStreamingChunkSize(8192) // 8KB chunks .recommendedBufferSizeMs(100) // 100ms buffers .requiresConversion(false) // Deepgram accepts raw PCM .build(); } private String buildBatchUrl(int sampleRate, String languageCode) { StringBuilder url = new StringBuilder(DEEPGRAM_API_URL); url.append("?encoding=linear16"); url.append("&sample_rate=").append(sampleRate); String effectiveLanguage = languageCode != null ? languageCode : config.getDeepgram().getLanguage().getValue(); url.append("&language=").append(effectiveLanguage); url.append("&model=").append(config.getDeepgram().getModel()); url.append("&punctuate=").append(config.getDeepgram().isPunctuate()); return url.toString(); } private String buildStreamingUrl(int sampleRate, String languageCode) { StringBuilder url = new StringBuilder(DEEPGRAM_WS_URL); url.append("?encoding=linear16"); url.append("&sample_rate=").append(sampleRate); String effectiveLanguage = languageCode != null ? languageCode : config.getDeepgram().getLanguage().getValue(); url.append("&language=").append(effectiveLanguage); url.append("&model=").append(config.getDeepgram().getModel()); url.append("&punctuate=").append(config.getDeepgram().isPunctuate()); url.append("&interim_results=").append(config.getDeepgram().isInterimResults()); return url.toString(); } private TranscriptionResult parseDeepgramResponse(String json) { try { DeepgramResponse response = objectMapper.readValue(json, DeepgramResponse.class); // Handle streaming response format (has direct channel) if (response.getChannel() != null) { var channel = response.getChannel(); if (channel.getAlternatives() != null && !channel.getAlternatives().isEmpty()) { var alternative = channel.getAlternatives().get(0); String transcript = alternative.getTranscript(); Double confidence = alternative.getConfidence(); return TranscriptionResult.builder() .text(transcript) .confidence(confidence) .language(response.getLanguage() != null ? response.getLanguage() : "en") .timestamp(System.currentTimeMillis()) .error(false) .metadata(response.toMap()) .build(); } } // Handle batch response format (has results.channels) if (response.getResults() != null && response.getResults().getChannels() != null && !response.getResults().getChannels().isEmpty()) { var channel = response.getResults().getChannels().get(0); if (channel.getAlternatives() != null && !channel.getAlternatives().isEmpty()) { var alternative = channel.getAlternatives().get(0); String transcript = alternative.getTranscript(); Double confidence = alternative.getConfidence(); return TranscriptionResult.builder() .text(transcript) .confidence(confidence) .language(response.getLanguage() != null ? response.getLanguage() : "en") .timestamp(System.currentTimeMillis()) .error(false) .metadata(response.toMap()) .build(); } } return TranscriptionResult.builder() .error(true) .errorMessage("No transcription results found") .timestamp(System.currentTimeMillis()) .build(); } catch (Exception e) { log.error("Failed to parse Deepgram response", e); return TranscriptionResult.builder() .error(true) .errorMessage("Failed to parse response: " + e.getMessage()) .timestamp(System.currentTimeMillis()) .build(); } } /** * WebSocket-based streaming session for Deepgram. */ private class DeepgramStreamingSession implements StreamingSession { private final String sessionId; private final int sampleRate; private final String languageCode; private final Consumer<TranscriptionResult> resultCallback; private WebSocket webSocket; private volatile boolean active = false; private volatile boolean shouldReconnect = true; private final WordBuffer wordBuffer = new WordBuffer(); private final AtomicInteger reconnectAttempts = new AtomicInteger(0); private static final int MAX_RECONNECT_ATTEMPTS = 5; private static final long RECONNECT_DELAY_MS = 1000; private static final long MAX_RECONNECT_DELAY_MS = 30000; DeepgramStreamingSession(String sessionId, int sampleRate, String languageCode, Consumer<TranscriptionResult> resultCallback) { this.sessionId = sessionId; this.sampleRate = sampleRate; this.languageCode = languageCode; this.resultCallback = resultCallback; connect(); } private void connect() { try { String url = buildStreamingUrl(sampleRate, languageCode); Request request = new Request.Builder() .url(url) .header("Authorization", "Token " + config.getDeepgram().getApiKey()) .build(); WebSocketListener listener = new DeepgramWebSocketListener(); webSocket = httpClient.newWebSocket(request, listener); active = true; log.debug("Deepgram streaming session {} started", sessionId); } catch (Exception e) { log.error("Failed to start Deepgram streaming session", e); if (shouldReconnect) { scheduleReconnect(); } else { throw new RuntimeException("Failed to start streaming session", e); } } } private void scheduleReconnect() { int attempts = reconnectAttempts.incrementAndGet(); if (attempts > MAX_RECONNECT_ATTEMPTS) { log.error("Max reconnection attempts ({}) reached for session {}", MAX_RECONNECT_ATTEMPTS, sessionId); active = false; shouldReconnect = false; resultCallback.accept(TranscriptionResult.builder() .error(true) .errorMessage("Max reconnection attempts reached") .timestamp(System.currentTimeMillis()) .build()); return; } long delay = Math.min(RECONNECT_DELAY_MS * (1L << (attempts - 1)), MAX_RECONNECT_DELAY_MS); log.info("Scheduling reconnection attempt {} for session {} in {}ms", attempts, sessionId, delay); reconnectExecutor.schedule(() -> { if (shouldReconnect && !active) { log.info("Attempting to reconnect session {} (attempt {})", sessionId, attempts); connect(); } }, delay, TimeUnit.MILLISECONDS); } private void onConnectionSuccess() { reconnectAttempts.set(0); log.info("Deepgram streaming session {} reconnected successfully", sessionId); } private void onConnectionFailure(Throwable t) { active = false; log.error("Deepgram WebSocket connection failed for session {}: {}", sessionId, t.getMessage()); if (shouldReconnect) { scheduleReconnect(); } else { resultCallback.accept(TranscriptionResult.builder() .error(true) .errorMessage("WebSocket connection failed: " + t.getMessage()) .timestamp(System.currentTimeMillis()) .build()); } } @Override public void sendAudio(byte[] audioData) { if (webSocket != null && active) { webSocket.send(ByteString.of(audioData)); } } @Override public void close() { shouldReconnect = false; active = false; if (webSocket != null) { webSocket.close(1000, "Session closed"); log.debug("Deepgram streaming session {} closed", sessionId); } } @Override public boolean isActive() { return active; } private class DeepgramWebSocketListener extends WebSocketListener { List<String> list = new ArrayList<>(); @Override public void onOpen(WebSocket webSocket, Response response) { log.debug("Deepgram WebSocket opened for session {}", sessionId); onConnectionSuccess(); } @Override public void onMessage(WebSocket webSocket, String text) { try { DeepgramResponse response = objectMapper.readValue(text, DeepgramResponse.class); // Early exit if no channel or alternatives if (response.getChannel() == null || response.getChannel().getAlternatives() == null || response.getChannel().getAlternatives().isEmpty()) { return; } // Find the best alternative (highest confidence) DeepgramAlternative bestAlternative = findBestAlternative(response.getChannel().getAlternatives()); // Convert words and update buffer List<WordInfo> words = convertToWordInfoList(bestAlternative); boolean isFinal = Boolean.TRUE.equals(response.getIsFinal()); SegmentResult segmentResult = wordBuffer.updateWords(words, isFinal); // Create and send result only if we have new content if (StringUtils.isNotBlank(segmentResult.getText())) { TranscriptionResult result = createTranscriptionResult(response, bestAlternative, segmentResult, isFinal); list.add(text); resultCallback.accept(result); } } catch (Exception e) { log.error("Error processing Deepgram message", e); } } private DeepgramAlternative findBestAlternative(List<DeepgramAlternative> alternatives) { DeepgramAlternative best = alternatives.get(0); for (DeepgramAlternative alt : alternatives) { if (alt.getConfidence() == null || best.getConfidence() == null) { continue; } if (alt.getConfidence() > best.getConfidence()) { best = alt; } } return best; } private List<WordInfo> convertToWordInfoList(DeepgramAlternative alternative) { List<WordInfo> words = new ArrayList<>(); if (alternative.getWords() == null) { return words; } for (DeepgramWord word : alternative.getWords()) { words.add(WordInfo.builder() .word(word.getWord()) .punctuatedWord(word.getPunctuatedWord()) .start(word.getStart()) .end(word.getEnd()) .confidence(word.getConfidence()) .language(word.getLanguage()) .build()); } return words; } private TranscriptionResult createTranscriptionResult(DeepgramResponse response, DeepgramAlternative alternative, SegmentResult segmentResult, boolean isFinal) { return TranscriptionResult.builder() .text(alternative.getTranscript()) // Original transcript from this response .mergedTranscript(segmentResult.getText()) // Current segment only (since last final) .words(segmentResult.getWords()) // Words for current segment only .confidence(segmentResult.getConfidence()) .language(response.getLanguage() != null ? response.getLanguage() : "en") .timestamp(System.currentTimeMillis()) .interim(!isFinal) .error(false) .metadata(response.toMap()) .build(); } @Override public void onClosing(WebSocket webSocket, int code, String reason) { webSocket.close(1000, null); active = false; if (shouldReconnect && code != 1000) { log.warn("Deepgram WebSocket closing unexpectedly for session {} with code {}: {}", sessionId, code, reason); scheduleReconnect(); } } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { onConnectionFailure(t); } } } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/AudioAnalysis.java
package ai.driftkit.audio.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Result of audio buffer analysis */ @Data @NoArgsConstructor @AllArgsConstructor public class AudioAnalysis { private boolean isSilent; private double amplitude; /** * Check if this buffer contains voice activity */ public boolean hasVoiceActivity(int voiceThreshold) { return amplitude > voiceThreshold; } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/AudioChunk.java
package ai.driftkit.audio.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Represents a chunk of audio data with metadata */ @Data @NoArgsConstructor @AllArgsConstructor public class AudioChunk { private byte[] data; private long startTime; private long endTime; private String transcription; private boolean endedOnSilence; public AudioChunk(byte[] data, long startTime, long endTime, boolean endedOnSilence) { this.data = data; this.startTime = startTime; this.endTime = endTime; this.endedOnSilence = endedOnSilence; } /** * Get duration in seconds */ public double getDurationSeconds() { return (endTime - startTime) / 1000.0; } public boolean hasTranscription() { return transcription != null && !transcription.trim().isEmpty(); } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/SegmentResult.java
package ai.driftkit.audio.model; import lombok.Data; import lombok.AllArgsConstructor; import java.util.List; /** * Result of a transcription segment update. * Contains only the current segment (since last final result). */ @Data @AllArgsConstructor public class SegmentResult { private String text; private double confidence; private boolean isFinal; private List<WordInfo> words; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/TranscriptionResult.java
package ai.driftkit.audio.model; import lombok.Builder; import lombok.Data; import java.util.List; import java.util.Map; /** * Result of audio transcription */ @Data @Builder public class TranscriptionResult { private String text; private Double confidence; private Long timestamp; private String language; private boolean error; private String errorMessage; private Map<String, Object> metadata; private boolean interim; private List<WordInfo> words; private String mergedTranscript; public static TranscriptionResult success(String text, double confidence, String language) { return TranscriptionResult.builder() .text(text) .confidence(confidence) .language(language) .timestamp(System.currentTimeMillis()) .error(false) .build(); } public static TranscriptionResult error(String errorMessage) { return TranscriptionResult.builder() .error(true) .errorMessage(errorMessage) .timestamp(System.currentTimeMillis()) .build(); } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/WordBuffer.java
package ai.driftkit.audio.model; import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * Buffer for managing and deduplicating words from streaming transcription results. * Handles overlapping word updates and maintains a consistent timeline. */ @Slf4j public class WordBuffer { private final Map<String, WordEntry> wordMap = new ConcurrentHashMap<>(); private final List<WordEntry> currentSegmentWords = new ArrayList<>(); private final Object lock = new Object(); private double lastFinalEndTime = 0.0; /** * Add or update words from a new transcription result. * Handles deduplication and merging of overlapping words. * Returns the current segment transcript (since last final). */ public SegmentResult updateWords(List<WordInfo> newWords, boolean isFinal) { synchronized (lock) { // If this is a final result, first clean up old words if (isFinal) { cleanupOldWords(); } for (WordInfo newWord : newWords) { // Only process words that are after the last final end time if (newWord.getEnd() <= lastFinalEndTime) { continue; } String key = generateWordKey(newWord); WordEntry existing = wordMap.get(key); if (existing != null) { // Update existing word if new version has better confidence or is final if (isFinal || newWord.getConfidence() > existing.getConfidence()) { existing.update(newWord, isFinal); log.trace("Updated word: {} at {}-{} (confidence: {})", newWord.getWord(), newWord.getStart(), newWord.getEnd(), newWord.getConfidence()); } } else { // Add new word WordEntry entry = new WordEntry(newWord, isFinal); wordMap.put(key, entry); insertWordInOrder(entry); log.trace("Added new word: {} at {}-{}", newWord.getWord(), newWord.getStart(), newWord.getEnd()); } } // Clean up overlapping words if this is a final result if (isFinal) { cleanupOverlaps(); // Update final state String currentSegmentText = getCurrentSegmentTranscript(); if (!currentSegmentWords.isEmpty()) { lastFinalEndTime = currentSegmentWords.stream() .mapToDouble(WordEntry::getEnd) .max().orElse(lastFinalEndTime); } return new SegmentResult(currentSegmentText, getOverallConfidence(), true, getCurrentWords()); } else { // Return interim result String currentSegmentText = getCurrentSegmentTranscript(); return new SegmentResult(currentSegmentText, getOverallConfidence(), false, getCurrentWords()); } } } /** * Get the current segment transcript (since last final). */ public String getCurrentSegmentTranscript() { synchronized (lock) { return currentSegmentWords.stream() .map(w -> w.getPunctuatedWord() != null ? w.getPunctuatedWord() : w.getWord()) .collect(Collectors.joining(" ")); } } /** * Get the current segment transcript using smart punctuation spacing. */ public String getCurrentSegmentPunctuatedTranscript() { synchronized (lock) { StringBuilder sb = new StringBuilder(); String lastPunctuation = ""; for (WordEntry word : currentSegmentWords) { String punctuated = word.getPunctuatedWord() != null ? word.getPunctuatedWord() : word.getWord(); // Smart spacing: no space after opening quotes/brackets or before closing punctuation if (!sb.isEmpty() && !lastPunctuation.matches("[(\\[\"'«]") && !punctuated.matches("^[.,;:!?)\\]\"'»].*")) { sb.append(" "); } sb.append(punctuated); // Track last character for smart spacing if (!punctuated.isEmpty()) { lastPunctuation = punctuated.substring(punctuated.length() - 1); } } return sb.toString(); } } /** * Get current segment words in chronological order. */ public List<WordInfo> getCurrentWords() { synchronized (lock) { return currentSegmentWords.stream() .map(WordEntry::toWordInfo) .collect(Collectors.toList()); } } /** * Get the overall confidence of the current segment. */ public double getOverallConfidence() { synchronized (lock) { if (currentSegmentWords.isEmpty()) return 0.0; double sum = currentSegmentWords.stream() .mapToDouble(WordEntry::getConfidence) .sum(); return sum / currentSegmentWords.size(); } } /** * Clear all words from the buffer. */ public void clear() { synchronized (lock) { wordMap.clear(); currentSegmentWords.clear(); lastFinalEndTime = 0.0; } } /** * Clean up words that are before the last final result. */ private void cleanupOldWords() { // Remove words that ended before the last final time currentSegmentWords.removeIf(word -> word.getEnd() <= lastFinalEndTime); wordMap.entrySet().removeIf(entry -> entry.getValue().getEnd() <= lastFinalEndTime); } private String generateWordKey(WordInfo word) { // Key based on approximate time position and word text // This allows for small time adjustments while identifying the same word long timeSlot = Math.round(word.getStart() * 10); // 100ms slots return timeSlot + "_" + word.getWord().toLowerCase(); } private void insertWordInOrder(WordEntry entry) { // Binary search to find insertion point int index = Collections.binarySearch(currentSegmentWords, entry, Comparator.comparing(WordEntry::getStart)); if (index < 0) { index = -index - 1; } currentSegmentWords.add(index, entry); } private void cleanupOverlaps() { // Remove words that significantly overlap with higher confidence words List<WordEntry> toRemove = new ArrayList<>(); for (int i = 0; i < currentSegmentWords.size() - 1; i++) { WordEntry current = currentSegmentWords.get(i); WordEntry next = currentSegmentWords.get(i + 1); // Check for significant overlap if (current.getEnd() > next.getStart() + 0.1) { // 100ms overlap threshold // Keep the word with higher confidence or the final one if (next.isFinal() && !current.isFinal()) { toRemove.add(current); } else if (current.isFinal() && !next.isFinal()) { toRemove.add(next); } else if (next.getConfidence() > current.getConfidence()) { toRemove.add(current); } else { toRemove.add(next); } } } // Remove overlapping words for (WordEntry entry : toRemove) { currentSegmentWords.remove(entry); wordMap.values().removeIf(e -> e.equals(entry)); } } @Data private static class WordEntry { private String word; private String punctuatedWord; private double start; private double end; private double confidence; private String language; private boolean isFinal; private long lastUpdated; WordEntry(WordInfo info, boolean isFinal) { update(info, isFinal); } void update(WordInfo info, boolean isFinal) { this.word = info.getWord(); this.punctuatedWord = info.getPunctuatedWord(); this.start = info.getStart(); this.end = info.getEnd(); this.confidence = info.getConfidence(); this.language = info.getLanguage(); this.isFinal = this.isFinal || isFinal; this.lastUpdated = System.currentTimeMillis(); } WordInfo toWordInfo() { return WordInfo.builder() .word(word) .punctuatedWord(punctuatedWord) .start(start) .end(end) .confidence(confidence) .language(language) .build(); } } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/WordInfo.java
package ai.driftkit.audio.model; import lombok.Builder; import lombok.Data; /** * Represents a single word with timing and confidence information. */ @Data @Builder public class WordInfo { private String word; private String punctuatedWord; private double start; private double end; private double confidence; private String language; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramAlternative.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; @Data public class DeepgramAlternative { @JsonProperty("transcript") private String transcript; @JsonProperty("confidence") private Double confidence; @JsonProperty("words") private List<DeepgramWord> words; @JsonProperty("paragraphs") private DeepgramParagraphs paragraphs; @JsonProperty("entities") private List<DeepgramEntity> entities; @JsonProperty("translations") private List<DeepgramTranslation> translations; @JsonProperty("summaries") private List<DeepgramSummary> summaries; @JsonProperty("languages") private List<String> languages; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramChannel.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; @Data public class DeepgramChannel { @JsonProperty("search") private List<DeepgramSearch> search; @JsonProperty("alternatives") private List<DeepgramAlternative> alternatives; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramEntity.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class DeepgramEntity { @JsonProperty("label") private String label; @JsonProperty("value") private String value; @JsonProperty("confidence") private Double confidence; @JsonProperty("start") private Double start; @JsonProperty("end") private Double end; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramMetadata.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class DeepgramMetadata { @JsonProperty("transaction_key") private String transactionKey; @JsonProperty("request_id") private String requestId; @JsonProperty("sha256") private String sha256; @JsonProperty("created") private String created; @JsonProperty("duration") private Double duration; @JsonProperty("channels") private Integer channels; @JsonProperty("models") private String[] models; @JsonProperty("model_info") private Object modelInfo; @JsonProperty("model_uuid") private String modelUuid; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramParagraph.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; @Data public class DeepgramParagraph { @JsonProperty("sentences") private List<DeepgramSentence> sentences; @JsonProperty("start") private Double start; @JsonProperty("end") private Double end; @JsonProperty("num_words") private Integer numWords; @JsonProperty("speaker") private Integer speaker; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramParagraphs.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class DeepgramParagraphs { @JsonProperty("transcript") private String transcript; @JsonProperty("paragraphs") private DeepgramParagraph[] paragraphs; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramResponse.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; import java.util.Map; @Data public class DeepgramResponse { @JsonProperty("metadata") private DeepgramMetadata metadata; @JsonProperty("results") private DeepgramResults results; @JsonProperty("language") private String language; @JsonProperty("is_final") private Boolean isFinal; @JsonProperty("speech_final") private Boolean speechFinal; @JsonProperty("channel_index") private List<Integer> channelIndex; @JsonProperty("duration") private Double duration; @JsonProperty("start") private Double start; @JsonProperty("type") private String type; @JsonProperty("channel") private DeepgramChannel channel; @JsonProperty("from_finalize") private Boolean fromFinalize; public Map<String, Object> toMap() { return Map.of( "metadata", metadata, "results", results == null ? "" : results, "language", language != null ? language : "en", "is_final", isFinal != null ? isFinal : false, "speech_final", speechFinal != null ? speechFinal : false, "channel_index", channelIndex, "duration", duration, "start", start, "type", type ); } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramResults.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; @Data public class DeepgramResults { @JsonProperty("channels") private List<DeepgramChannel> channels; @JsonProperty("utterances") private List<DeepgramUtterance> utterances; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramSearch.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class DeepgramSearch { @JsonProperty("query") private String query; @JsonProperty("hits") private DeepgramSearchHit[] hits; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramSearchHit.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class DeepgramSearchHit { @JsonProperty("confidence") private Double confidence; @JsonProperty("start") private Double start; @JsonProperty("end") private Double end; @JsonProperty("snippet") private String snippet; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramSentence.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class DeepgramSentence { @JsonProperty("text") private String text; @JsonProperty("start") private Double start; @JsonProperty("end") private Double end; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramSummary.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class DeepgramSummary { @JsonProperty("summary") private String summary; @JsonProperty("start") private Double start; @JsonProperty("end") private Double end; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramTranslation.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class DeepgramTranslation { @JsonProperty("language") private String language; @JsonProperty("translation") private String translation; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramUtterance.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; @Data public class DeepgramUtterance { @JsonProperty("start") private Double start; @JsonProperty("end") private Double end; @JsonProperty("confidence") private Double confidence; @JsonProperty("channel") private Integer channel; @JsonProperty("transcript") private String transcript; @JsonProperty("words") private List<DeepgramWord> words; @JsonProperty("speaker") private Integer speaker; @JsonProperty("id") private String id; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/model/deepgram/DeepgramWord.java
package ai.driftkit.audio.model.deepgram; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class DeepgramWord { @JsonProperty("word") private String word; @JsonProperty("start") private Double start; @JsonProperty("end") private Double end; @JsonProperty("confidence") private Double confidence; @JsonProperty("punctuated_word") private String punctuatedWord; @JsonProperty("speaker") private Integer speaker; @JsonProperty("language") private String language; }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/processor/AudioAnalyzer.java
package ai.driftkit.audio.processor; import ai.driftkit.audio.core.config.CoreAudioConfig; import ai.driftkit.audio.model.AudioAnalysis; /** * Service for analyzing audio buffers and detecting voice activity */ public class AudioAnalyzer { private final CoreAudioConfig config; // Adaptive sensitivity fields private volatile long lastVoiceDetectedTime = System.currentTimeMillis(); private volatile boolean sensitivityBoosted = false; private volatile int currentSilenceThreshold; private volatile int currentVoiceThreshold; // Silence reset timer fields private volatile long lastSoundDetectedTime = System.currentTimeMillis(); private volatile int dynamicSilenceThreshold = -1; private volatile boolean timerRunning = false; private final Object thresholdLock = new Object(); // Calibration support private double backgroundNoiseLevel = 0; private boolean isCalibrated = false; public AudioAnalyzer(CoreAudioConfig config) { this.config = config; } /** * Calibrate background noise level * @param samples Array of AudioAnalysis samples from calibration phase * @return Adjusted thresholds based on background noise */ public CalibrationResult calibrateBackgroundNoise(AudioAnalysis[] samples) { // Default thresholds based on VAD config double defaultSilenceThreshold = config.getVad().getThreshold() * 100; // Convert to 0-100 scale double defaultVoiceThreshold = defaultSilenceThreshold * 2; if (samples == null || samples.length == 0) { return new CalibrationResult((int)defaultSilenceThreshold, (int)defaultVoiceThreshold); } // Calculate average background noise double totalAmplitude = 0; for (AudioAnalysis sample : samples) { totalAmplitude += sample.getAmplitude(); } backgroundNoiseLevel = totalAmplitude / samples.length; // Calculate adjusted thresholds int adjustedSilenceThreshold = (int)(backgroundNoiseLevel * 150); // 1.5x background int adjustedVoiceThreshold = (int)(backgroundNoiseLevel * 250); // 2.5x background // Use adjusted thresholds if they're higher than configured int finalSilenceThreshold = Math.max(adjustedSilenceThreshold, (int)defaultSilenceThreshold); int finalVoiceThreshold = Math.max(adjustedVoiceThreshold, (int)defaultVoiceThreshold); // Update current thresholds currentSilenceThreshold = finalSilenceThreshold; currentVoiceThreshold = finalVoiceThreshold; isCalibrated = true; return new CalibrationResult(finalSilenceThreshold, finalVoiceThreshold, backgroundNoiseLevel); } /** * Analyze audio buffer for voice activity and silence detection */ public AudioAnalysis analyzeBuffer(byte[] buffer, int length) { // Convert bytes to 16-bit samples and calculate RMS (Root Mean Square) long sum = 0; int sampleCount = length / 2; // 16-bit samples for (int i = 0; i < length - 1; i += 2) { // Convert two bytes to a 16-bit sample (big-endian) short sample = (short)((buffer[i] << 8) | (buffer[i + 1] & 0xFF)); sum += sample * sample; } double rms = Math.sqrt((double)sum / sampleCount); boolean isSilent = rms < getCurrentSilenceThreshold(); // Update sound detection time for silence reset timer updateSoundDetectionTime(rms); return new AudioAnalysis(isSilent, rms); } /** * Analyze entire chunk for voice activity */ public boolean analyzeChunkForVoice(byte[] chunkData) { // Analyze the entire chunk in segments to detect voice activity int segmentSize = config.getSampleRate() * 2; // 1 second segments int numSegments = chunkData.length / segmentSize; int voiceSegments = 0; double maxSegmentAmplitude = 0; for (int i = 0; i < numSegments; i++) { int start = i * segmentSize; int length = Math.min(segmentSize, chunkData.length - start); if (length > 0) { byte[] segment = new byte[length]; System.arraycopy(chunkData, start, segment, 0, length); AudioAnalysis analysis = analyzeBuffer(segment, length); if (analysis.getAmplitude() > maxSegmentAmplitude) { maxSegmentAmplitude = analysis.getAmplitude(); } if (analysis.getAmplitude() > getCurrentVoiceThreshold()) { voiceSegments++; } } } // Calculate average amplitude across segments double avgAmplitude = 0; if (numSegments > 0) { double totalAmplitude = 0; for (int i = 0; i < numSegments; i++) { int start = i * segmentSize; int length = Math.min(segmentSize, chunkData.length - start); if (length > 0) { byte[] segment = new byte[length]; System.arraycopy(chunkData, start, segment, 0, length); AudioAnalysis analysis = analyzeBuffer(segment, length); totalAmplitude += analysis.getAmplitude(); } } avgAmplitude = totalAmplitude / numSegments; } // Consider it has voice if: // 1. At least one segment has voice activity, OR // 2. Maximum amplitude is above 70% of threshold (more lenient) // 3. Average amplitude across segments is reasonably high boolean hasVoice = voiceSegments > 0 || maxSegmentAmplitude > (getCurrentVoiceThreshold() * 0.7) || avgAmplitude > (getCurrentVoiceThreshold() * 0.5); return hasVoice; } /** * Initialize adaptive sensitivity settings */ public void initializeAdaptiveSensitivity() { int baseThreshold = (int)(config.getVad().getThreshold() * 100); currentSilenceThreshold = baseThreshold; currentVoiceThreshold = baseThreshold * 2; lastVoiceDetectedTime = System.currentTimeMillis(); sensitivityBoosted = false; } /** * Update adaptive sensitivity based on voice activity */ public void updateAdaptiveSensitivity(boolean voiceDetected) { long currentTime = System.currentTimeMillis(); if (voiceDetected) { lastVoiceDetectedTime = currentTime; if (sensitivityBoosted) { // Reset to normal sensitivity when voice is detected int baseThreshold = (int)(config.getVad().getThreshold() * 100); currentSilenceThreshold = baseThreshold; currentVoiceThreshold = baseThreshold * 2; sensitivityBoosted = false; } } else { // Check if we should boost sensitivity after 5 seconds of silence long silenceDuration = currentTime - lastVoiceDetectedTime; if (!sensitivityBoosted && silenceDuration > 5000) { currentSilenceThreshold = currentSilenceThreshold / 2; currentVoiceThreshold = currentVoiceThreshold / 2; sensitivityBoosted = true; } } } /** * Get current silence threshold (may be adapted) */ public int getCurrentSilenceThreshold() { return currentSilenceThreshold > 0 ? currentSilenceThreshold : (int)(config.getVad().getThreshold() * 100); } /** * Get current voice activity threshold (may be adapted) */ public int getCurrentVoiceThreshold() { return currentVoiceThreshold > 0 ? currentVoiceThreshold : (int)(config.getVad().getThreshold() * 200); } /** * Update last sound detected time when analyzing audio */ private void updateSoundDetectionTime(double amplitude) { // If sound is detected (not silence), update the timer if (amplitude > getCurrentSilenceThreshold()) { lastSoundDetectedTime = System.currentTimeMillis(); } } /** * Set dynamic silence threshold (for background noise adaptation) */ public void setDynamicSilenceThreshold(int threshold) { this.currentSilenceThreshold = threshold; } /** * Set dynamic voice threshold (for background noise adaptation) */ public void setDynamicVoiceThreshold(int threshold) { this.currentVoiceThreshold = threshold; } /** * Decrease silence threshold and start 15-second timer to reset * @return new threshold value */ public int decreaseSilenceThreshold() { synchronized (thresholdLock) { // Set to a very low threshold int newThreshold = 15; dynamicSilenceThreshold = newThreshold; currentSilenceThreshold = newThreshold; // Reset the timer lastSoundDetectedTime = System.currentTimeMillis(); // Start timer thread if not already running startSilenceResetTimer(); return newThreshold; } } /** * Start a timer that resets silence threshold after 15 seconds of silence */ private void startSilenceResetTimer() { if (timerRunning) { return; // Timer already running } timerRunning = true; new Thread(() -> { while (timerRunning) { try { Thread.sleep(1000); // Check every second long currentTime = System.currentTimeMillis(); long silenceDuration = currentTime - lastSoundDetectedTime; // Check if 15 seconds of silence have passed if (silenceDuration >= 15000) { synchronized (thresholdLock) { dynamicSilenceThreshold = 0; currentSilenceThreshold = 0; timerRunning = false; break; } } } catch (InterruptedException e) { break; } } timerRunning = false; }).start(); } /** * Reset all thresholds to default values */ public void resetThresholds() { synchronized (thresholdLock) { int baseThreshold = (int)(config.getVad().getThreshold() * 100); currentSilenceThreshold = baseThreshold; currentVoiceThreshold = baseThreshold * 2; dynamicSilenceThreshold = -1; sensitivityBoosted = false; isCalibrated = false; timerRunning = false; } } /** * Get current configuration state for debugging */ public String getDebugInfo() { return String.format("AudioAnalyzer Debug Info:\n" + " Background Noise: %.1f\n" + " Current Silence Threshold: %d\n" + " Current Voice Threshold: %d\n" + " Is Calibrated: %b\n" + " Sensitivity Boosted: %b\n" + " Dynamic Threshold: %d\n" + " Timer Running: %b", backgroundNoiseLevel, getCurrentSilenceThreshold(), getCurrentVoiceThreshold(), isCalibrated, sensitivityBoosted, dynamicSilenceThreshold, timerRunning ); } /** * Calibration result class */ public static class CalibrationResult { private final int silenceThreshold; private final int voiceThreshold; private final double backgroundNoise; public CalibrationResult(int silenceThreshold, int voiceThreshold) { this(silenceThreshold, voiceThreshold, 0); } public CalibrationResult(int silenceThreshold, int voiceThreshold, double backgroundNoise) { this.silenceThreshold = silenceThreshold; this.voiceThreshold = voiceThreshold; this.backgroundNoise = backgroundNoise; } public int getSilenceThreshold() { return silenceThreshold; } public int getVoiceThreshold() { return voiceThreshold; } public double getBackgroundNoise() { return backgroundNoise; } } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/processor/BatchAudioProcessor.java
package ai.driftkit.audio.processor; import ai.driftkit.audio.converter.AudioConverter; import ai.driftkit.audio.core.AudioFormatType; import ai.driftkit.audio.core.config.CoreAudioConfig; import lombok.extern.slf4j.Slf4j; import ai.driftkit.audio.engine.TranscriptionEngine; import ai.driftkit.audio.model.AudioAnalysis; import ai.driftkit.audio.model.TranscriptionResult; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; /** * Processor for batch mode audio transcription. * Accumulates audio chunks based on VAD and sends complete segments for transcription. */ @Slf4j public class BatchAudioProcessor { private final String sessionId; private final CoreAudioConfig config; private final AudioAnalyzer audioAnalyzer; private final AudioConverter audioConverter; private final TranscriptionEngine engine; private final Consumer<TranscriptionResult> resultCallback; private final ByteArrayOutputStream audioBuffer = new ByteArrayOutputStream(); private final AtomicBoolean isProcessing = new AtomicBoolean(true); private final AtomicLong lastSpeechTime = new AtomicLong(0); private final AtomicLong totalChunksProcessed = new AtomicLong(0); private boolean inSpeechSegment = false; private long segmentStartTime = 0; public BatchAudioProcessor( String sessionId, CoreAudioConfig config, AudioAnalyzer audioAnalyzer, AudioConverter audioConverter, TranscriptionEngine engine, Consumer<TranscriptionResult> resultCallback) { this.sessionId = sessionId; this.config = config; this.audioAnalyzer = audioAnalyzer; this.audioConverter = audioConverter; this.engine = engine; this.resultCallback = resultCallback; } /** * Process an audio chunk. */ public void processAudioChunk(byte[] audioData) { if (!isProcessing.get()) { log.warn("Processor is stopped, ignoring audio chunk for session {}", sessionId); return; } totalChunksProcessed.incrementAndGet(); // Analyze audio for voice activity AudioAnalysis analysis = audioAnalyzer.analyzeBuffer(audioData, audioData.length); if (!analysis.isSilent()) { handleSpeechDetected(audioData); } else { handleSilenceDetected(); } // Debug output if enabled if (config.getDebug().isEnabled()) { saveDebugAudio(audioData); } } private void handleSpeechDetected(byte[] audioData) { lastSpeechTime.set(System.currentTimeMillis()); if (!inSpeechSegment) { // Start new speech segment inSpeechSegment = true; segmentStartTime = System.currentTimeMillis(); log.debug("Speech started in session {}", sessionId); } // Add audio to buffer try { audioBuffer.write(audioData); } catch (IOException e) { log.error("Failed to buffer audio data", e); } } private void handleSilenceDetected() { if (inSpeechSegment) { long silenceDuration = System.currentTimeMillis() - lastSpeechTime.get(); if (silenceDuration >= config.getVad().getSilenceDurationMs()) { // End of speech segment detected finalizeSpeechSegment(); } } } private void finalizeSpeechSegment() { inSpeechSegment = false; byte[] audioData = audioBuffer.toByteArray(); audioBuffer.reset(); long segmentDuration = System.currentTimeMillis() - segmentStartTime; log.debug("Speech segment ended in session {} after {}ms", sessionId, segmentDuration); // Check minimum duration if (segmentDuration < config.getMinChunkDurationSeconds() * 1000) { log.debug("Segment too short ({}ms), discarding", segmentDuration); return; } // Convert audio if needed byte[] processedAudio = audioData; if (engine.getConfiguration().isRequiresConversion()) { try { processedAudio = audioConverter.convertToFormat( audioData, config.getSampleRate(), AudioFormatType.WAV ); } catch (Exception e) { log.error("Failed to convert audio", e); return; } } // Send for transcription final byte[] finalAudio = processedAudio; engine.transcribeBatch( finalAudio, config.getSampleRate(), getLanguageCode() ).thenAccept(result -> { if (resultCallback != null) { resultCallback.accept(result); } }).exceptionally(throwable -> { log.error("Transcription failed for session {}", sessionId, throwable); if (resultCallback != null) { resultCallback.accept(TranscriptionResult.builder() .error(true) .errorMessage("Transcription failed: " + throwable.getMessage()) .timestamp(System.currentTimeMillis()) .build()); } return null; }); } /** * Force finalize any pending audio. */ public void flush() { if (audioBuffer.size() > 0) { finalizeSpeechSegment(); } } /** * Close this processor. */ public void close() { isProcessing.set(false); flush(); log.info("Batch processor closed for session {} after processing {} chunks", sessionId, totalChunksProcessed.get()); } private String getLanguageCode() { switch (config.getEngine()) { case ASSEMBLYAI: return config.getAssemblyai().getLanguageCode().getValue(); case DEEPGRAM: return config.getDeepgram().getLanguage().getValue(); default: return "en"; } } private void saveDebugAudio(byte[] audioData) { try { String filename = String.format("%s/session_%s_chunk_%d.raw", config.getDebug().getOutputPath(), sessionId, totalChunksProcessed.get()); File file = new File(filename); file.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(audioData); } } catch (IOException e) { log.error("Failed to save debug audio", e); } } }
0
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-core/1.0.1/ai/driftkit/audio/util/Retrier.java
package ai.driftkit.audio.util; import java.util.concurrent.Callable; import java.util.function.Consumer; /** * Utility class for retrying operations with exponential backoff */ public class Retrier { private static final int DEFAULT_TRIALS = 3; private static final int DEFAULT_DELAY = 3000; private Retrier() { } public static void retry(Runnable runnable) throws Exception { retry(runnable, 3L); } public static <R> R retry(Callable<R> callable) throws Exception { return retry(callable, 3L); } public static void retry(Runnable runnable, long delay) throws Exception { retry(runnable, 3, delay / 3L, 1); } public static <R> R retry(Callable<R> callable, long delay) throws Exception { return retry(callable, 3, delay / 3L, 1); } public static void retry(Runnable runnable, int trials, long delay) throws Exception { retry(runnable, trials, delay, 1); } public static <R> R retry(Callable<R> callable, int trials, long delay) throws Exception { return retry(callable, trials, delay, 1); } public static void retryQuietly(Runnable runnable, Consumer<Exception> log) { try { retry(runnable, 3L); } catch (Exception e) { log.accept(e); } } public static <R> R retryQuietly(Callable<R> callable, Consumer<Exception> log) { try { return retry(callable, 3000L); } catch (Exception e) { log.accept(e); return null; } } public static void retryQuietly(Runnable runnable, Consumer<Exception> log, int trials, long delay, int multiplier) { try { retry(runnable, trials, delay, multiplier); } catch (Exception e) { log.accept(e); } } public static <R> R retryQuietly(Callable<R> callable, Consumer<Exception> log, int trials, long delay, int multiplier) { try { return retry(callable, trials, delay, multiplier); } catch (Exception e) { log.accept(e); return null; } } public static <R> R retry(Callable<R> callable, int trials, long delay, int multiplier) throws Exception { for(int trial = 0; trial < trials; delay *= (long)multiplier) { ++trial; try { return callable.call(); } catch (Exception e) { if (trial >= trials) { throw e; } Thread.sleep(delay); } } return null; } public static void retry(Runnable runnable, int trials, long delay, int multiplier) throws Exception { for(int trial = 0; trial < trials; delay *= (long)multiplier) { ++trial; try { runnable.run(); return; } catch (Exception e) { if (trial >= trials) { throw e; } Thread.sleep(delay); } } } }
0
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio/AutoConfiguration.java
package ai.driftkit.audio; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import ai.driftkit.audio.config.AudioProcessingConfig; /** * Auto-configuration for audio processing library */ @Configuration @ComponentScan(basePackages = "ai.driftkit.audio") @EnableConfigurationProperties(AudioProcessingConfig.class) public class AutoConfiguration { }
0
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio/autoconfigure/AutoConfiguration.java
package ai.driftkit.audio.autoconfigure; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import ai.driftkit.audio.config.AudioProcessingConfig; /** * Auto-configuration for audio processing library */ @Configuration @ComponentScan(basePackages = "ai.driftkit.audio") @EnableConfigurationProperties(AudioProcessingConfig.class) public class AutoConfiguration { }
0
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio/config/AudioProcessingConfig.java
package ai.driftkit.audio.config; import ai.driftkit.audio.core.config.CoreAudioConfig; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Configuration properties for audio processing */ @Data @ConfigurationProperties(prefix = "audio.processing") public class AudioProcessingConfig extends CoreAudioConfig { }
0
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio/engine/SpringTranscriptionEngineFactory.java
package ai.driftkit.audio.engine; import ai.driftkit.audio.config.AudioProcessingConfig; import ai.driftkit.audio.core.config.CoreAudioConfig; import ai.driftkit.audio.core.config.EngineType; import ai.driftkit.audio.engine.impl.AssemblyAIEngine; import ai.driftkit.audio.engine.impl.DeepgramEngine; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; /** * Factory for creating transcription engine instances based on configuration. */ @Slf4j @Component public class SpringTranscriptionEngineFactory extends TranscriptionEngineFactory { public SpringTranscriptionEngineFactory(CoreAudioConfig config) { super(config); } }
0
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio/service/AudioSessionManager.java
package ai.driftkit.audio.service; import ai.driftkit.audio.converter.AudioConverter; import ai.driftkit.audio.processor.AudioAnalyzer; import lombok.extern.slf4j.Slf4j; import ai.driftkit.audio.config.AudioProcessingConfig; import ai.driftkit.audio.engine.TranscriptionEngine; import ai.driftkit.audio.engine.SpringTranscriptionEngineFactory; import ai.driftkit.audio.model.TranscriptionResult; import org.springframework.beans.factory.DisposableBean; import org.springframework.stereotype.Service; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Consumer; /** * Audio session manager that supports multiple transcription engines * and both batch and streaming processing modes. */ @Slf4j @Service public class AudioSessionManager implements DisposableBean { private final AudioProcessingConfig config; private final TranscriptionEngine engine; private final AudioConverter audioConverter; // For batch mode processing private final ConcurrentMap<String, BatchAudioProcessor> batchProcessors = new ConcurrentHashMap<>(); // For streaming mode - callbacks are managed by the engine private final ConcurrentMap<String, Consumer<TranscriptionResult>> streamingCallbacks = new ConcurrentHashMap<>(); public AudioSessionManager( AudioProcessingConfig config, SpringTranscriptionEngineFactory engineFactory, AudioConverter audioConverter ) { this.config = config; this.audioConverter = audioConverter; // Create engine based on configuration this.engine = engineFactory.createEngine(); log.info("Enhanced audio session manager initialized with {} engine in {} mode", engine.getName(), config.getProcessingMode()); } /** * Create a new audio processing session. * * @param sessionId Unique session identifier * @param resultCallback Callback for transcription results */ public void createSession(String sessionId, Consumer<TranscriptionResult> resultCallback) { if (hasSession(sessionId)) { throw new IllegalArgumentException("Session already exists: " + sessionId); } switch (config.getProcessingMode()) { case STREAMING: // For streaming mode, start a streaming session with the engine streamingCallbacks.put(sessionId, resultCallback); engine.startStreamingSession( sessionId, config.getSampleRate(), getLanguageCode(), resultCallback ); log.debug("Created streaming session: {}", sessionId); break; case BATCH: // For batch mode, create a batch processor with its own AudioAnalyzer AudioAnalyzer sessionAnalyzer = new AudioAnalyzer(config); BatchAudioProcessor processor = new BatchAudioProcessor( sessionId, config, sessionAnalyzer, audioConverter, engine, resultCallback); batchProcessors.put(sessionId, processor); log.debug("Created batch session: {}", sessionId); break; } } /** * Process audio chunk for a session. * * @param sessionId Session identifier * @param audioData Audio data to process */ public void processAudioChunk(String sessionId, byte[] audioData) { switch (config.getProcessingMode()) { case STREAMING: // For streaming mode, send directly to engine engine.sendStreamingAudio(sessionId, audioData); break; case BATCH: // For batch mode, use the batch processor BatchAudioProcessor processor = batchProcessors.get(sessionId); if (processor == null) { throw new IllegalArgumentException("No active session found: " + sessionId); } processor.processAudioChunk(audioData); break; } } /** * Check if a session exists. * * @param sessionId Session identifier * @return true if session exists */ public boolean hasSession(String sessionId) { return batchProcessors.containsKey(sessionId) || engine.isStreamingSessionActive(sessionId); } /** * Close a session. * * @param sessionId Session identifier */ public void closeSession(String sessionId) { // Close streaming session if exists if (engine.isStreamingSessionActive(sessionId)) { engine.stopStreamingSession(sessionId); streamingCallbacks.remove(sessionId); log.debug("Closed streaming session: {}", sessionId); } // Close batch processor if exists BatchAudioProcessor processor = batchProcessors.remove(sessionId); if (processor != null) { processor.close(); log.debug("Closed batch session: {}", sessionId); } } /** * Get all active session IDs. * * @return Set of active session IDs */ public Set<String> getActiveSessions() { Set<String> sessions = new java.util.HashSet<>(); sessions.addAll(batchProcessors.keySet()); sessions.addAll(streamingCallbacks.keySet()); return sessions; } /** * Close all active sessions. */ public void closeAllSessions() { // Close all batch sessions batchProcessors.forEach((id, processor) -> processor.close()); batchProcessors.clear(); // Close all streaming sessions streamingCallbacks.keySet().forEach(engine::stopStreamingSession); streamingCallbacks.clear(); log.info("All audio sessions closed"); } @Override public void destroy() { closeAllSessions(); engine.shutdown(); log.info("Enhanced audio session manager shut down"); } private String getLanguageCode() { // Get language code based on engine type switch (config.getEngine()) { case ASSEMBLYAI: return config.getAssemblyai().getLanguageCode().getValue(); case DEEPGRAM: return config.getDeepgram().getLanguage().getValue(); default: return "en"; // Default } } /** * Get session statistics (placeholder for future implementation). */ public SessionStats getSessionStats(String sessionId) { // TODO: Implement session statistics return new SessionStats(); } public static class SessionStats { // Placeholder for session statistics private long chunksProcessed; private long bytesProcessed; private long transcriptionsReceived; // Getters/setters would be here } }
0
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio/service/BatchAudioProcessor.java
package ai.driftkit.audio.service; import ai.driftkit.audio.converter.AudioConverter; import ai.driftkit.audio.core.AudioFormatType; import ai.driftkit.audio.processor.AudioAnalyzer; import lombok.extern.slf4j.Slf4j; import ai.driftkit.audio.config.AudioProcessingConfig; import ai.driftkit.audio.engine.TranscriptionEngine; import ai.driftkit.audio.model.AudioAnalysis; import ai.driftkit.audio.model.TranscriptionResult; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; /** * Processor for batch mode audio transcription. * Accumulates audio chunks based on VAD and sends complete segments for transcription. */ @Slf4j public class BatchAudioProcessor { private final String sessionId; private final AudioProcessingConfig config; private final AudioAnalyzer audioAnalyzer; private final AudioConverter audioConverter; private final TranscriptionEngine engine; private final Consumer<TranscriptionResult> resultCallback; private final ByteArrayOutputStream audioBuffer = new ByteArrayOutputStream(); private final AtomicBoolean isProcessing = new AtomicBoolean(true); private final AtomicLong lastSpeechTime = new AtomicLong(0); private final AtomicLong totalChunksProcessed = new AtomicLong(0); private boolean inSpeechSegment = false; private long segmentStartTime = 0; public BatchAudioProcessor( String sessionId, AudioProcessingConfig config, AudioAnalyzer audioAnalyzer, AudioConverter audioConverter, TranscriptionEngine engine, Consumer<TranscriptionResult> resultCallback) { this.sessionId = sessionId; this.config = config; this.audioAnalyzer = audioAnalyzer; this.audioConverter = audioConverter; this.engine = engine; this.resultCallback = resultCallback; } /** * Process an audio chunk. */ public void processAudioChunk(byte[] audioData) { if (!isProcessing.get()) { log.warn("Processor is stopped, ignoring audio chunk for session {}", sessionId); return; } totalChunksProcessed.incrementAndGet(); // Analyze audio for voice activity AudioAnalysis analysis = audioAnalyzer.analyzeBuffer(audioData, audioData.length); if (!analysis.isSilent()) { handleSpeechDetected(audioData); } else { handleSilenceDetected(); } // Debug output if enabled if (config.getDebug().isEnabled()) { saveDebugAudio(audioData); } } private void handleSpeechDetected(byte[] audioData) { lastSpeechTime.set(System.currentTimeMillis()); if (!inSpeechSegment) { // Start new speech segment inSpeechSegment = true; segmentStartTime = System.currentTimeMillis(); log.debug("Speech started in session {}", sessionId); } // Add audio to buffer try { audioBuffer.write(audioData); } catch (IOException e) { log.error("Failed to buffer audio data", e); } } private void handleSilenceDetected() { if (inSpeechSegment) { long silenceDuration = System.currentTimeMillis() - lastSpeechTime.get(); if (silenceDuration >= config.getVad().getSilenceDurationMs()) { // End of speech segment detected finalizeSpeechSegment(); } } } private void finalizeSpeechSegment() { inSpeechSegment = false; byte[] audioData = audioBuffer.toByteArray(); audioBuffer.reset(); long segmentDuration = System.currentTimeMillis() - segmentStartTime; log.debug("Speech segment ended in session {} after {}ms", sessionId, segmentDuration); // Check minimum duration if (segmentDuration < config.getMinChunkDurationSeconds() * 1000) { log.debug("Segment too short ({}ms), discarding", segmentDuration); return; } // Convert audio if needed byte[] processedAudio = audioData; if (engine.getConfiguration().isRequiresConversion()) { try { processedAudio = audioConverter.convertToFormat( audioData, config.getSampleRate(), AudioFormatType.WAV ); } catch (Exception e) { log.error("Failed to convert audio", e); return; } } // Send for transcription final byte[] finalAudio = processedAudio; engine.transcribeBatch( finalAudio, config.getSampleRate(), getLanguageCode() ).thenAccept(result -> { if (resultCallback != null) { resultCallback.accept(result); } }).exceptionally(throwable -> { log.error("Transcription failed for session {}", sessionId, throwable); if (resultCallback != null) { resultCallback.accept(TranscriptionResult.builder() .error(true) .errorMessage("Transcription failed: " + throwable.getMessage()) .timestamp(System.currentTimeMillis()) .build()); } return null; }); } /** * Force finalize any pending audio. */ public void flush() { if (audioBuffer.size() > 0) { finalizeSpeechSegment(); } } /** * Close this processor. */ public void close() { isProcessing.set(false); flush(); log.info("Batch processor closed for session {} after processing {} chunks", sessionId, totalChunksProcessed.get()); } private String getLanguageCode() { switch (config.getEngine()) { case ASSEMBLYAI: return config.getAssemblyai().getLanguageCode().getValue(); case DEEPGRAM: return config.getDeepgram().getLanguage().getValue(); default: return "en"; } } private void saveDebugAudio(byte[] audioData) { try { String filename = String.format("%s/session_%s_chunk_%d.raw", config.getDebug().getOutputPath(), sessionId, totalChunksProcessed.get()); File file = new File(filename); file.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(audioData); } } catch (IOException e) { log.error("Failed to save debug audio", e); } } }
0
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio/service/SpringAudioConverter.java
package ai.driftkit.audio.service; import ai.driftkit.audio.converter.AudioConverter; import ai.driftkit.audio.core.config.CoreAudioConfig; import lombok.extern.slf4j.Slf4j; import ai.driftkit.audio.config.AudioProcessingConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Service for converting audio formats using Java libraries and FFmpeg fallback */ @Slf4j @Service public class SpringAudioConverter extends AudioConverter { @Autowired public SpringAudioConverter(CoreAudioConfig config) { super(config); } }
0
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio
java-sources/ai/driftkit/audio-processing-spring-boot-starter/1.0.1/ai/driftkit/audio/service/SpringAudioSessionManager.java
package ai.driftkit.audio.service; import ai.driftkit.audio.config.AudioProcessingConfig; import ai.driftkit.audio.converter.AudioConverter; import ai.driftkit.audio.core.AudioSessionManager; import ai.driftkit.audio.engine.TranscriptionEngineFactory; import ai.driftkit.audio.model.TranscriptionResult; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.function.Consumer; /** * Spring wrapper for core AudioSessionManager */ @Slf4j @Service public class SpringAudioSessionManager implements DisposableBean { private final AudioSessionManager sessionManager; @Autowired public SpringAudioSessionManager( AudioProcessingConfig config, TranscriptionEngineFactory engineFactory, AudioConverter audioConverter ) { this.sessionManager = new AudioSessionManager(config, engineFactory, audioConverter); } // Delegate all methods to core implementation public void createSession(String sessionId, Consumer<TranscriptionResult> callback) { sessionManager.createSession(sessionId, callback); } public void processAudioChunk(String sessionId, byte[] audioData) { sessionManager.processAudioChunk(sessionId, audioData); } public void closeSession(String sessionId) { sessionManager.closeSession(sessionId); } public boolean hasActiveSession(String sessionId) { return sessionManager.getActiveSessions().contains(sessionId); } public void closeAllSessions() { sessionManager.closeAllSessions(); } @Override public void destroy() { log.info("Shutting down Spring Audio Session Manager"); sessionManager.closeAllSessions(); } }
0
java-sources/ai/driftkit/driftkit-ai-audio/1.0.0/ai/driftkit/audio
java-sources/ai/driftkit/driftkit-ai-audio/1.0.0/ai/driftkit/audio/config/AssemblyAIConfig.java
package ai.driftkit.audio.config; import lombok.Data; /** * Configuration for AssemblyAI transcription service. */ @Data public class AssemblyAIConfig { /** * AssemblyAI API key. */ private String apiKey; /** * Language code for transcription. * Default: ENGLISH */ private LanguageCode languageCode = LanguageCode.ENGLISH; }
0
java-sources/ai/driftkit/driftkit-ai-audio/1.0.0/ai/driftkit/audio
java-sources/ai/driftkit/driftkit-ai-audio/1.0.0/ai/driftkit/audio/config/AudioProcessingConfig.java
package ai.driftkit.audio.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Configuration properties for audio processing */ @Data @ConfigurationProperties(prefix = "audio.processing") public class AudioProcessingConfig { /** * Transcription engine to use. * Default: ASSEMBLYAI */ private EngineType engine = EngineType.ASSEMBLYAI; /** * Processing mode for transcription. * Default: BATCH */ private ProcessingMode processingMode = ProcessingMode.BATCH; // Engine Configuration private AssemblyAIConfig assemblyai = new AssemblyAIConfig(); private DeepgramConfig deepgram = new DeepgramConfig(); // Audio Format Settings private int sampleRate = 16000; private int bufferSize = 4096; private int bufferSizeMs = 100; // Chunk Duration Settings private int maxChunkDurationSeconds = 60; private int minChunkDurationSeconds = 2; // Voice Activity Detection private VadConfig vad = new VadConfig(); // Debug Settings private DebugConfig debug = new DebugConfig(); // Performance and Resource Settings private int maxChunkSizeKb = 1024; private int maxBufferSizeMb = 10; private int processingTimeoutMs = 30000; }
0
java-sources/ai/driftkit/driftkit-ai-audio/1.0.0/ai/driftkit/audio
java-sources/ai/driftkit/driftkit-ai-audio/1.0.0/ai/driftkit/audio/config/DeepgramConfig.java
package ai.driftkit.audio.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.DefaultValue; /** * Configuration properties for Deepgram transcription service. */ @Data @ConfigurationProperties(prefix = "audio.processing.deepgram") public class DeepgramConfig { /** * Deepgram API key. */ private String apiKey; /** * Language code for transcription. * Default: ENGLISH */ private LanguageCode language = LanguageCode.ENGLISH; /** * Deepgram model to use. * Options: "nova-2", "nova", "enhanced", "base" * Default: "nova-2" */ private String model = "nova-2"; /** * Whether to add punctuation to transcriptions. * Default: true */ private boolean punctuate = true; /** * Whether to enable interim results for streaming. * Default: true */ private boolean interimResults = true; /** * Whether to enable automatic language detection. * Default: false */ private boolean detectLanguage = false; /** * Whether to enable speaker diarization. * Default: false */ private boolean diarize = false; /** * Number of speakers to detect if diarization is enabled. * Default: 2 */ private int diarizeVersion = 2; /** * Whether to enable profanity filtering. * Default: false */ private boolean profanityFilter = false; /** * Whether to enable redaction of sensitive information. * Default: false */ private boolean redact = false; /** * Smart formatting options. * Default: false */ private boolean smartFormat = false; }
0
java-sources/ai/driftkit/driftkit-ai-audio/1.0.0/ai/driftkit/audio
java-sources/ai/driftkit/driftkit-ai-audio/1.0.0/ai/driftkit/audio/config/EngineType.java
package ai.driftkit.audio.config; /** * Enumeration of supported transcription engines. */ public enum EngineType { ASSEMBLYAI("assemblyai"), DEEPGRAM("deepgram"); private final String value; EngineType(String value) { this.value = value; } public String getValue() { return value; } public static EngineType fromValue(String value) { for (EngineType engine : values()) { if (engine.value.equals(value)) { return engine; } } throw new IllegalArgumentException("Unknown transcription engine: " + value); } }
0
java-sources/ai/driftkit/driftkit-ai-audio/1.0.0/ai/driftkit/audio
java-sources/ai/driftkit/driftkit-ai-audio/1.0.0/ai/driftkit/audio/config/LanguageCode.java
package ai.driftkit.audio.config; /** * Enumeration of supported language codes for transcription. */ public enum LanguageCode { ENGLISH("en"), SPANISH("es"), FRENCH("fr"), GERMAN("de"), ITALIAN("it"), PORTUGUESE("pt"), DUTCH("nl"), RUSSIAN("ru"), CHINESE("zh"), JAPANESE("ja"), KOREAN("ko"), ARABIC("ar"), HINDI("hi"), TURKISH("tr"), POLISH("pl"), SWEDISH("sv"), NORWEGIAN("no"), DANISH("da"), FINNISH("fi"), CZECH("cs"), HUNGARIAN("hu"), ROMANIAN("ro"), BULGARIAN("bg"), CROATIAN("hr"), SLOVAK("sk"), SLOVENIAN("sl"), ESTONIAN("et"), LATVIAN("lv"), LITHUANIAN("lt"), UKRAINIAN("uk"), VIETNAMESE("vi"), THAI("th"), INDONESIAN("id"), MALAY("ms"), TAMIL("ta"), BENGALI("bn"), GUJARATI("gu"), MARATHI("mr"), TELUGU("te"), KANNADA("kn"), MALAYALAM("ml"), PUNJABI("pa"), URDU("ur"), HEBREW("he"), PERSIAN("fa"), GREEK("el"), CATALAN("ca"), BASQUE("eu"), GALICIAN("gl"), WELSH("cy"), IRISH("ga"), SCOTTISH_GAELIC("gd"), ICELANDIC("is"), MALTESE("mt"), AFRIKAANS("af"), SWAHILI("sw"), YORUBA("yo"), HAUSA("ha"), IGBO("ig"), AMHARIC("am"), SOMALI("so"), MULTI("multi"); private final String value; LanguageCode(String value) { this.value = value; } public String getValue() { return value; } public static LanguageCode fromValue(String value) { if (value == null) { return ENGLISH; // Default } for (LanguageCode language : values()) { if (language.value.equals(value)) { return language; } } throw new IllegalArgumentException("Unknown language code: " + value); } }