index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/SegmentMetadata.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import ai.whylabs.service.model.ModelMetadata;
import ai.whylabs.service.model.Segment;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* Metadata about a segment
*/
@ApiModel(description = "Metadata about a segment")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class SegmentMetadata {
public static final String SERIALIZED_NAME_ORG_ID = "orgId";
@SerializedName(SERIALIZED_NAME_ORG_ID)
private String orgId;
public static final String SERIALIZED_NAME_MODEL = "model";
@SerializedName(SERIALIZED_NAME_MODEL)
private ModelMetadata model;
public static final String SERIALIZED_NAME_SEGMENT = "segment";
@SerializedName(SERIALIZED_NAME_SEGMENT)
private Segment segment;
public static final String SERIALIZED_NAME_UPDATED_TIME = "updatedTime";
@SerializedName(SERIALIZED_NAME_UPDATED_TIME)
private Long updatedTime;
public SegmentMetadata orgId(String orgId) {
this.orgId = orgId;
return this;
}
/**
* Get orgId
* @return orgId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public SegmentMetadata model(ModelMetadata model) {
this.model = model;
return this;
}
/**
* Get model
* @return model
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public ModelMetadata getModel() {
return model;
}
public void setModel(ModelMetadata model) {
this.model = model;
}
public SegmentMetadata segment(Segment segment) {
this.segment = segment;
return this;
}
/**
* Get segment
* @return segment
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public Segment getSegment() {
return segment;
}
public void setSegment(Segment segment) {
this.segment = segment;
}
public SegmentMetadata updatedTime(Long updatedTime) {
this.updatedTime = updatedTime;
return this;
}
/**
* Get updatedTime
* @return updatedTime
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public Long getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Long updatedTime) {
this.updatedTime = updatedTime;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SegmentMetadata segmentMetadata = (SegmentMetadata) o;
return Objects.equals(this.orgId, segmentMetadata.orgId) &&
Objects.equals(this.model, segmentMetadata.model) &&
Objects.equals(this.segment, segmentMetadata.segment) &&
Objects.equals(this.updatedTime, segmentMetadata.updatedTime);
}
@Override
public int hashCode() {
return Objects.hash(orgId, model, segment, updatedTime);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SegmentMetadata {\n");
sb.append(" orgId: ").append(toIndentedString(orgId)).append("\n");
sb.append(" model: ").append(toIndentedString(model)).append("\n");
sb.append(" segment: ").append(toIndentedString(segment)).append("\n");
sb.append(" updatedTime: ").append(toIndentedString(updatedTime)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/SegmentSummary.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import ai.whylabs.service.model.Segment;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* Summary about a segment
*/
@ApiModel(description = "Summary about a segment")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class SegmentSummary {
public static final String SERIALIZED_NAME_ORG_ID = "orgId";
@SerializedName(SERIALIZED_NAME_ORG_ID)
private String orgId;
public static final String SERIALIZED_NAME_MODEL_ID = "modelId";
@SerializedName(SERIALIZED_NAME_MODEL_ID)
private String modelId;
public static final String SERIALIZED_NAME_SEGMENT = "segment";
@SerializedName(SERIALIZED_NAME_SEGMENT)
private Segment segment;
public static final String SERIALIZED_NAME_UPDATED_TIME = "updatedTime";
@SerializedName(SERIALIZED_NAME_UPDATED_TIME)
private Long updatedTime;
public SegmentSummary orgId(String orgId) {
this.orgId = orgId;
return this;
}
/**
* Get orgId
* @return orgId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public SegmentSummary modelId(String modelId) {
this.modelId = modelId;
return this;
}
/**
* Get modelId
* @return modelId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getModelId() {
return modelId;
}
public void setModelId(String modelId) {
this.modelId = modelId;
}
public SegmentSummary segment(Segment segment) {
this.segment = segment;
return this;
}
/**
* Get segment
* @return segment
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public Segment getSegment() {
return segment;
}
public void setSegment(Segment segment) {
this.segment = segment;
}
public SegmentSummary updatedTime(Long updatedTime) {
this.updatedTime = updatedTime;
return this;
}
/**
* Get updatedTime
* @return updatedTime
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public Long getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Long updatedTime) {
this.updatedTime = updatedTime;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SegmentSummary segmentSummary = (SegmentSummary) o;
return Objects.equals(this.orgId, segmentSummary.orgId) &&
Objects.equals(this.modelId, segmentSummary.modelId) &&
Objects.equals(this.segment, segmentSummary.segment) &&
Objects.equals(this.updatedTime, segmentSummary.updatedTime);
}
@Override
public int hashCode() {
return Objects.hash(orgId, modelId, segment, updatedTime);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SegmentSummary {\n");
sb.append(" orgId: ").append(toIndentedString(orgId)).append("\n");
sb.append(" modelId: ").append(toIndentedString(modelId)).append("\n");
sb.append(" segment: ").append(toIndentedString(segment)).append("\n");
sb.append(" updatedTime: ").append(toIndentedString(updatedTime)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/SegmentTag.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* A key value tag
*/
@ApiModel(description = "A key value tag")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class SegmentTag {
public static final String SERIALIZED_NAME_KEY = "key";
@SerializedName(SERIALIZED_NAME_KEY)
private String key;
public static final String SERIALIZED_NAME_VALUE = "value";
@SerializedName(SERIALIZED_NAME_VALUE)
private String value;
public SegmentTag key(String key) {
this.key = key;
return this;
}
/**
* Get key
* @return key
**/
@ApiModelProperty(required = true, value = "")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public SegmentTag value(String value) {
this.value = value;
return this;
}
/**
* Get value
* @return value
**/
@ApiModelProperty(required = true, value = "")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SegmentTag segmentTag = (SegmentTag) o;
return Objects.equals(this.key, segmentTag.key) &&
Objects.equals(this.value, segmentTag.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SegmentTag {\n");
sb.append(" key: ").append(toIndentedString(key)).append("\n");
sb.append(" value: ").append(toIndentedString(value)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/SessionMetadata.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* Response for getting sessions.
*/
@ApiModel(description = "Response for getting sessions.")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class SessionMetadata {
public static final String SERIALIZED_NAME_SESSION_ID = "sessionId";
@SerializedName(SERIALIZED_NAME_SESSION_ID)
private String sessionId;
public static final String SERIALIZED_NAME_ORG_ID = "orgId";
@SerializedName(SERIALIZED_NAME_ORG_ID)
private String orgId;
public static final String SERIALIZED_NAME_MODEL_ID = "modelId";
@SerializedName(SERIALIZED_NAME_MODEL_ID)
private String modelId;
public static final String SERIALIZED_NAME_CLOSED = "closed";
@SerializedName(SERIALIZED_NAME_CLOSED)
private Boolean closed;
public static final String SERIALIZED_NAME_USER_ID = "userId";
@SerializedName(SERIALIZED_NAME_USER_ID)
private String userId;
public SessionMetadata sessionId(String sessionId) {
this.sessionId = sessionId;
return this;
}
/**
* The id of the session
* @return sessionId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The id of the session")
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public SessionMetadata orgId(String orgId) {
this.orgId = orgId;
return this;
}
/**
* The org id of the session
* @return orgId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The org id of the session")
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public SessionMetadata modelId(String modelId) {
this.modelId = modelId;
return this;
}
/**
* The model id of the session. There should only be a single model.
* @return modelId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The model id of the session. There should only be a single model.")
public String getModelId() {
return modelId;
}
public void setModelId(String modelId) {
this.modelId = modelId;
}
public SessionMetadata closed(Boolean closed) {
this.closed = closed;
return this;
}
/**
* Whether or not the session is open for uploading dataset profiles to.
* @return closed
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Whether or not the session is open for uploading dataset profiles to.")
public Boolean getClosed() {
return closed;
}
public void setClosed(Boolean closed) {
this.closed = closed;
}
public SessionMetadata userId(String userId) {
this.userId = userId;
return this;
}
/**
* The generated user id for the session.
* @return userId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The generated user id for the session.")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SessionMetadata sessionMetadata = (SessionMetadata) o;
return Objects.equals(this.sessionId, sessionMetadata.sessionId) &&
Objects.equals(this.orgId, sessionMetadata.orgId) &&
Objects.equals(this.modelId, sessionMetadata.modelId) &&
Objects.equals(this.closed, sessionMetadata.closed) &&
Objects.equals(this.userId, sessionMetadata.userId);
}
@Override
public int hashCode() {
return Objects.hash(sessionId, orgId, modelId, closed, userId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SessionMetadata {\n");
sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n");
sb.append(" orgId: ").append(toIndentedString(orgId)).append("\n");
sb.append(" modelId: ").append(toIndentedString(modelId)).append("\n");
sb.append(" closed: ").append(toIndentedString(closed)).append("\n");
sb.append(" userId: ").append(toIndentedString(userId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/SetDefaultMembershipRequest.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* SetDefaultMembershipRequest
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class SetDefaultMembershipRequest {
public static final String SERIALIZED_NAME_ORG_ID = "orgId";
@SerializedName(SERIALIZED_NAME_ORG_ID)
private String orgId;
public static final String SERIALIZED_NAME_USER_ID = "userId";
@SerializedName(SERIALIZED_NAME_USER_ID)
private String userId;
public SetDefaultMembershipRequest orgId(String orgId) {
this.orgId = orgId;
return this;
}
/**
* Get orgId
* @return orgId
**/
@ApiModelProperty(required = true, value = "")
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public SetDefaultMembershipRequest userId(String userId) {
this.userId = userId;
return this;
}
/**
* Get userId
* @return userId
**/
@ApiModelProperty(required = true, value = "")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SetDefaultMembershipRequest setDefaultMembershipRequest = (SetDefaultMembershipRequest) o;
return Objects.equals(this.orgId, setDefaultMembershipRequest.orgId) &&
Objects.equals(this.userId, setDefaultMembershipRequest.userId);
}
@Override
public int hashCode() {
return Objects.hash(orgId, userId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SetDefaultMembershipRequest {\n");
sb.append(" orgId: ").append(toIndentedString(orgId)).append("\n");
sb.append(" userId: ").append(toIndentedString(userId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/SubscriptionTier.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* Gets or Sets SubscriptionTier
*/
@JsonAdapter(SubscriptionTier.Adapter.class)
public enum SubscriptionTier {
FREE("FREE"),
PAID("PAID");
private String value;
SubscriptionTier(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static SubscriptionTier fromValue(String value) {
for (SubscriptionTier b : SubscriptionTier.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
public static class Adapter extends TypeAdapter<SubscriptionTier> {
@Override
public void write(final JsonWriter jsonWriter, final SubscriptionTier enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public SubscriptionTier read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return SubscriptionTier.fromValue(value);
}
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/SummarizedDatasetProfileMeta.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* SummarizedDatasetProfileMeta
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class SummarizedDatasetProfileMeta {
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private String id;
public static final String SERIALIZED_NAME_ORG_ID = "orgId";
@SerializedName(SERIALIZED_NAME_ORG_ID)
private String orgId;
public static final String SERIALIZED_NAME_MODEL_ID = "modelId";
@SerializedName(SERIALIZED_NAME_MODEL_ID)
private String modelId;
public static final String SERIALIZED_NAME_TIMESTAMP_EPOCH = "timestampEpoch";
@SerializedName(SERIALIZED_NAME_TIMESTAMP_EPOCH)
private Long timestampEpoch;
public SummarizedDatasetProfileMeta id(String id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public SummarizedDatasetProfileMeta orgId(String orgId) {
this.orgId = orgId;
return this;
}
/**
* Get orgId
* @return orgId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public SummarizedDatasetProfileMeta modelId(String modelId) {
this.modelId = modelId;
return this;
}
/**
* Get modelId
* @return modelId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getModelId() {
return modelId;
}
public void setModelId(String modelId) {
this.modelId = modelId;
}
public SummarizedDatasetProfileMeta timestampEpoch(Long timestampEpoch) {
this.timestampEpoch = timestampEpoch;
return this;
}
/**
* Get timestampEpoch
* @return timestampEpoch
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public Long getTimestampEpoch() {
return timestampEpoch;
}
public void setTimestampEpoch(Long timestampEpoch) {
this.timestampEpoch = timestampEpoch;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SummarizedDatasetProfileMeta summarizedDatasetProfileMeta = (SummarizedDatasetProfileMeta) o;
return Objects.equals(this.id, summarizedDatasetProfileMeta.id) &&
Objects.equals(this.orgId, summarizedDatasetProfileMeta.orgId) &&
Objects.equals(this.modelId, summarizedDatasetProfileMeta.modelId) &&
Objects.equals(this.timestampEpoch, summarizedDatasetProfileMeta.timestampEpoch);
}
@Override
public int hashCode() {
return Objects.hash(id, orgId, modelId, timestampEpoch);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SummarizedDatasetProfileMeta {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" orgId: ").append(toIndentedString(orgId)).append("\n");
sb.append(" modelId: ").append(toIndentedString(modelId)).append("\n");
sb.append(" timestampEpoch: ").append(toIndentedString(timestampEpoch)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/SummarizedDatasetProfilePaths.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* Information about locations of summarized dataset profile.
*/
@ApiModel(description = "Information about locations of summarized dataset profile.")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class SummarizedDatasetProfilePaths {
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private String id;
public static final String SERIALIZED_NAME_MODEL_ID = "modelId";
@SerializedName(SERIALIZED_NAME_MODEL_ID)
private String modelId;
public static final String SERIALIZED_NAME_TIMESTAMP = "timestamp";
@SerializedName(SERIALIZED_NAME_TIMESTAMP)
private Long timestamp;
public static final String SERIALIZED_NAME_PROTOBUF = "protobuf";
@SerializedName(SERIALIZED_NAME_PROTOBUF)
private String protobuf;
public static final String SERIALIZED_NAME_PROTOBUF_ETAG = "protobufEtag";
@SerializedName(SERIALIZED_NAME_PROTOBUF_ETAG)
private String protobufEtag;
public static final String SERIALIZED_NAME_JSON = "json";
@SerializedName(SERIALIZED_NAME_JSON)
private String json;
public static final String SERIALIZED_NAME_JSON_ETAG = "jsonEtag";
@SerializedName(SERIALIZED_NAME_JSON_ETAG)
private String jsonEtag;
public SummarizedDatasetProfilePaths id(String id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public SummarizedDatasetProfilePaths modelId(String modelId) {
this.modelId = modelId;
return this;
}
/**
* Get modelId
* @return modelId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getModelId() {
return modelId;
}
public void setModelId(String modelId) {
this.modelId = modelId;
}
public SummarizedDatasetProfilePaths timestamp(Long timestamp) {
this.timestamp = timestamp;
return this;
}
/**
* Get timestamp
* @return timestamp
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public SummarizedDatasetProfilePaths protobuf(String protobuf) {
this.protobuf = protobuf;
return this;
}
/**
* Get protobuf
* @return protobuf
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getProtobuf() {
return protobuf;
}
public void setProtobuf(String protobuf) {
this.protobuf = protobuf;
}
public SummarizedDatasetProfilePaths protobufEtag(String protobufEtag) {
this.protobufEtag = protobufEtag;
return this;
}
/**
* Get protobufEtag
* @return protobufEtag
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getProtobufEtag() {
return protobufEtag;
}
public void setProtobufEtag(String protobufEtag) {
this.protobufEtag = protobufEtag;
}
public SummarizedDatasetProfilePaths json(String json) {
this.json = json;
return this;
}
/**
* Get json
* @return json
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
public SummarizedDatasetProfilePaths jsonEtag(String jsonEtag) {
this.jsonEtag = jsonEtag;
return this;
}
/**
* Get jsonEtag
* @return jsonEtag
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getJsonEtag() {
return jsonEtag;
}
public void setJsonEtag(String jsonEtag) {
this.jsonEtag = jsonEtag;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SummarizedDatasetProfilePaths summarizedDatasetProfilePaths = (SummarizedDatasetProfilePaths) o;
return Objects.equals(this.id, summarizedDatasetProfilePaths.id) &&
Objects.equals(this.modelId, summarizedDatasetProfilePaths.modelId) &&
Objects.equals(this.timestamp, summarizedDatasetProfilePaths.timestamp) &&
Objects.equals(this.protobuf, summarizedDatasetProfilePaths.protobuf) &&
Objects.equals(this.protobufEtag, summarizedDatasetProfilePaths.protobufEtag) &&
Objects.equals(this.json, summarizedDatasetProfilePaths.json) &&
Objects.equals(this.jsonEtag, summarizedDatasetProfilePaths.jsonEtag);
}
@Override
public int hashCode() {
return Objects.hash(id, modelId, timestamp, protobuf, protobufEtag, json, jsonEtag);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SummarizedDatasetProfilePaths {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" modelId: ").append(toIndentedString(modelId)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append(" protobuf: ").append(toIndentedString(protobuf)).append("\n");
sb.append(" protobufEtag: ").append(toIndentedString(protobufEtag)).append("\n");
sb.append(" json: ").append(toIndentedString(json)).append("\n");
sb.append(" jsonEtag: ").append(toIndentedString(jsonEtag)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/TimePeriod.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import io.swagger.annotations.ApiModel;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* A TimePeriod represents the bucketing that a dataset has undergone.
*/
@JsonAdapter(TimePeriod.Adapter.class)
public enum TimePeriod {
P1D("P1D"),
PT1H("PT1H"),
PT5M("PT5M");
private String value;
TimePeriod(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static TimePeriod fromValue(String value) {
for (TimePeriod b : TimePeriod.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
public static class Adapter extends TypeAdapter<TimePeriod> {
@Override
public void write(final JsonWriter jsonWriter, final TimePeriod enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public TimePeriod read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return TimePeriod.fromValue(value);
}
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/UberNotificationSchedule.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import ai.whylabs.service.model.NotificationSettingsDay;
import ai.whylabs.service.model.NotificationSqsMessageCadence;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* Combination of all possible schedule types, a hacky workaround for bugs in generated clients that use polymorphic types. There are three types of schedules. Weekly, Daily, and Individual. You need to set the right fields for each one. Weekly: enabled, cadence=WEEKLY, dayOfWeek, local24HourOfDay, localMinuteOfHour, localTimezone Daily: enabled, cadence=DAILY, local24HourOfDay, localMinuteOfHour, localTimezone Individual: enabled, cadence=INDIVIDUAL
*/
@ApiModel(description = " Combination of all possible schedule types, a hacky workaround for bugs in generated clients that use polymorphic types. There are three types of schedules. Weekly, Daily, and Individual. You need to set the right fields for each one. Weekly: enabled, cadence=WEEKLY, dayOfWeek, local24HourOfDay, localMinuteOfHour, localTimezone Daily: enabled, cadence=DAILY, local24HourOfDay, localMinuteOfHour, localTimezone Individual: enabled, cadence=INDIVIDUAL ")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class UberNotificationSchedule {
public static final String SERIALIZED_NAME_ENABLED = "enabled";
@SerializedName(SERIALIZED_NAME_ENABLED)
private Boolean enabled;
public static final String SERIALIZED_NAME_CADENCE = "cadence";
@SerializedName(SERIALIZED_NAME_CADENCE)
private NotificationSqsMessageCadence cadence;
public static final String SERIALIZED_NAME_DAY_OF_WEEK = "dayOfWeek";
@SerializedName(SERIALIZED_NAME_DAY_OF_WEEK)
private NotificationSettingsDay dayOfWeek;
public static final String SERIALIZED_NAME_LOCAL24_HOUR_OF_DAY = "local24HourOfDay";
@SerializedName(SERIALIZED_NAME_LOCAL24_HOUR_OF_DAY)
private Integer local24HourOfDay;
public static final String SERIALIZED_NAME_LOCAL_MINUTE_OF_HOUR = "localMinuteOfHour";
@SerializedName(SERIALIZED_NAME_LOCAL_MINUTE_OF_HOUR)
private Integer localMinuteOfHour;
public static final String SERIALIZED_NAME_LOCAL_TIMEZONE = "localTimezone";
@SerializedName(SERIALIZED_NAME_LOCAL_TIMEZONE)
private String localTimezone;
public UberNotificationSchedule enabled(Boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Get enabled
* @return enabled
**/
@ApiModelProperty(required = true, value = "")
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public UberNotificationSchedule cadence(NotificationSqsMessageCadence cadence) {
this.cadence = cadence;
return this;
}
/**
* Get cadence
* @return cadence
**/
@ApiModelProperty(required = true, value = "")
public NotificationSqsMessageCadence getCadence() {
return cadence;
}
public void setCadence(NotificationSqsMessageCadence cadence) {
this.cadence = cadence;
}
public UberNotificationSchedule dayOfWeek(NotificationSettingsDay dayOfWeek) {
this.dayOfWeek = dayOfWeek;
return this;
}
/**
* Get dayOfWeek
* @return dayOfWeek
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public NotificationSettingsDay getDayOfWeek() {
return dayOfWeek;
}
public void setDayOfWeek(NotificationSettingsDay dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}
public UberNotificationSchedule local24HourOfDay(Integer local24HourOfDay) {
this.local24HourOfDay = local24HourOfDay;
return this;
}
/**
* Get local24HourOfDay
* @return local24HourOfDay
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public Integer getLocal24HourOfDay() {
return local24HourOfDay;
}
public void setLocal24HourOfDay(Integer local24HourOfDay) {
this.local24HourOfDay = local24HourOfDay;
}
public UberNotificationSchedule localMinuteOfHour(Integer localMinuteOfHour) {
this.localMinuteOfHour = localMinuteOfHour;
return this;
}
/**
* Get localMinuteOfHour
* @return localMinuteOfHour
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public Integer getLocalMinuteOfHour() {
return localMinuteOfHour;
}
public void setLocalMinuteOfHour(Integer localMinuteOfHour) {
this.localMinuteOfHour = localMinuteOfHour;
}
public UberNotificationSchedule localTimezone(String localTimezone) {
this.localTimezone = localTimezone;
return this;
}
/**
* Get localTimezone
* @return localTimezone
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getLocalTimezone() {
return localTimezone;
}
public void setLocalTimezone(String localTimezone) {
this.localTimezone = localTimezone;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UberNotificationSchedule uberNotificationSchedule = (UberNotificationSchedule) o;
return Objects.equals(this.enabled, uberNotificationSchedule.enabled) &&
Objects.equals(this.cadence, uberNotificationSchedule.cadence) &&
Objects.equals(this.dayOfWeek, uberNotificationSchedule.dayOfWeek) &&
Objects.equals(this.local24HourOfDay, uberNotificationSchedule.local24HourOfDay) &&
Objects.equals(this.localMinuteOfHour, uberNotificationSchedule.localMinuteOfHour) &&
Objects.equals(this.localTimezone, uberNotificationSchedule.localTimezone);
}
@Override
public int hashCode() {
return Objects.hash(enabled, cadence, dayOfWeek, local24HourOfDay, localMinuteOfHour, localTimezone);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UberNotificationSchedule {\n");
sb.append(" enabled: ").append(toIndentedString(enabled)).append("\n");
sb.append(" cadence: ").append(toIndentedString(cadence)).append("\n");
sb.append(" dayOfWeek: ").append(toIndentedString(dayOfWeek)).append("\n");
sb.append(" local24HourOfDay: ").append(toIndentedString(local24HourOfDay)).append("\n");
sb.append(" localMinuteOfHour: ").append(toIndentedString(localMinuteOfHour)).append("\n");
sb.append(" localTimezone: ").append(toIndentedString(localTimezone)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/UploadDatasetProfileResponse.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* UploadDatasetProfileResponse
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class UploadDatasetProfileResponse {
public static final String SERIALIZED_NAME_DATASET_PROFILE_ID = "datasetProfileId";
@SerializedName(SERIALIZED_NAME_DATASET_PROFILE_ID)
private String datasetProfileId;
public UploadDatasetProfileResponse datasetProfileId(String datasetProfileId) {
this.datasetProfileId = datasetProfileId;
return this;
}
/**
* Get datasetProfileId
* @return datasetProfileId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getDatasetProfileId() {
return datasetProfileId;
}
public void setDatasetProfileId(String datasetProfileId) {
this.datasetProfileId = datasetProfileId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UploadDatasetProfileResponse uploadDatasetProfileResponse = (UploadDatasetProfileResponse) o;
return Objects.equals(this.datasetProfileId, uploadDatasetProfileResponse.datasetProfileId);
}
@Override
public int hashCode() {
return Objects.hash(datasetProfileId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UploadDatasetProfileResponse {\n");
sb.append(" datasetProfileId: ").append(toIndentedString(datasetProfileId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/User.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* User metadata
*/
@ApiModel(description = "User metadata")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class User {
public static final String SERIALIZED_NAME_USER_ID = "userId";
@SerializedName(SERIALIZED_NAME_USER_ID)
private String userId;
public static final String SERIALIZED_NAME_EMAIL = "email";
@SerializedName(SERIALIZED_NAME_EMAIL)
private String email;
public User userId(String userId) {
this.userId = userId;
return this;
}
/**
* The id of the users.
* @return userId
**/
@ApiModelProperty(required = true, value = "The id of the users.")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public User email(String email) {
this.email = email;
return this;
}
/**
* The users email address.
* @return email
**/
@ApiModelProperty(required = true, value = "The users email address.")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(this.userId, user.userId) &&
Objects.equals(this.email, user.email);
}
@Override
public int hashCode() {
return Objects.hash(userId, email);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class User {\n");
sb.append(" userId: ").append(toIndentedString(userId)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/UserApiKey.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Response when creating an API key successfully
*/
@ApiModel(description = "Response when creating an API key successfully")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class UserApiKey {
public static final String SERIALIZED_NAME_KEY = "key";
@SerializedName(SERIALIZED_NAME_KEY)
private String key;
public static final String SERIALIZED_NAME_KEY_ID = "keyId";
@SerializedName(SERIALIZED_NAME_KEY_ID)
private String keyId;
public static final String SERIALIZED_NAME_ORG_ID = "orgId";
@SerializedName(SERIALIZED_NAME_ORG_ID)
private String orgId;
public static final String SERIALIZED_NAME_USER_ID = "userId";
@SerializedName(SERIALIZED_NAME_USER_ID)
private String userId;
public static final String SERIALIZED_NAME_CREATION_TIME = "creationTime";
@SerializedName(SERIALIZED_NAME_CREATION_TIME)
private String creationTime;
public static final String SERIALIZED_NAME_EXPIRATION_TIME = "expirationTime";
@SerializedName(SERIALIZED_NAME_EXPIRATION_TIME)
private String expirationTime;
public static final String SERIALIZED_NAME_SCOPES = "scopes";
@SerializedName(SERIALIZED_NAME_SCOPES)
private List<String> scopes = null;
public static final String SERIALIZED_NAME_ALIAS = "alias";
@SerializedName(SERIALIZED_NAME_ALIAS)
private String alias;
public static final String SERIALIZED_NAME_REVOKED = "revoked";
@SerializedName(SERIALIZED_NAME_REVOKED)
private Boolean revoked;
public UserApiKey key(String key) {
this.key = key;
return this;
}
/**
* The full value of the key. This is not persisted in the system
* @return key
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The full value of the key. This is not persisted in the system")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public UserApiKey keyId(String keyId) {
this.keyId = keyId;
return this;
}
/**
* The key id. Can be used to identify keys for a given user
* @return keyId
**/
@ApiModelProperty(required = true, value = "The key id. Can be used to identify keys for a given user")
public String getKeyId() {
return keyId;
}
public void setKeyId(String keyId) {
this.keyId = keyId;
}
public UserApiKey orgId(String orgId) {
this.orgId = orgId;
return this;
}
/**
* The organization that the key belongs to
* @return orgId
**/
@ApiModelProperty(required = true, value = "The organization that the key belongs to")
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public UserApiKey userId(String userId) {
this.userId = userId;
return this;
}
/**
* The user that the key represents
* @return userId
**/
@ApiModelProperty(required = true, value = "The user that the key represents")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public UserApiKey creationTime(String creationTime) {
this.creationTime = creationTime;
return this;
}
/**
* Creation time in human readable format
* @return creationTime
**/
@ApiModelProperty(required = true, value = "Creation time in human readable format")
public String getCreationTime() {
return creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public UserApiKey expirationTime(String expirationTime) {
this.expirationTime = expirationTime;
return this;
}
/**
* Expiration time in human readable format
* @return expirationTime
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Expiration time in human readable format")
public String getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(String expirationTime) {
this.expirationTime = expirationTime;
}
public UserApiKey scopes(List<String> scopes) {
this.scopes = scopes;
return this;
}
public UserApiKey addScopesItem(String scopesItem) {
if (this.scopes == null) {
this.scopes = new ArrayList<>();
}
this.scopes.add(scopesItem);
return this;
}
/**
* Scope of the key
* @return scopes
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Scope of the key")
public List<String> getScopes() {
return scopes;
}
public void setScopes(List<String> scopes) {
this.scopes = scopes;
}
public UserApiKey alias(String alias) {
this.alias = alias;
return this;
}
/**
* Human-readable alias for the key
* @return alias
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Human-readable alias for the key")
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public UserApiKey revoked(Boolean revoked) {
this.revoked = revoked;
return this;
}
/**
* Whether the key has been revoked
* @return revoked
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Whether the key has been revoked")
public Boolean getRevoked() {
return revoked;
}
public void setRevoked(Boolean revoked) {
this.revoked = revoked;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UserApiKey userApiKey = (UserApiKey) o;
return Objects.equals(this.key, userApiKey.key) &&
Objects.equals(this.keyId, userApiKey.keyId) &&
Objects.equals(this.orgId, userApiKey.orgId) &&
Objects.equals(this.userId, userApiKey.userId) &&
Objects.equals(this.creationTime, userApiKey.creationTime) &&
Objects.equals(this.expirationTime, userApiKey.expirationTime) &&
Objects.equals(this.scopes, userApiKey.scopes) &&
Objects.equals(this.alias, userApiKey.alias) &&
Objects.equals(this.revoked, userApiKey.revoked);
}
@Override
public int hashCode() {
return Objects.hash(key, keyId, orgId, userId, creationTime, expirationTime, scopes, alias, revoked);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UserApiKey {\n");
sb.append(" key: ").append(toIndentedString(key)).append("\n");
sb.append(" keyId: ").append(toIndentedString(keyId)).append("\n");
sb.append(" orgId: ").append(toIndentedString(orgId)).append("\n");
sb.append(" userId: ").append(toIndentedString(userId)).append("\n");
sb.append(" creationTime: ").append(toIndentedString(creationTime)).append("\n");
sb.append(" expirationTime: ").append(toIndentedString(expirationTime)).append("\n");
sb.append(" scopes: ").append(toIndentedString(scopes)).append("\n");
sb.append(" alias: ").append(toIndentedString(alias)).append("\n");
sb.append(" revoked: ").append(toIndentedString(revoked)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service | java-sources/ai/whylabs/whylabs-api-client/0.1.8/ai/whylabs/service/model/UserApiKeyResponse.java | /*
* WhyLabs API client
* WhyLabs API that enables end-to-end AI observability
*
* The version of the OpenAPI document: 0.1
* Contact: support@whylabs.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.whylabs.service.model;
import java.util.Objects;
import java.util.Arrays;
import ai.whylabs.service.model.UserApiKey;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* UserApiKeyResponse
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-06T09:52:04.507863-07:00[America/Los_Angeles]")
public class UserApiKeyResponse {
public static final String SERIALIZED_NAME_KEY = "key";
@SerializedName(SERIALIZED_NAME_KEY)
private UserApiKey key;
public UserApiKeyResponse key(UserApiKey key) {
this.key = key;
return this;
}
/**
* Get key
* @return key
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public UserApiKey getKey() {
return key;
}
public void setKey(UserApiKey key) {
this.key = key;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UserApiKeyResponse userApiKeyResponse = (UserApiKeyResponse) o;
return Objects.equals(this.key, userApiKeyResponse.key);
}
@Override
public int hashCode() {
return Objects.hash(key);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UserApiKeyResponse {\n");
sb.append(" key: ").append(toIndentedString(key)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/ColumnProfile.java | package com.whylogs.core;
import static com.whylogs.core.SummaryConverters.fromSchemaTracker;
import static com.whylogs.core.statistics.datatypes.StringTracker.ARRAY_OF_STRINGS_SER_DE;
import static com.whylogs.core.types.TypedDataConverter.NUMERIC_TYPES;
import com.google.common.base.Preconditions;
import com.google.protobuf.ByteString;
import com.whylogs.core.message.ColumnMessage;
import com.whylogs.core.message.ColumnSummary;
import com.whylogs.core.message.FrequentItemsSketchMessage;
import com.whylogs.core.message.HllSketchMessage;
import com.whylogs.core.statistics.CountersTracker;
import com.whylogs.core.statistics.NumberTracker;
import com.whylogs.core.statistics.SchemaTracker;
import com.whylogs.core.types.TypedDataConverter;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.val;
import org.apache.datasketches.frequencies.ItemsSketch;
import org.apache.datasketches.hll.HllSketch;
import org.apache.datasketches.hll.Union;
import org.apache.datasketches.memory.Memory;
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
@Builder(setterPrefix = "set")
public class ColumnProfile {
private static final int FREQUENT_MAX_LG_K = 7;
private static final int CARDINALITY_LG_K = 12;
@NonNull private final String columnName;
@NonNull private final CountersTracker counters;
@NonNull private final SchemaTracker schemaTracker;
@NonNull private final NumberTracker numberTracker;
@NonNull private final ItemsSketch<String> frequentItems;
@NonNull private final HllSketch cardinalityTracker;
public ColumnProfile(String columnName) {
this.columnName = columnName;
this.counters = new CountersTracker();
this.schemaTracker = new SchemaTracker();
this.numberTracker = new NumberTracker();
this.frequentItems = new ItemsSketch<>((int) Math.pow(2, FREQUENT_MAX_LG_K));
this.cardinalityTracker = new HllSketch(CARDINALITY_LG_K);
}
public void track(Object value) {
synchronized (this) {
counters.incrementCount();
if (value == null) {
counters.incrementNull();
return;
}
// always track text information
// TODO: ignore this if we already know the data type
if (value instanceof String) {
val stringValue = (String) value;
this.frequentItems.update(stringValue);
}
val typedData = TypedDataConverter.convert(value);
schemaTracker.track(typedData.getType());
switch (typedData.getType()) {
case FRACTIONAL:
frequentItems.update(typedData.toString());
numberTracker.track(typedData.getFractional());
break;
case INTEGRAL:
frequentItems.update(typedData.toString());
numberTracker.track(typedData.getIntegralValue());
break;
case BOOLEAN:
// TODO: handle boolean across languages? Python booleans are "True" vs Java "true"
frequentItems.update(typedData.toString());
if (typedData.isBooleanValue()) {
counters.incrementTrue();
}
break;
}
}
}
public ColumnSummary toColumnSummary() {
val schema = fromSchemaTracker(schemaTracker);
val builder = ColumnSummary.newBuilder().setCounters(counters.toProtobuf());
if (schema != null) {
builder.setSchema(schema);
if (NUMERIC_TYPES.contains(schema.getInferredType().getType())) {
val numberSummary = SummaryConverters.fromNumberTracker(this.numberTracker);
if (numberSummary != null) {
builder.setNumberSummary(numberSummary);
}
}
}
return builder.build();
}
public ColumnProfile merge(ColumnProfile other) {
Preconditions.checkArgument(
this.columnName.equals(other.columnName),
"Mismatched column name. Expected [%s], got [%s]",
this.columnName,
other.columnName);
val mergedSketch = Union.heapify(this.cardinalityTracker.toCompactByteArray());
mergedSketch.update(other.cardinalityTracker);
val iMem = Memory.wrap(frequentItems.toByteArray(ARRAY_OF_STRINGS_SER_DE));
val copyFreqItems = ItemsSketch.getInstance(iMem, ARRAY_OF_STRINGS_SER_DE);
copyFreqItems.merge(other.frequentItems);
return ColumnProfile.builder()
.setColumnName(this.columnName)
.setCounters(this.counters.merge(other.counters))
.setNumberTracker(this.numberTracker.merge(other.numberTracker))
.setSchemaTracker(this.schemaTracker.merge(other.schemaTracker))
.setCardinalityTracker(HllSketch.heapify(mergedSketch.toCompactByteArray()))
.setFrequentItems(copyFreqItems)
.build();
}
public ColumnMessage.Builder toProtobuf() {
val hllSketchMessage =
HllSketchMessage.newBuilder()
.setLgK(cardinalityTracker.getLgConfigK())
.setSketch(ByteString.copyFrom(cardinalityTracker.toCompactByteArray()));
val frequentItems =
FrequentItemsSketchMessage.newBuilder()
.setLgMaxK(FREQUENT_MAX_LG_K)
.setSketch(
ByteString.copyFrom(this.frequentItems.toByteArray(ARRAY_OF_STRINGS_SER_DE)));
return ColumnMessage.newBuilder()
.setName(columnName)
.setCounters(counters.toProtobuf())
.setSchema(schemaTracker.toProtobuf())
.setNumbers(numberTracker.toProtobuf())
.setCardinalityTracker(hllSketchMessage)
.setFrequentItems(frequentItems);
}
public static ColumnProfile fromProtobuf(ColumnMessage message) {
val iMem = Memory.wrap(message.getFrequentItems().getSketch().toByteArray());
val items = ItemsSketch.getInstance(iMem, ARRAY_OF_STRINGS_SER_DE);
return ColumnProfile.builder()
.setColumnName(message.getName())
.setCounters(CountersTracker.fromProtobuf(message.getCounters()))
.setSchemaTracker(SchemaTracker.fromProtobuf(message.getSchema()))
.setNumberTracker(NumberTracker.fromProtobuf(message.getNumbers()))
.setCardinalityTracker(
HllSketch.heapify(message.getCardinalityTracker().getSketch().toByteArray()))
.setFrequentItems(items)
.build();
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/DatasetProfile.java | package com.whylogs.core;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import com.whylogs.core.iterator.ColumnsChunkSegmentIterator;
import com.whylogs.core.message.ColumnMessage;
import com.whylogs.core.message.ColumnSummary;
import com.whylogs.core.message.ColumnsChunkSegment;
import com.whylogs.core.message.DatasetMetadataSegment;
import com.whylogs.core.message.DatasetProfileMessage;
import com.whylogs.core.message.DatasetProperties;
import com.whylogs.core.message.DatasetSummary;
import com.whylogs.core.message.MessageSegment;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.time.Instant;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import lombok.Getter;
import lombok.NonNull;
import lombok.Value;
import lombok.val;
/** Representing a DatasetProfile that tracks */
public class DatasetProfile implements Serializable {
// generated by IntelliJ
private static final long serialVersionUID = -9221998596693275458L;
@Getter String sessionId;
@Getter Instant sessionTimestamp;
@Getter Instant dataTimestamp;
// always sorted
@Getter Map<String, String> tags;
@Getter Map<String, String> metadata;
Map<String, ColumnProfile> columns;
/**
* DEVELOPER API. DO NOT USE DIRECTLY
*
* @param sessionId dataset name
* @param sessionTimestamp the timestamp for the current profiling session
* @param dataTimestamp the timestamp for the dataset. Used to aggregate across different cadences
* @param tags tags of the dataset
* @param columns the columns that we're copying over. Note that the source of columns should stop
* using these column objects as they will back this DatasetProfile instead
*/
public DatasetProfile(
@NonNull String sessionId,
@NonNull Instant sessionTimestamp,
@Nullable Instant dataTimestamp,
@NonNull Map<String, String> tags,
@NonNull Map<String, ColumnProfile> columns) {
this.sessionId = sessionId;
this.sessionTimestamp = sessionTimestamp;
this.dataTimestamp = dataTimestamp;
this.columns = new ConcurrentHashMap<>();
this.tags = new ConcurrentHashMap<>(Optional.ofNullable(tags).orElse(Collections.emptyMap()));
this.metadata = new ConcurrentHashMap<>();
this.columns =
new ConcurrentHashMap<>(Optional.ofNullable(columns).orElse(Collections.emptyMap()));
}
/**
* Create a new Dataset profile
*
* @param sessionId the name of the dataset profile
* @param sessionTimestamp the timestamp for this run
* @param tags the tags to track the dataset with
*/
public DatasetProfile(
@NonNull String sessionId,
@NonNull Instant sessionTimestamp,
@NonNull Map<String, String> tags) {
this(sessionId, sessionTimestamp, null, tags, Collections.emptyMap());
}
public DatasetProfile(String sessionId, Instant sessionTimestamp) {
this(sessionId, sessionTimestamp, Collections.emptyMap());
}
public Map<String, ColumnProfile> getColumns() {
return Collections.unmodifiableMap(columns);
}
public DatasetProfile withMetadata(String key, String value) {
this.metadata.put(key, value);
return this;
}
public DatasetProfile withAllMetadata(Map<String, String> metadata) {
this.metadata.putAll(metadata);
return this;
}
private void validate() {
Preconditions.checkNotNull(sessionId);
Preconditions.checkNotNull(sessionTimestamp);
Preconditions.checkNotNull(columns);
Preconditions.checkNotNull(metadata);
Preconditions.checkNotNull(tags);
}
public void track(String columnName, Object data) {
trackSingleColumn(columnName, data);
}
private void trackSingleColumn(String columnName, Object data) {
val columnProfile = columns.computeIfAbsent(columnName, ColumnProfile::new);
columnProfile.track(data);
}
public void track(Map<String, ?> columns) {
columns.forEach(this::track);
}
public DatasetSummary toSummary() {
validate();
val summaryColumns =
columns.values().stream()
.map(Pair::fromColumn)
.collect(Collectors.toMap(Pair::getName, Pair::getStatistics));
val summary =
DatasetSummary.newBuilder()
.setProperties(toDatasetProperties())
.putAllColumns(summaryColumns);
return summary.build();
}
public Iterator<MessageSegment> toChunkIterator() {
validate();
final String marker = sessionId + UUID.randomUUID().toString();
// first segment is the metadata
val properties = toDatasetProperties();
val metadataBuilder =
DatasetMetadataSegment.newBuilder().setProperties(properties).setMarker(marker);
val metadataSegment =
MessageSegment.newBuilder().setMarker(marker).setMetadata(metadataBuilder).build();
// then we group the columns by size
val chunkedColumns =
columns.values().stream()
.map(ColumnProfile::toProtobuf)
.map(ColumnMessage.Builder::build)
.iterator();
val columnSegmentMessages =
Iterators.<ColumnsChunkSegment, MessageSegment>transform(
new ColumnsChunkSegmentIterator(chunkedColumns, marker),
msg -> MessageSegment.newBuilder().setColumns(msg).build());
return Iterators.concat(Iterators.singletonIterator(metadataSegment), columnSegmentMessages);
}
public DatasetProfile mergeStrict(@NonNull DatasetProfile other) {
Preconditions.checkArgument(
Objects.equals(this.sessionId, other.sessionId),
"Mismatched name. Current name [%s] is merged with [%s]",
this.sessionId,
other.sessionId);
Preconditions.checkArgument(
Objects.equals(this.sessionTimestamp, other.sessionTimestamp),
"Mismatched session timestamp. Current ts [%s] is merged with [%s]",
this.sessionTimestamp,
other.sessionTimestamp);
Preconditions.checkArgument(
Objects.equals(this.dataTimestamp, other.dataTimestamp),
"Mismatched data timestamp. Current ts [%s] is merged with [%s]",
this.dataTimestamp,
other.dataTimestamp);
Preconditions.checkArgument(
Objects.equals(this.tags, other.tags),
"Mismatched tags. Current %s being merged with %s",
this.tags,
other.tags);
return doMerge(other, this.tags);
}
/**
* Merge the data of another {@link DatasetProfile} into this one.
*
* <p>We will only retain the shared tags and share metadata. The timestamps are copied over from
* this dataset. It is the responsibility of the user to ensure that the two datasets are matched
* on important grouping information
*
* @param other a {@link DatasetProfile}
* @return a merged {@link DatasetProfile} with summed up columns
*/
public DatasetProfile merge(@NonNull DatasetProfile other) {
val sharedTags = ImmutableMap.<String, String>builder();
for (val tagKey : this.tags.keySet()) {
val tagValue = this.tags.get(tagKey);
if (tagValue.equals(other.tags.get(tagKey))) {
sharedTags.put(tagKey, tagValue);
}
}
return doMerge(other, sharedTags.build());
}
private DatasetProfile doMerge(@NonNull DatasetProfile other, Map<String, String> tags) {
this.validate();
other.validate();
val result =
new DatasetProfile(
this.sessionId,
this.sessionTimestamp,
this.dataTimestamp,
tags,
Collections.emptyMap());
val sharedMetadata = ImmutableMap.<String, String>builder();
for (val mKey : this.metadata.keySet()) {
val mValue = this.metadata.get(mKey);
if (mValue.equals(other.metadata.get(mKey))) {
sharedMetadata.put(mKey, mValue);
}
}
result.withAllMetadata(sharedMetadata.build());
val unionColumns = Sets.union(this.columns.keySet(), other.columns.keySet());
for (val column : unionColumns) {
val emptyColumn = new ColumnProfile(column);
val thisColumn = this.columns.getOrDefault(column, emptyColumn);
val otherColumn = other.columns.getOrDefault(column, emptyColumn);
result.columns.put(column, thisColumn.merge(otherColumn));
}
return result;
}
public DatasetProfileMessage.Builder toProtobuf() {
validate();
val properties = toDatasetProperties();
val builder = DatasetProfileMessage.newBuilder().setProperties(properties);
columns.forEach((k, v) -> builder.putColumns(k, v.toProtobuf().build()));
return builder;
}
private DatasetProperties.Builder toDatasetProperties() {
val dataTimeInMillis = (dataTimestamp == null) ? -1L : dataTimestamp.toEpochMilli();
return DatasetProperties.newBuilder()
.setSessionId(sessionId)
.setSessionTimestamp(sessionTimestamp.toEpochMilli())
.setDataTimestamp(dataTimeInMillis)
.putAllTags(tags)
.putAllMetadata(metadata)
.setSchemaMajorVersion(SchemaInformation.SCHEMA_MAJOR_VERSION)
.setSchemaMinorVersion(SchemaInformation.SCHEMA_MAJOR_VERSION);
}
public static DatasetProfile fromProtobuf(DatasetProfileMessage message) {
val props = message.getProperties();
SchemaInformation.validateSchema(props.getSchemaMajorVersion(), props.getSchemaMinorVersion());
val tags = props.getTagsMap();
val sessionTimestamp = Instant.ofEpochMilli(props.getSessionTimestamp());
val dataTimestamp =
(props.getDataTimestamp() < 0L) ? null : Instant.ofEpochMilli(props.getDataTimestamp());
val ds =
new DatasetProfile(
props.getSessionId(), sessionTimestamp, dataTimestamp, tags, Collections.emptyMap());
ds.withAllMetadata(props.getMetadataMap());
message.getColumnsMap().forEach((k, v) -> ds.columns.put(k, ColumnProfile.fromProtobuf(v)));
ds.validate();
return ds;
}
private void writeObject(ObjectOutputStream out) throws IOException {
validate();
toProtobuf().build().writeTo(out);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
val msg = DatasetProfileMessage.parseFrom(in);
final DatasetProfile copy = fromProtobuf(msg);
this.sessionId = copy.sessionId;
this.sessionTimestamp = copy.sessionTimestamp;
this.dataTimestamp = copy.dataTimestamp;
this.metadata = copy.metadata;
this.tags = copy.tags;
this.columns = copy.columns;
this.validate();
}
@Value
static class Pair {
String name;
ColumnSummary statistics;
static Pair fromColumn(ColumnProfile column) {
return new Pair(column.getColumnName(), column.toColumnSummary());
}
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/SchemaInformation.java | package com.whylogs.core;
import com.google.common.base.Preconditions;
import lombok.experimental.UtilityClass;
@UtilityClass
public class SchemaInformation {
final int SCHEMA_MAJOR_VERSION = 1;
final int SCHEMA_MINOR_VERSION = 1;
void validateSchema(int majorVersion, int minorVersion) {
Preconditions.checkArgument(
SCHEMA_MAJOR_VERSION == majorVersion,
"Expect major version %s, got %s",
SCHEMA_MAJOR_VERSION,
minorVersion);
Preconditions.checkArgument(
SCHEMA_MINOR_VERSION == minorVersion,
"Expect minor version %s, got %s",
SCHEMA_MINOR_VERSION,
minorVersion);
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/SummaryConverters.java | package com.whylogs.core;
import com.whylogs.core.message.FrequentStringsSummary;
import com.whylogs.core.message.HistogramSummary;
import com.whylogs.core.message.NumberSummary;
import com.whylogs.core.message.SchemaSummary;
import com.whylogs.core.message.StringsSummary;
import com.whylogs.core.message.UniqueCountSummary;
import com.whylogs.core.statistics.NumberTracker;
import com.whylogs.core.statistics.SchemaTracker;
import com.whylogs.core.statistics.datatypes.StringTracker;
import java.util.ArrayList;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.val;
import org.apache.datasketches.frequencies.ErrorType;
import org.apache.datasketches.frequencies.ItemsSketch;
import org.apache.datasketches.frequencies.ItemsSketch.Row;
import org.apache.datasketches.kll.KllFloatsSketch;
import org.apache.datasketches.theta.UpdateSketch;
public class SummaryConverters {
public static UniqueCountSummary fromSketch(UpdateSketch sketch) {
return UniqueCountSummary.newBuilder()
.setEstimate(sketch.getEstimate())
.setUpper(sketch.getUpperBound(1))
.setLower(sketch.getLowerBound(1))
.build();
}
public static StringsSummary fromStringTracker(StringTracker tracker) {
if (tracker == null) {
return null;
}
if (tracker.getCount() == 0) {
return null;
}
val uniqueCount = fromSketch(tracker.getThetaSketch());
val builder = StringsSummary.newBuilder().setUniqueCount(uniqueCount);
// TODO: make this value (100) configurable
if (uniqueCount.getEstimate() < 100) {
val frequentStrings = fromStringSketch(tracker.getItems());
if (frequentStrings != null) {
builder.setFrequent(frequentStrings);
}
}
return builder.build();
}
public static SchemaSummary.Builder fromSchemaTracker(SchemaTracker tracker) {
val typeCounts = tracker.getTypeCounts();
val typeCountWithNames =
typeCounts.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().name(), Entry::getValue));
return SchemaSummary.newBuilder()
.setInferredType(tracker.getInferredType())
.putAllTypeCounts(typeCountWithNames);
}
public static NumberSummary fromNumberTracker(NumberTracker numberTracker) {
if (numberTracker == null) {
return null;
}
long count = numberTracker.getVariance().getCount();
if (count == 0) {
return null;
}
double stddev = numberTracker.getVariance().stddev();
double mean, min, max;
val doubles = numberTracker.getDoubles().toProtobuf();
if (doubles.getCount() > 0) {
mean = doubles.getSum() / doubles.getCount();
min = doubles.getMin();
max = doubles.getMax();
} else {
mean = numberTracker.getLongs().getMean();
min = (double) numberTracker.getLongs().getMin();
max = (double) numberTracker.getLongs().getMax();
}
val histogram = fromUpdateDoublesSketch(numberTracker.getHistogram());
return NumberSummary.newBuilder()
.setCount(count)
.setStddev(stddev)
.setMin(min)
.setMax(max)
.setMean(mean)
.setHistogram(histogram)
.build();
}
public static FrequentStringsSummary fromStringSketch(ItemsSketch<String> sketch) {
val frequentItems = sketch.getFrequentItems(ErrorType.NO_FALSE_NEGATIVES);
if (frequentItems.length == 0) {
return null;
}
val result =
Stream.of(frequentItems)
.map(SummaryConverters::toFrequentItem)
.collect(Collectors.toList());
return FrequentStringsSummary.newBuilder().addAllItems(result).build();
}
private static FrequentStringsSummary.FrequentItem toFrequentItem(Row<String> row) {
return FrequentStringsSummary.FrequentItem.newBuilder()
.setValue(row.getItem())
.setEstimate(row.getEstimate())
.build();
}
public static HistogramSummary fromUpdateDoublesSketch(KllFloatsSketch sketch) {
val n = sketch.getN();
float start = sketch.getMinValue();
float end = sketch.getMaxValue();
val builder = HistogramSummary.newBuilder().setStart(start).setEnd(end);
// try to be smart here. We don't really have a "histogram"
// if there are too few data points or there's no band
if (n < 2 || start == end) {
val longs = new ArrayList<Long>();
for (int i = 0; i < n; i++) {
longs.add(0L);
}
return builder.setWidth(0).addAllCounts(longs).build();
}
int numberOfBuckets = (int) Math.min(Math.ceil(n / 4.0), 100);
val width = (end - start) / (numberOfBuckets * 1.0f);
builder.setWidth(width);
// calculate histograms from PMF
val splitPoints = new float[numberOfBuckets];
for (int i = 0; i < numberOfBuckets; i++) {
splitPoints[i] = start + i * width;
}
val pmf = sketch.getPMF(splitPoints);
int len = pmf.length - 1;
for (int i = 0; i < len; i++) {
builder.addCounts(Math.round(pmf[i] * sketch.getN()));
}
return builder.build();
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/datetime/DateTimeFormatParser.java | package com.whylogs.core.datetime;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.MonthDay;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.val;
class DateTimeFormatParser<TIME_FORMAT extends TemporalAccessor> {
private final Class<TIME_FORMAT> timeFormat;
private final BiFunction<DateTimeFormatter, String, Instant> function;
public DateTimeFormatParser(
Class<TIME_FORMAT> timeFormat, BiFunction<DateTimeFormatter, String, Instant> function) {
this.timeFormat = timeFormat;
this.function = function;
}
public Class<TIME_FORMAT> getTimeFormatClass() {
return timeFormat;
}
public Instant parse(DateTimeFormatter formatter, String input) {
return function.apply(formatter, input);
}
static final DateTimeFormatParser<ZonedDateTime> ZONED_DATETIME =
new DateTimeFormatParser<>(
ZonedDateTime.class,
(dateTimeFormatter, input) -> {
val dateTime = ZonedDateTime.parse(input, dateTimeFormatter);
return dateTime.toInstant();
});
static final DateTimeFormatParser<LocalDateTime> LOCAL_DATETIME =
new DateTimeFormatParser<>(
LocalDateTime.class,
(dateTimeFormatter, input) -> {
val dateTime = LocalDateTime.parse(input, dateTimeFormatter);
return dateTime.atZone(ZoneOffset.UTC).toInstant();
});
static final DateTimeFormatParser<LocalTime> LOCAL_TIME =
new DateTimeFormatParser<>(
LocalTime.class,
(dateTimeFormatter, input) -> {
val dateTime = LocalTime.parse(input, dateTimeFormatter);
return dateTime.atDate(LocalDate.now()).atZone(ZoneOffset.UTC).toInstant();
});
static final DateTimeFormatParser<MonthDay> MONTH_DAY =
new DateTimeFormatParser<>(
MonthDay.class,
(dateTimeFormatter, input) -> {
val dateTime = MonthDay.parse(input, dateTimeFormatter);
val currentYear = Year.now().getValue();
return dateTime.atYear(currentYear).atStartOfDay().atZone(ZoneOffset.UTC).toInstant();
});
static final DateTimeFormatParser<LocalDate> LOCAL_DATE =
new DateTimeFormatParser<>(
LocalDate.class,
(dateTimeFormatter, input) -> {
val dateTime = LocalDate.parse(input, dateTimeFormatter);
return dateTime.atStartOfDay().atZone(ZoneOffset.UTC).toInstant();
});
static final DateTimeFormatParser<YearMonth> YEAR_MONTH =
new DateTimeFormatParser<>(
YearMonth.class,
(dateTimeFormatter, input) -> {
val dateTime = YearMonth.parse(input, dateTimeFormatter);
return dateTime.atDay(1).atStartOfDay().atZone(ZoneOffset.UTC).toInstant();
});
static final DateTimeFormatParser<Year> YEAR =
new DateTimeFormatParser<>(
Year.class,
(dateTimeFormatter, input) -> {
val dateTime = Year.parse(input, dateTimeFormatter);
return dateTime.atMonth(1).atDay(1).atStartOfDay().atZone(ZoneOffset.UTC).toInstant();
});
static final DateTimeFormatParser<Instant> EPOCH_SECONDS =
new DateTimeFormatParser<>(
Instant.class,
(dateTimeFormatter, input) -> {
try {
return Instant.ofEpochSecond(Long.parseLong(input));
} catch (NumberFormatException e) {
throw new DateTimeParseException("Invalid number format", input, 0, e);
}
});
static final DateTimeFormatParser<Instant> EPOCH_MILLISECONDS =
new DateTimeFormatParser<>(
Instant.class,
(dateTimeFormatter, input) -> {
try {
return Instant.ofEpochMilli(Long.parseLong(input));
} catch (NumberFormatException e) {
throw new DateTimeParseException("Invalid number format", input, 0, e);
}
});
static final Set<Class<?>> SUPPORT_TIME_CLASSES =
Stream.of(
ZONED_DATETIME,
LOCAL_DATE,
LOCAL_TIME,
MONTH_DAY,
LOCAL_DATE,
YEAR_MONTH,
YEAR,
EPOCH_SECONDS,
EPOCH_MILLISECONDS)
.map(DateTimeFormatParser::getTimeFormatClass)
.collect(Collectors.toSet());
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/datetime/EasyDateTimeParser.java | package com.whylogs.core.datetime;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Locale;
import lombok.val;
public class EasyDateTimeParser {
public static final String EPOCH_SECONDS_FORMAT = "epoch";
public static final String EPOCH_MILLIS_FORMAT = "epochMillis";
public static final Instant BEGINNING_OF_TIME = Instant.ofEpochMilli(0);
private final DateTimeFormatter dateTimeFormatter;
private volatile DateTimeFormatParser<?> parser;
public EasyDateTimeParser(String format) {
if (EPOCH_SECONDS_FORMAT.equalsIgnoreCase(format)) {
this.dateTimeFormatter = null;
this.parser = DateTimeFormatParser.EPOCH_SECONDS;
} else if (EPOCH_MILLIS_FORMAT.equalsIgnoreCase(format)) {
this.dateTimeFormatter = null;
this.parser = DateTimeFormatParser.EPOCH_MILLISECONDS;
} else {
this.dateTimeFormatter = DateTimeFormatter.ofPattern(format).withLocale(Locale.ENGLISH);
}
}
public Instant parse(String input) {
if (input == null
|| "nan".equalsIgnoreCase(input)
|| "null".equalsIgnoreCase(input)
|| "".equalsIgnoreCase(input)) {
return BEGINNING_OF_TIME;
}
if (this.parser == null) {
return this.calculateFormat(input);
} else {
return this.parser.parse(dateTimeFormatter, input);
}
}
private Instant calculateFormat(String firstInput) {
val parsed = dateTimeFormatter.parse(firstInput);
val hasYear = parsed.isSupported(ChronoField.YEAR);
val hasMonth = parsed.isSupported(ChronoField.MONTH_OF_YEAR);
val hasDayOfMonth = parsed.isSupported(ChronoField.DAY_OF_MONTH);
val hasHourOfDay = parsed.isSupported(ChronoField.HOUR_OF_DAY);
if (hasHourOfDay) {
if (hasYear && hasMonth && hasDayOfMonth) {
if (dateTimeFormatter.getZone() != null) {
this.parser = DateTimeFormatParser.ZONED_DATETIME;
} else {
this.parser = DateTimeFormatParser.LOCAL_DATETIME;
}
} else if (!hasYear && !hasMonth && !hasDayOfMonth) {
this.parser = DateTimeFormatParser.LOCAL_TIME;
}
} else if (hasYear && hasMonth & hasDayOfMonth) {
this.parser = DateTimeFormatParser.LOCAL_DATE;
} else if (!hasYear && hasMonth && hasDayOfMonth) {
this.parser = DateTimeFormatParser.MONTH_DAY;
} else if (hasYear && hasMonth) {
this.parser = DateTimeFormatParser.YEAR_MONTH;
} else if (hasYear) {
this.parser = DateTimeFormatParser.YEAR;
}
if (this.parser == null) {
throw new RuntimeException(
"Failed to match supported format. Supported format: "
+ DateTimeFormatParser.SUPPORT_TIME_CLASSES);
}
try {
return this.parse(firstInput);
} catch (Exception e) {
throw new RuntimeException(
"The determined formatter failed to parse the input. Supported format: "
+ DateTimeFormatParser.SUPPORT_TIME_CLASSES,
e);
}
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/iterator/ColumnsChunkSegmentIterator.java | package com.whylogs.core.iterator;
import com.whylogs.core.message.ColumnMessage;
import com.whylogs.core.message.ColumnsChunkSegment;
import java.util.Iterator;
import java.util.NoSuchElementException;
import lombok.val;
public class ColumnsChunkSegmentIterator implements Iterator<ColumnsChunkSegment> {
private static final int MAX_LEN_IN_BYTES = 1_000_000 - 10; // 1MB for each message
private final int maxChunkLength;
private final Iterator<ColumnMessage> iterator;
private final ColumnsChunkSegment.Builder builder;
private int contentLength;
private int numberOfColumns;
public ColumnsChunkSegmentIterator(Iterator<ColumnMessage> iterator, String marker) {
this(MAX_LEN_IN_BYTES, iterator, marker);
}
ColumnsChunkSegmentIterator(int maxChunkLength, Iterator<ColumnMessage> iterator, String marker) {
this.maxChunkLength = maxChunkLength;
this.iterator = iterator;
this.builder = ColumnsChunkSegment.newBuilder().setMarker(marker);
this.contentLength = 0;
this.numberOfColumns = 0;
}
@Override
public boolean hasNext() {
if (this.numberOfColumns > 0) {
return true;
}
return iterator.hasNext();
}
@Override
public ColumnsChunkSegment next() {
while (iterator.hasNext()) {
final ColumnMessage columnMessage = iterator.next();
// TODO: handle the case if messageLen > baselength
val messageLen = columnMessage.getSerializedSize();
val candidateContentSize = contentLength + messageLen;
val canItemBeAppended = candidateContentSize <= maxChunkLength;
if (canItemBeAppended) {
builder.addColumns(columnMessage);
this.numberOfColumns++;
contentLength = candidateContentSize;
} else {
val result = builder.build();
builder.clearColumns();
builder.addColumns(columnMessage);
this.numberOfColumns = 1;
contentLength = messageLen;
return result;
}
}
if (this.numberOfColumns > 0) {
val result = builder.build();
this.builder.clearColumns();
this.contentLength = 0;
this.numberOfColumns = 0;
return result;
}
throw new NoSuchElementException();
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics/CountersTracker.java | package com.whylogs.core.statistics;
import com.google.protobuf.Int64Value;
import com.whylogs.core.message.Counters;
import java.util.Optional;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import lombok.val;
@EqualsAndHashCode
@Getter
@FieldDefaults(level = AccessLevel.PRIVATE)
public class CountersTracker {
long count;
long trueCount;
long nullCount;
public void incrementCount() {
count++;
}
public void incrementTrue() {
trueCount++;
}
public void incrementNull() {
nullCount++;
}
public void add(CountersTracker other) {
this.count += other.count;
this.trueCount += other.trueCount;
this.nullCount += other.nullCount;
}
public CountersTracker merge(CountersTracker other) {
val result = new CountersTracker();
result.count = this.count + other.count;
result.trueCount = this.trueCount + other.trueCount;
result.nullCount = this.nullCount + other.nullCount;
return result;
}
public Counters.Builder toProtobuf() {
val countersBuilder = Counters.newBuilder().setCount(count);
if (trueCount > 0) {
countersBuilder.setTrueCount(Int64Value.of(trueCount));
}
if (nullCount > 0) {
countersBuilder.setTrueCount(Int64Value.of(nullCount));
}
return countersBuilder;
}
public static CountersTracker fromProtobuf(Counters message) {
val tracker = new CountersTracker();
tracker.count = message.getCount();
tracker.trueCount =
Optional.ofNullable(message.getTrueCount()).map(Int64Value::getValue).orElse(0L);
tracker.nullCount =
Optional.ofNullable(message.getNullCount()).map(Int64Value::getValue).orElse(0L);
return tracker;
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics/NumberTracker.java | package com.whylogs.core.statistics;
import com.google.protobuf.ByteString;
import com.whylogs.core.message.NumbersMessage;
import com.whylogs.core.statistics.datatypes.DoubleTracker;
import com.whylogs.core.statistics.datatypes.LongTracker;
import com.whylogs.core.statistics.datatypes.VarianceTracker;
import java.util.Optional;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.val;
import org.apache.datasketches.kll.KllFloatsSketch;
import org.apache.datasketches.memory.Memory;
@Getter
@Builder(setterPrefix = "set")
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class NumberTracker {
// our own trackers
VarianceTracker variance;
DoubleTracker doubles;
LongTracker longs;
// sketches
KllFloatsSketch histogram; // histogram
public NumberTracker() {
this.variance = new VarianceTracker();
this.doubles = new DoubleTracker();
this.longs = new LongTracker();
this.histogram = new KllFloatsSketch(256);
}
public void track(Number number) {
float dValue = number.floatValue();
variance.update(dValue);
histogram.update(dValue);
if (doubles.getCount() > 0) {
doubles.update(dValue);
} else if (number instanceof Long || number instanceof Integer) {
longs.update(number.longValue());
} else {
doubles.addLongs(longs);
longs.reset();
doubles.update(dValue);
}
}
public void add(NumberTracker other) {
if (other == null) {
return;
}
this.variance.add(other.variance);
this.doubles.add(other.doubles);
this.longs.add(other.longs);
this.histogram.merge(other.histogram);
}
public NumberTracker merge(NumberTracker other) {
if (other == null) {
return this;
}
val unionHistogram = KllFloatsSketch.heapify(Memory.wrap(this.histogram.toByteArray()));
unionHistogram.merge(other.histogram);
return NumberTracker.builder()
.setVariance(this.variance.merge(other.variance))
.setDoubles(this.doubles.merge(other.doubles))
.setLongs(this.longs.merge(other.longs))
.setHistogram(unionHistogram)
.build();
}
public NumbersMessage.Builder toProtobuf() {
val builder =
NumbersMessage.newBuilder()
.setVariance(variance.toProtobuf())
.setHistogram(ByteString.copyFrom(histogram.toByteArray()));
if (this.doubles.getCount() > 0) {
builder.setDoubles(this.doubles.toProtobuf());
} else if (this.longs.getCount() > 0) {
builder.setLongs(this.longs.toProtobuf());
}
return builder;
}
public static NumberTracker fromProtobuf(NumbersMessage message) {
val hMem = Memory.wrap(message.getHistogram().toByteArray());
val builder =
NumberTracker.builder()
.setHistogram(KllFloatsSketch.heapify(hMem))
.setVariance(VarianceTracker.fromProtobuf(message.getVariance()));
Optional.ofNullable(message.getDoubles())
.map(DoubleTracker::fromProtobuf)
.ifPresent(builder::setDoubles);
Optional.ofNullable(message.getLongs())
.map(LongTracker::fromProtobuf)
.ifPresent(builder::setLongs);
return builder.build();
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics/SchemaTracker.java | package com.whylogs.core.statistics;
import com.google.common.collect.Maps;
import com.whylogs.core.message.InferredType;
import com.whylogs.core.message.SchemaMessage;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.val;
@EqualsAndHashCode
@RequiredArgsConstructor
public class SchemaTracker {
private static final InferredType.Builder UNKNOWN_TYPE_BUILDER =
InferredType.newBuilder().setType(InferredType.Type.UNKNOWN);
private final Map<InferredType.Type, Long> typeCounts;
public SchemaTracker() {
this.typeCounts = new HashMap<>(InferredType.Type.values().length, 1.0f);
}
public void track(InferredType.Type type) {
typeCounts.merge(type, 1L, Long::sum);
}
long getCount(InferredType.Type type) {
return typeCounts.getOrDefault(type, 0L);
}
public Map<InferredType.Type, Long> getTypeCounts() {
return Collections.unmodifiableMap(typeCounts);
}
public InferredType getInferredType() {
val totalCount = typeCounts.values().stream().mapToLong(Long::longValue).sum();
if (totalCount == 0) {
return UNKNOWN_TYPE_BUILDER.build();
}
// first figure out the most popular type and its count
val candidate = getMostPopularType(totalCount);
if (candidate.getRatio() > 0.7) {
return candidate.build();
}
// integral is a subset of fractional
val fractionalCount =
Stream.of(InferredType.Type.INTEGRAL, InferredType.Type.FRACTIONAL)
.mapToLong(type -> typeCounts.getOrDefault(type, 0L))
.sum();
// Handling String case first
// it has to have more entries than fractional values
val candidateType = candidate.getType();
if (candidateType == InferredType.Type.STRING
&& typeCounts.get(InferredType.Type.STRING) > fractionalCount) {
// treat everything else as "String" except UNKNOWN
val coercedCount =
Stream.of(
InferredType.Type.STRING,
InferredType.Type.INTEGRAL,
InferredType.Type.FRACTIONAL,
InferredType.Type.BOOLEAN)
.mapToLong(type -> typeCounts.getOrDefault(type, 0L))
.sum();
val actualRatio = coercedCount / (double) totalCount;
return InferredType.newBuilder()
.setType(InferredType.Type.STRING)
.setRatio(actualRatio)
.build();
}
// if not string but another type with majority
if (candidate.getRatio() > 0.5) {
long actualCount = typeCounts.get(candidateType);
if (candidateType == InferredType.Type.FRACTIONAL) {
actualCount = fractionalCount;
}
return InferredType.newBuilder()
.setType(candidateType)
.setRatio(actualCount / (double) totalCount)
.build();
}
// Otherwise, if fractional count is the majority, then likely this is a fractional type
final double fractionalRatio = fractionalCount / (double) totalCount;
if (fractionalRatio > 0.5) {
return InferredType.newBuilder()
.setType(InferredType.Type.FRACTIONAL)
.setRatio(fractionalRatio)
.build();
}
// we can't infer any type
return InferredType.newBuilder().setType(InferredType.Type.UNKNOWN).setRatio(1.0).build();
}
public SchemaMessage.Builder toProtobuf() {
val protobufFriendlyMap =
typeCounts.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().getNumber(), Entry::getValue));
return SchemaMessage.newBuilder().putAllTypeCounts(protobufFriendlyMap);
}
public static SchemaTracker fromProtobuf(SchemaMessage message) {
val schemaTracker = new SchemaTracker();
message
.getTypeCountsMap()
.forEach((k, v) -> schemaTracker.typeCounts.put(InferredType.Type.forNumber(k), v));
return schemaTracker;
}
private InferredType.Builder getMostPopularType(long totalCount) {
val mostPopularType =
typeCounts.entrySet().stream()
.max((e1, e2) -> (int) (e1.getValue() - e2.getValue()))
.map(Entry::getKey)
.orElse(InferredType.Type.UNKNOWN);
val count = typeCounts.getOrDefault(mostPopularType, 0L);
val ratio = count * 1.0 / totalCount;
return InferredType.newBuilder().setType(mostPopularType).setRatio(ratio);
}
public void add(SchemaTracker other) {
final InferredType.Type[] allTypes = InferredType.Type.values();
for (val type : allTypes) {
if (this.typeCounts.containsKey(type) || other.typeCounts.containsKey(type)) {
this.typeCounts.merge(type, other.getCount(type), Long::sum);
}
}
}
public SchemaTracker merge(SchemaTracker other) {
val thisCopy = new SchemaTracker(Maps.newHashMap(typeCounts));
final InferredType.Type[] allTypes = InferredType.Type.values();
for (val type : allTypes) {
if (this.typeCounts.containsKey(type) || other.typeCounts.containsKey(type)) {
thisCopy.typeCounts.merge(type, other.getCount(type), Long::sum);
}
}
return thisCopy;
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics/datatypes/DoubleTracker.java | package com.whylogs.core.statistics.datatypes;
import com.whylogs.core.message.DoublesMessage;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.val;
@Getter
@EqualsAndHashCode
@ToString
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class DoubleTracker {
private double min;
private double max;
private double sum;
private long count;
public DoubleTracker() {
this.min = Double.MAX_VALUE;
this.max = -Double.MAX_VALUE;
this.sum = 0;
this.count = 0;
}
public void addLongs(LongTracker longs) {
if (longs != null && longs.getCount() != 0) {
this.min = longs.getMin();
this.max = longs.getMax();
this.sum = longs.getSum();
this.count = longs.getCount();
}
}
public double getMean() {
return sum / count;
}
public void update(double value) {
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
count++;
sum += value;
}
public void add(DoubleTracker other) {
if (other == null) {
return;
}
if (other.min < this.min) {
this.min = other.min;
}
if (other.max > this.max) {
this.max = other.max;
}
this.sum += other.sum;
this.count += other.count;
}
public DoubleTracker merge(DoubleTracker other) {
val thisCopy = new DoubleTracker(min, max, sum, count);
thisCopy.add(other);
return thisCopy;
}
public DoublesMessage.Builder toProtobuf() {
return DoublesMessage.newBuilder().setCount(count).setSum(sum).setMin(min).setMax(max);
}
public static DoubleTracker fromProtobuf(DoublesMessage message) {
val tracker = new DoubleTracker();
tracker.count = message.getCount();
tracker.max = message.getMax();
tracker.min = message.getMin();
tracker.sum = message.getSum();
return tracker;
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics/datatypes/LongTracker.java | package com.whylogs.core.statistics.datatypes;
import com.whylogs.core.message.LongsMessage;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.val;
@Getter
@EqualsAndHashCode
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class LongTracker {
private long min;
private long max;
private long sum;
private long count;
public LongTracker() {
reset();
}
public Double getMean() {
if (count == 0) {
return null;
} else {
return sum / (double) count;
}
}
public void update(long value) {
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
count++;
sum += value;
}
public void add(LongTracker other) {
if (other == null) {
return;
}
if (other.min < this.min) {
this.min = other.min;
}
if (other.max > this.max) {
this.max = other.max;
}
this.sum += other.sum;
this.count += other.count;
}
public LongTracker merge(LongTracker other) {
val thisCopy = new LongTracker(min, max, sum, count);
thisCopy.add(other);
return thisCopy;
}
public void reset() {
min = Long.MAX_VALUE;
max = Long.MIN_VALUE;
sum = 0;
count = 0;
}
public LongsMessage.Builder toProtobuf() {
return LongsMessage.newBuilder().setCount(count).setSum(sum).setMin(min).setMax(max);
}
public static LongTracker fromProtobuf(LongsMessage message) {
val tracker = new LongTracker();
tracker.count = message.getCount();
tracker.max = message.getMax();
tracker.min = message.getMin();
tracker.sum = message.getSum();
return tracker;
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics/datatypes/StringTracker.java | package com.whylogs.core.statistics.datatypes;
import com.google.protobuf.ByteString;
import com.whylogs.core.message.StringsMessage;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.val;
import org.apache.datasketches.ArrayOfStringsSerDe;
import org.apache.datasketches.frequencies.ItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.theta.Union;
import org.apache.datasketches.theta.UpdateSketch;
@Builder
@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public final class StringTracker {
public static final ArrayOfStringsSerDe ARRAY_OF_STRINGS_SER_DE = new ArrayOfStringsSerDe();
// be careful to not use 32 here - somehow the sketches are empty
public static final int MAX_FREQUENT_ITEM_SIZE = 128;
private long count;
// sketches
private final ItemsSketch<String> items;
private final UpdateSketch thetaSketch;
public StringTracker() {
this.count = 0L;
this.items = new ItemsSketch<>(MAX_FREQUENT_ITEM_SIZE); // TODO: make this value configurable
this.thetaSketch = UpdateSketch.builder().build();
}
public void update(String value) {
if (value == null) {
return;
}
count++;
thetaSketch.update(value);
items.update(value);
}
/**
* Merge this StringTracker object with another. This merges the sketches as well
*
* @param other the other String tracker to merge
* @return a new StringTracker object
*/
public StringTracker merge(StringTracker other) {
val bytes = this.items.toByteArray(ARRAY_OF_STRINGS_SER_DE);
val itemsCopy = ItemsSketch.getInstance(WritableMemory.wrap(bytes), ARRAY_OF_STRINGS_SER_DE);
itemsCopy.merge(other.items);
val thetaUnion = Union.builder().buildUnion();
thetaUnion.update(this.thetaSketch);
thetaUnion.update(other.thetaSketch);
val thetaSketch = UpdateSketch.heapify(WritableMemory.wrap(thetaUnion.toByteArray()));
return new StringTracker(this.count + other.count, itemsCopy, thetaSketch);
}
public StringsMessage.Builder toProtobuf() {
return StringsMessage.newBuilder()
.setCount(count)
.setItems(ByteString.copyFrom(items.toByteArray(ARRAY_OF_STRINGS_SER_DE)))
.setTheta(ByteString.copyFrom(thetaSketch.toByteArray()));
}
public static StringTracker fromProtobuf(StringsMessage message) {
val iMem = Memory.wrap(message.getItems().toByteArray());
val items = ItemsSketch.getInstance(iMem, ARRAY_OF_STRINGS_SER_DE);
val tMem = WritableMemory.wrap(message.getTheta().toByteArray());
val theta = UpdateSketch.heapify(tMem);
return StringTracker.builder()
.count(message.getCount())
.items(items)
.thetaSketch(theta)
.build();
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/statistics/datatypes/VarianceTracker.java | package com.whylogs.core.statistics.datatypes;
import com.whylogs.core.message.VarianceMessage;
import lombok.Getter;
import lombok.val;
@Getter
public class VarianceTracker {
long count;
double sum; // sample variance * (n-1)
double mean;
public VarianceTracker() {
this.count = 0L;
this.sum = 0L;
this.mean = 0L;
}
// Based on
// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
public void update(double newValue) {
count++;
double delta = newValue - mean;
mean += delta / count;
double delta2 = newValue - mean;
sum += delta * delta2;
}
/** @return sample standard deviation */
public double stddev() {
return Math.sqrt(this.variance());
}
/** @return the sample variance */
public double variance() {
if (count < 2) {
return Double.NaN;
}
return sum / (count - 1.0);
}
/** https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm */
public void add(VarianceTracker other) {
if (other == null || other.count == 0L) {
return;
}
if (this.count == 0L) {
this.count = other.count;
this.mean = other.mean;
this.sum = other.sum;
return;
}
val delta = this.mean - other.mean;
val totalCount = this.count + other.count;
this.sum += other.sum + Math.pow(delta, 2) * this.count * other.count / (double) totalCount;
val thisRatio = this.count / (double) totalCount;
val otherRatio = 1.0 - thisRatio;
this.mean = this.mean * thisRatio + other.mean * otherRatio;
this.count += other.count;
}
public VarianceTracker merge(VarianceTracker other) {
final VarianceTracker thisCopy = this.copy();
thisCopy.add(other);
return thisCopy;
}
VarianceTracker copy() {
val result = new VarianceTracker();
result.count = this.count;
result.sum = this.sum;
result.mean = this.mean;
return result;
}
public VarianceMessage.Builder toProtobuf() {
return VarianceMessage.newBuilder().setCount(count).setMean(mean).setSum(sum);
}
public static VarianceTracker fromProtobuf(VarianceMessage message) {
final VarianceTracker tracker = new VarianceTracker();
tracker.count = message.getCount();
tracker.mean = message.getMean();
tracker.sum = message.getSum();
return tracker;
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/types/TypedData.java | package com.whylogs.core.types;
import com.whylogs.core.message.InferredType;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.NonNull;
import lombok.Value;
@Value
@Builder(setterPrefix = "set", access = AccessLevel.PRIVATE)
public class TypedData {
private static final TypedData UNKNOWN_INSTANCE =
TypedData.builder().setType(InferredType.Type.UNKNOWN).build();
private static final TypedData BOOLEAN_TRUE_INSTANCE =
TypedData.builder().setType(InferredType.Type.BOOLEAN).setBooleanValue(true).build();
private static final TypedData BOOLEAN_FALSE_INSTANCE =
TypedData.builder().setType(InferredType.Type.BOOLEAN).setBooleanValue(false).build();
@NonNull InferredType.Type type;
boolean booleanValue;
long integralValue;
double fractional;
String stringValue;
public static TypedData booleanValue(boolean booleanValue) {
if (booleanValue) {
return BOOLEAN_TRUE_INSTANCE;
} else {
return BOOLEAN_FALSE_INSTANCE;
}
}
public static TypedData stringValue(String stringValue) {
return TypedData.builder()
.setType(InferredType.Type.STRING)
.setStringValue(stringValue)
.build();
}
public static TypedData integralValue(long integralValue) {
return TypedData.builder()
.setType(InferredType.Type.INTEGRAL)
.setIntegralValue(integralValue)
.build();
}
public static TypedData fractionalValue(double fractionalValue) {
return TypedData.builder()
.setType(InferredType.Type.FRACTIONAL)
.setFractional(fractionalValue)
.build();
}
public static TypedData unknownValue() {
// we don't track "unknown" since we can't track any statistics
return UNKNOWN_INSTANCE;
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/types/TypedDataConverter.java | package com.whylogs.core.types;
import static java.util.stream.Collectors.toSet;
import com.whylogs.core.message.InferredType;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import lombok.experimental.UtilityClass;
import lombok.val;
@UtilityClass
public class TypedDataConverter {
public static final Set<InferredType.Type> NUMERIC_TYPES =
Stream.of(InferredType.Type.FRACTIONAL, InferredType.Type.INTEGRAL).collect(toSet());
private final Pattern FRACTIONAL = Pattern.compile("^[-+]? ?\\d+[.]\\d+$");
private final Pattern INTEGRAL = Pattern.compile("^[-+]? ?\\d+$");
private final Pattern BOOLEAN = Pattern.compile("^(?i)true|false$");
private final Pattern EMPTY_SPACES = Pattern.compile("\\s");
private final ThreadLocal<Matcher> FRACTIONAL_MATCHER =
ThreadLocal.withInitial(() -> FRACTIONAL.matcher(""));
private final ThreadLocal<Matcher> INTEGRAL_MATCHER =
ThreadLocal.withInitial(() -> INTEGRAL.matcher(""));
private final ThreadLocal<Matcher> BOOLEAN_MATCHER =
ThreadLocal.withInitial(() -> BOOLEAN.matcher(""));
private final ThreadLocal<Matcher> EMPTY_SPACES_REMOVER =
ThreadLocal.withInitial(() -> EMPTY_SPACES.matcher(""));
public TypedData convert(Object data) {
if (data == null) {
return null;
}
if (data instanceof String) {
val strData = (String) data;
INTEGRAL_MATCHER.get().reset(strData);
if (INTEGRAL_MATCHER.get().matches()) {
val trimmedText = EMPTY_SPACES_REMOVER.get().reset(strData).replaceAll("");
return TypedData.integralValue(Long.parseLong(trimmedText));
}
FRACTIONAL_MATCHER.get().reset(strData);
if (FRACTIONAL_MATCHER.get().matches()) {
val trimmedText = EMPTY_SPACES_REMOVER.get().reset(strData).replaceAll("");
return TypedData.fractionalValue(Double.parseDouble(trimmedText));
}
BOOLEAN_MATCHER.get().reset(strData);
if (BOOLEAN_MATCHER.get().matches()) {
val trimmedText = EMPTY_SPACES_REMOVER.get().reset(strData).replaceAll("");
return TypedData.booleanValue(Boolean.parseBoolean(trimmedText));
}
return TypedData.stringValue(strData);
}
if (data instanceof Double || data instanceof Float) {
final double doubleValue = ((Number) data).doubleValue();
return TypedData.fractionalValue(doubleValue);
}
if (data instanceof Integer || data instanceof Long || data instanceof Short) {
final long longValue = ((Number) data).longValue();
return TypedData.integralValue(longValue);
}
if (data instanceof Boolean) {
return TypedData.booleanValue((boolean) data);
}
return TypedData.unknownValue();
}
}
|
0 | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core | java-sources/ai/whylabs/whylogs-core/0.1.1/com/whylogs/core/utils/ProtobufHelper.java | package com.whylogs.core.utils;
import com.whylogs.core.message.DatasetSummary;
import java.time.Instant;
import java.util.stream.Collectors;
import lombok.experimental.UtilityClass;
import lombok.val;
@SuppressWarnings("unused")
@UtilityClass
public class ProtobufHelper {
public String summaryToString(DatasetSummary summary) {
val name = summary.getProperties().getSessionId();
val tags =
summary.getProperties().getTagsMap().entrySet().stream()
.map(entry -> String.format("%s:%s", entry.getKey(), entry.getValue()))
.collect(Collectors.joining(","));
val timestamp = Instant.ofEpochMilli(summary.getProperties().getSessionTimestamp()).toString();
val columns = summary.getColumnsMap().keySet();
return String.format(
"Name: %s. Tags: %s. Timestamp: %s. Columns: %s", name, tags, timestamp, columns);
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/ColumnProfile.java | package com.whylogs.core;
import static com.whylogs.core.SummaryConverters.fromSchemaTracker;
import static com.whylogs.core.statistics.datatypes.StringTracker.ARRAY_OF_STRINGS_SER_DE;
import static com.whylogs.core.types.TypedDataConverter.NUMERIC_TYPES;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.protobuf.ByteString;
import com.whylogs.core.message.ColumnMessage;
import com.whylogs.core.message.ColumnSummary;
import com.whylogs.core.message.HllSketchMessage;
import com.whylogs.core.message.InferredType;
import com.whylogs.core.statistics.CountersTracker;
import com.whylogs.core.statistics.NumberTracker;
import com.whylogs.core.statistics.SchemaTracker;
import com.whylogs.core.statistics.datatypes.StringTracker;
import com.whylogs.core.types.TypedData;
import com.whylogs.core.types.TypedDataConverter;
import com.whylogs.core.utils.sketches.FrequentStringsSketch;
import javax.annotation.Nullable;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.val;
import org.apache.datasketches.frequencies.ItemsSketch;
import org.apache.datasketches.hll.HllSketch;
import org.apache.datasketches.hll.Union;
import org.apache.datasketches.memory.Memory;
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
@Builder(setterPrefix = "set")
public class ColumnProfile {
public static final int FREQUENT_MAX_LG_K = 7;
private static final int CARDINALITY_LG_K = 12;
public static final int STRING_LENGTH_MAX = 256;
private static volatile ImmutableSet<String> NULL_STR_ENVS;
@NonNull private final String columnName;
@NonNull private final CountersTracker counters;
@NonNull private final SchemaTracker schemaTracker;
@NonNull private final NumberTracker numberTracker;
@NonNull private final ItemsSketch<String> frequentItems;
@NonNull private final HllSketch cardinalityTracker;
@NonNull private final ImmutableSet<String> nullStrs;
@NonNull private final StringTracker stringTracker;
static ImmutableSet<String> nullStrsFromEnv() {
if (ColumnProfile.NULL_STR_ENVS == null) {
val nullSpec = System.getenv("NULL_STRINGS");
ColumnProfile.NULL_STR_ENVS =
nullSpec == null ? ImmutableSet.of() : ImmutableSet.copyOf(nullSpec.split(","));
}
return ColumnProfile.NULL_STR_ENVS;
}
public ColumnProfile(String columnName) {
this(columnName, nullStrsFromEnv());
}
public ColumnProfile(String columnName, ImmutableSet<String> nullStrs) {
this.columnName = columnName;
this.counters = new CountersTracker();
this.schemaTracker = new SchemaTracker();
this.stringTracker = new StringTracker();
this.numberTracker = new NumberTracker();
this.frequentItems = FrequentStringsSketch.create();
this.cardinalityTracker = new HllSketch(CARDINALITY_LG_K);
this.nullStrs = nullStrs;
}
public void track(Object value) {
synchronized (this) {
counters.incrementCount();
// TODO: ignore this if we already know the data type
val typedData = TypedDataConverter.convert(value);
if (isNull(typedData)) {
schemaTracker.track(InferredType.Type.NULL);
return;
}
schemaTracker.track(typedData.getType());
switch (typedData.getType()) {
case FRACTIONAL:
final double fractional = typedData.getFractional();
trackText(String.valueOf(fractional));
numberTracker.track(fractional);
break;
case INTEGRAL:
final long integralValue = typedData.getIntegralValue();
trackText(String.valueOf(integralValue));
numberTracker.track(integralValue);
break;
case BOOLEAN:
// TODO: handle boolean across languages? Python booleans are "True" vs Java "true"
trackText(String.valueOf(typedData.isBooleanValue()));
if (typedData.isBooleanValue()) {
counters.incrementTrue();
}
break;
case STRING:
final String stringValue = typedData.getStringValue();
// trackText is the older tracking code. It limits the length of strings in order to
// track cardinality.
trackText(stringValue);
// string tracking does not limit the length of input text.
stringTracker.update(stringValue);
}
}
}
private boolean isNull(TypedData value) {
if (value == null) return true;
if (value.getType() == InferredType.Type.STRING && !this.nullStrs.isEmpty()) {
return this.nullStrs.contains(value.getStringValue());
}
if (value.getType() == InferredType.Type.FRACTIONAL) {
return Double.isNaN(value.getFractional()) || Double.isInfinite(value.getFractional());
}
return false;
}
private void trackText(String text) {
if (text != null && text.length() > STRING_LENGTH_MAX) {
text = text.substring(0, STRING_LENGTH_MAX);
}
frequentItems.update(text);
cardinalityTracker.update(text);
}
public ColumnSummary toColumnSummary() {
val schema = fromSchemaTracker(schemaTracker);
val builder = ColumnSummary.newBuilder().setCounters(counters.toProtobuf());
if (schema != null) {
builder.setSchema(schema);
if (NUMERIC_TYPES.contains(schema.getInferredType().getType())) {
val stringsSummary = SummaryConverters.fromStringTracker(this.stringTracker);
val numberSummary = SummaryConverters.fromNumberTracker(this.numberTracker);
if (numberSummary != null) {
builder.setNumberSummary(numberSummary);
}
}
}
return builder.build();
}
public ColumnProfile merge(ColumnProfile other) {
return this.merge(other, true);
}
public ColumnProfile merge(ColumnProfile other, boolean checkName) {
if (checkName) {
Preconditions.checkArgument(
this.columnName.equals(other.columnName),
String.format(
"Mismatched column name. Expected [%s], got [%s]",
this.columnName, other.columnName));
}
val mergedSketch = Union.heapify(this.cardinalityTracker.toCompactByteArray());
mergedSketch.update(other.cardinalityTracker);
val iMem = Memory.wrap(frequentItems.toByteArray(ARRAY_OF_STRINGS_SER_DE));
val copyFreqItems = ItemsSketch.getInstance(iMem, ARRAY_OF_STRINGS_SER_DE);
copyFreqItems.merge(other.frequentItems);
val builder =
ColumnProfile.builder()
.setColumnName(this.columnName)
.setCounters(this.counters.merge(other.counters))
.setNumberTracker(this.numberTracker.merge(other.numberTracker))
.setSchemaTracker(this.schemaTracker.merge(other.schemaTracker))
.setCardinalityTracker(HllSketch.heapify(mergedSketch.toCompactByteArray()))
.setFrequentItems(copyFreqItems)
.setNullStrs(Sets.union(this.getNullStrs(), other.getNullStrs()).immutableCopy());
// backward compatibility with profiles that don't have stringtracker.
if (this.stringTracker == null) {
builder.setStringTracker(other.stringTracker);
} else {
builder.setStringTracker(this.stringTracker.merge(other.stringTracker));
}
return builder.build();
}
public ColumnMessage.Builder toProtobuf() {
val hllSketchMessage =
HllSketchMessage.newBuilder()
.setLgK(cardinalityTracker.getLgConfigK())
.setSketch(ByteString.copyFrom(cardinalityTracker.toCompactByteArray()));
return ColumnMessage.newBuilder()
.setName(columnName)
.setCounters(counters.toProtobuf())
.setSchema(schemaTracker.toProtobuf())
.setNumbers(numberTracker.toProtobuf())
.setStrings(stringTracker.toProtobuf())
.setCardinalityTracker(hllSketchMessage)
.setFrequentItems(FrequentStringsSketch.toStringSketch(this.frequentItems));
}
@Nullable
public static ColumnProfile fromProtobuf(@Nullable ColumnMessage message) {
if (message == null || message.getSerializedSize() == 0) {
return null;
}
val builder =
ColumnProfile.builder()
.setColumnName(message.getName())
.setCounters(CountersTracker.fromProtobuf(message.getCounters()))
.setSchemaTracker(
SchemaTracker.fromProtobuf(
message.getSchema(), message.getCounters().getNullCount().getValue()))
.setNumberTracker(NumberTracker.fromProtobuf(message.getNumbers()))
.setCardinalityTracker(
HllSketch.heapify(message.getCardinalityTracker().getSketch().toByteArray()))
.setFrequentItems(
FrequentStringsSketch.deserialize(message.getFrequentItems().getSketch()))
.setNullStrs(ColumnProfile.nullStrsFromEnv());
// backward compatibility - only decode StringsMessage if it exists.
// older profiles written by java library may not have any StringsMessage.
StringTracker strTracker;
if (message.hasStrings()) {
strTracker = StringTracker.fromProtobuf(message.getStrings());
} else {
strTracker = new StringTracker();
}
builder.setStringTracker(strTracker);
return builder.build();
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/DatasetProfile.java | package com.whylogs.core;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import com.whylogs.core.iterator.ColumnsChunkSegmentIterator;
import com.whylogs.core.message.ColumnMessage;
import com.whylogs.core.message.ColumnSummary;
import com.whylogs.core.message.ColumnsChunkSegment;
import com.whylogs.core.message.DatasetMetadataSegment;
import com.whylogs.core.message.DatasetProfileMessage;
import com.whylogs.core.message.DatasetProperties;
import com.whylogs.core.message.DatasetSummary;
import com.whylogs.core.message.MessageSegment;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.time.Instant;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import lombok.Value;
import lombok.val;
/** Representing a DatasetProfile that tracks */
@AllArgsConstructor
public class DatasetProfile implements Serializable {
// generated by IntelliJ
private static final long serialVersionUID = -9221998596693275458L;
public static final String TAG_PREFIX = "whylogs.tag.";
@Getter String sessionId;
@Getter Instant sessionTimestamp;
@Getter Instant dataTimestamp;
Map<String, ColumnProfile> columns;
// always sorted
@Getter Map<String, String> tags;
@Getter Map<String, String> metadata;
@Nullable ModelProfile modelProfile;
/**
* DEVELOPER API. DO NOT USE DIRECTLY
*
* @param sessionId dataset name
* @param sessionTimestamp the timestamp for the current profiling session
* @param dataTimestamp the timestamp for the dataset. Used to aggregate across different cadences
* @param tags tags of the dataset
* @param columns the columns that we're copying over. Note that the source of columns should stop
* using these column objects as they will back this DatasetProfile instead
*/
public DatasetProfile(
@NonNull String sessionId,
@NonNull Instant sessionTimestamp,
@Nullable Instant dataTimestamp,
@NonNull Map<String, String> tags,
@NonNull Map<String, ColumnProfile> columns) {
this(
sessionId,
sessionTimestamp,
dataTimestamp,
new ConcurrentHashMap<>(columns),
new ConcurrentHashMap<>(tags),
new ConcurrentHashMap<>(),
null);
}
/**
* Create a new Dataset profile
*
* @param sessionId the name of the dataset profile
* @param sessionTimestamp the timestamp for this run
* @param tags the tags to track the dataset with
*/
public DatasetProfile(
@NonNull String sessionId,
@NonNull Instant sessionTimestamp,
@NonNull Map<String, String> tags) {
this(sessionId, sessionTimestamp, null, tags, Collections.emptyMap());
}
public DatasetProfile(String sessionId, Instant sessionTimestamp) {
this(sessionId, sessionTimestamp, Collections.emptyMap());
}
public Map<String, ColumnProfile> getColumns() {
return Collections.unmodifiableMap(columns);
}
public ModelProfile getModelProfile() {
return modelProfile;
}
public DatasetProfile withTag(String key, String value) {
this.tags.put(TAG_PREFIX + key, value);
return this;
}
public DatasetProfile withMetadata(String key, String value) {
this.metadata.put(key, value);
return this;
}
public DatasetProfile withAllMetadata(Map<String, String> metadata) {
this.metadata.putAll(metadata);
return this;
}
private void validate() {
Preconditions.checkNotNull(sessionId);
Preconditions.checkNotNull(sessionTimestamp);
Preconditions.checkNotNull(columns);
Preconditions.checkNotNull(metadata);
Preconditions.checkNotNull(tags);
}
public void track(String columnName, Object data) {
trackSingleColumn(columnName, data);
}
private void trackSingleColumn(String columnName, Object data) {
val columnProfile = columns.computeIfAbsent(columnName, ColumnProfile::new);
columnProfile.track(data);
}
public void track(Map<String, ?> columns) {
columns.forEach(this::track);
if (modelProfile != null) {
modelProfile.track(columns);
}
}
/**
* Returns a new dataset profile with the same backing datastructure. However, this new object
* contains a ClassificationMetrics object
*
* @return a new DatasetProfile object
*/
public DatasetProfile withClassificationModel(
String prediction, String target, String score, Iterable<String> additionalOutputFields) {
val model = new ModelProfile(prediction, target, score, additionalOutputFields);
return new DatasetProfile(
sessionId, sessionTimestamp, dataTimestamp, columns, tags, metadata, model);
}
public DatasetProfile withClassificationModel(String prediction, String target, String score) {
return this.withClassificationModel(prediction, target, score, Collections.emptyList());
}
public DatasetProfile withRegressionModel(String prediction, String target) {
return this.withRegressionModel(prediction, target, Collections.emptyList());
}
public DatasetProfile withRegressionModel(
String prediction, String target, Iterable<String> additionalOutputFields) {
val model = new ModelProfile(prediction, target, additionalOutputFields);
return new DatasetProfile(
sessionId, sessionTimestamp, dataTimestamp, columns, tags, metadata, model);
}
public DatasetSummary toSummary() {
validate();
val summaryColumns =
columns.values().stream()
.map(Pair::fromColumn)
.collect(Collectors.toMap(Pair::getName, Pair::getStatistics));
val summary =
DatasetSummary.newBuilder()
.setProperties(toDatasetProperties())
.putAllColumns(summaryColumns);
return summary.build();
}
public Iterator<MessageSegment> toChunkIterator() {
validate();
final String marker = sessionId + UUID.randomUUID().toString();
// first segment is the metadata
val properties = toDatasetProperties();
val metadataBuilder =
DatasetMetadataSegment.newBuilder().setProperties(properties).setMarker(marker);
val metadataSegment =
MessageSegment.newBuilder().setMarker(marker).setMetadata(metadataBuilder).build();
// then we group the columns by size
val chunkedColumns =
columns.values().stream()
.map(ColumnProfile::toProtobuf)
.map(ColumnMessage.Builder::build)
.iterator();
val columnSegmentMessages =
Iterators.<ColumnsChunkSegment, MessageSegment>transform(
new ColumnsChunkSegmentIterator(chunkedColumns, marker),
msg -> MessageSegment.newBuilder().setColumns(msg).build());
return Iterators.concat(Iterators.singletonIterator(metadataSegment), columnSegmentMessages);
}
public DatasetProfile mergeStrict(@NonNull DatasetProfile other) {
Preconditions.checkArgument(
Objects.equals(this.sessionId, other.sessionId),
String.format(
"Mismatched name. Current name [%s] is merged with [%s]",
this.sessionId, other.sessionId));
Preconditions.checkArgument(
Objects.equals(this.sessionTimestamp, other.sessionTimestamp),
String.format(
"Mismatched session timestamp. Current ts [%s] is merged with [%s]",
this.sessionTimestamp, other.sessionTimestamp));
Preconditions.checkArgument(
Objects.equals(this.dataTimestamp, other.dataTimestamp),
String.format(
"Mismatched data timestamp. Current ts [%s] is merged with [%s]",
this.dataTimestamp, other.dataTimestamp));
Preconditions.checkArgument(
Objects.equals(this.tags, other.tags),
String.format("Mismatched tags. Current %s being merged with %s", this.tags, other.tags));
return doMerge(other, this.tags);
}
/**
* Merge the data of another {@link DatasetProfile} into this one.
*
* <p>We will only retain the shared tags and share metadata. The timestamps are copied over from
* this dataset. It is the responsibility of the user to ensure that the two datasets are matched
* on important grouping information
*
* @param other a {@link DatasetProfile}
* @return a merged {@link DatasetProfile} with summed up columns
*/
public DatasetProfile merge(@NonNull DatasetProfile other) {
if (this.tags.isEmpty()) {
return doMerge(other, ImmutableMap.copyOf(other.tags));
}
val sharedTags = ImmutableMap.<String, String>builder();
for (val tagKey : this.tags.keySet()) {
val tagValue = this.tags.get(tagKey);
if (tagValue.equals(other.tags.get(tagKey))) {
sharedTags.put(tagKey, tagValue);
}
}
return doMerge(other, sharedTags.build());
}
private DatasetProfile doMerge(@NonNull DatasetProfile other, Map<String, String> tags) {
this.validate();
other.validate();
Instant datasetTimestamp =
(this.dataTimestamp == null) ? other.getDataTimestamp() : this.dataTimestamp;
val result =
new DatasetProfile(
this.sessionId, this.sessionTimestamp, datasetTimestamp, tags, Collections.emptyMap());
val sharedMetadata = ImmutableMap.<String, String>builder();
for (val mKey : this.metadata.keySet()) {
val mValue = this.metadata.get(mKey);
if (mValue.equals(other.metadata.get(mKey))) {
sharedMetadata.put(mKey, mValue);
}
}
result.withAllMetadata(sharedMetadata.build());
val unionColumns = Sets.union(this.columns.keySet(), other.columns.keySet());
for (val column : unionColumns) {
val emptyColumn = new ColumnProfile(column);
val thisColumn = this.columns.getOrDefault(column, emptyColumn);
val otherColumn = other.columns.getOrDefault(column, emptyColumn);
result.columns.put(column, thisColumn.merge(otherColumn));
}
if (modelProfile != null) {
result.modelProfile = this.modelProfile.merge(other.modelProfile);
} else if (other.modelProfile != null) {
result.modelProfile = other.modelProfile.copy();
}
return result;
}
public DatasetProfileMessage.Builder toProtobuf() {
validate();
val properties = toDatasetProperties();
val builder = DatasetProfileMessage.newBuilder().setProperties(properties);
columns.forEach((k, v) -> builder.putColumns(k, v.toProtobuf().build()));
if (modelProfile != null) {
builder.setModeProfile(modelProfile.toProtobuf());
}
return builder;
}
public void writeTo(OutputStream out) throws IOException {
this.toProtobuf().build().writeDelimitedTo(out);
}
public byte[] toBytes() throws IOException {
val msg = this.toProtobuf().build();
val bos = new ByteArrayOutputStream(msg.getSerializedSize());
msg.writeDelimitedTo(bos);
return bos.toByteArray();
}
private DatasetProperties.Builder toDatasetProperties() {
val dataTimeInMillis = (dataTimestamp == null) ? -1L : dataTimestamp.toEpochMilli();
return DatasetProperties.newBuilder()
.setSessionId(sessionId)
.setSessionTimestamp(sessionTimestamp.toEpochMilli())
.setDataTimestamp(dataTimeInMillis)
.putAllTags(tags)
.putAllMetadata(metadata)
.setSchemaMajorVersion(SchemaInformation.SCHEMA_MAJOR_VERSION)
.setSchemaMinorVersion(SchemaInformation.SCHEMA_MINOR_VERSION);
}
@Nullable
public static DatasetProfile fromProtobuf(@Nullable DatasetProfileMessage message) {
if (message == null || message.getSerializedSize() == 0) {
return null;
}
val props = message.getProperties();
SchemaInformation.validateSchema(props.getSchemaMajorVersion(), props.getSchemaMinorVersion());
val tags = props.getTagsMap();
val sessionTimestamp = Instant.ofEpochMilli(props.getSessionTimestamp());
val dataTimestamp =
(props.getDataTimestamp() < 0L) ? null : Instant.ofEpochMilli(props.getDataTimestamp());
val ds =
new DatasetProfile(
props.getSessionId(), sessionTimestamp, dataTimestamp, tags, Collections.emptyMap());
ds.withAllMetadata(props.getMetadataMap());
message.getColumnsMap().forEach((k, v) -> ds.columns.put(k, ColumnProfile.fromProtobuf(v)));
ds.modelProfile = ModelProfile.fromProtobuf(message.getModeProfile());
ds.validate();
return ds;
}
public static DatasetProfile parse(InputStream in) throws IOException {
val msg = DatasetProfileMessage.parseDelimitedFrom(in);
return DatasetProfile.fromProtobuf(msg);
}
private void writeObject(ObjectOutputStream out) throws IOException {
validate();
this.writeTo(out);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
val copy = DatasetProfile.parse(in);
this.sessionId = copy.sessionId;
this.sessionTimestamp = copy.sessionTimestamp;
this.dataTimestamp = copy.dataTimestamp;
this.metadata = copy.metadata;
this.tags = copy.tags;
this.columns = copy.columns;
this.modelProfile = copy.modelProfile;
this.validate();
}
@Value
static class Pair {
String name;
ColumnSummary statistics;
static Pair fromColumn(ColumnProfile column) {
return new Pair(column.getColumnName(), column.toColumnSummary());
}
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/ModelProfile.java | package com.whylogs.core;
import com.google.common.collect.Sets;
import com.whylogs.core.message.ModelProfileMessage;
import com.whylogs.core.message.ModelType;
import com.whylogs.core.metrics.ModelMetrics;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
@Slf4j
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ModelProfile {
private final Set<String> outputFields;
@NonNull @Getter private final ModelMetrics metrics;
public ModelProfile(
String prediction, String target, String score, Iterable<String> additionalOutputFields) {
this.outputFields = Sets.newHashSet(additionalOutputFields);
this.outputFields.add(prediction);
this.metrics = new ModelMetrics(prediction, target, score);
}
public ModelProfile(String prediction, String target, Iterable<String> additionalOutputFields) {
this.outputFields = Sets.newHashSet(additionalOutputFields);
this.outputFields.add(prediction);
this.metrics = new ModelMetrics(prediction, target);
}
public ModelProfileMessage.Builder toProtobuf() {
val builder = ModelProfileMessage.newBuilder();
builder.addAllOutputFields(outputFields);
builder.setMetrics(metrics.toProtobuf());
return builder;
}
@Nullable
public static ModelProfile fromProtobuf(@Nullable ModelProfileMessage message) {
if (message == null
|| message.getSerializedSize() == 0
|| message.getMetrics().getModelType().equals(ModelType.UNKNOWN)) {
return null;
}
val metrics = ModelMetrics.fromProtobuf(message.getMetrics());
if (metrics == null) {
return null;
}
val outputFields = Sets.newHashSet(message.getOutputFieldsList());
if (outputFields.isEmpty()) {
log.warn("Empty output fields. This is not supposed to happen");
}
return new ModelProfile(outputFields, metrics);
}
@NonNull
public ModelProfile merge(@Nullable ModelProfile other) {
if (other == null) {
val metricsCopy = metrics.copy();
return new ModelProfile(Sets.newHashSet(outputFields), metricsCopy);
}
if (!this.outputFields.equals(other.outputFields)) {
log.warn("Output fields don't match. Using the current output fields");
}
return new ModelProfile(Sets.newHashSet(outputFields), metrics.merge(other.metrics));
}
public ModelProfile copy() {
return merge(null);
}
public void track(Map<String, ?> columns) {
this.metrics.track(columns);
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/SchemaInformation.java | package com.whylogs.core;
import com.google.common.base.Preconditions;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@UtilityClass
public class SchemaInformation {
final int SCHEMA_MAJOR_VERSION = 1;
final int SCHEMA_MINOR_VERSION = 3;
void validateSchema(int majorVersion, int minorVersion) {
Preconditions.checkArgument(
SCHEMA_MAJOR_VERSION == majorVersion,
String.format("Expect major version %s, got %s", SCHEMA_MAJOR_VERSION, majorVersion));
Preconditions.checkArgument(
SCHEMA_MINOR_VERSION >= minorVersion,
String.format(
"Does not support forward compatibility. Minor version: %s, got: %s",
SCHEMA_MINOR_VERSION, minorVersion));
if (SCHEMA_MINOR_VERSION > minorVersion) {
log.warn("Expect minor version {}. Got: {}", SCHEMA_MINOR_VERSION, minorVersion);
}
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/SummaryConverters.java | package com.whylogs.core;
import static org.apache.commons.lang3.ArrayUtils.toObject;
import com.whylogs.core.message.FrequentStringsSummary;
import com.whylogs.core.message.HistogramSummary;
import com.whylogs.core.message.NumberSummary;
import com.whylogs.core.message.QuantileSummary;
import com.whylogs.core.message.SchemaSummary;
import com.whylogs.core.message.StringsSummary;
import com.whylogs.core.message.UniqueCountSummary;
import com.whylogs.core.statistics.NumberTracker;
import com.whylogs.core.statistics.SchemaTracker;
import com.whylogs.core.statistics.datatypes.StringTracker;
import java.util.Arrays;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import lombok.val;
import org.apache.datasketches.frequencies.ErrorType;
import org.apache.datasketches.frequencies.ItemsSketch;
import org.apache.datasketches.frequencies.ItemsSketch.Row;
import org.apache.datasketches.kll.KllFloatsSketch;
import org.apache.datasketches.theta.Union;
public class SummaryConverters {
public static UniqueCountSummary fromSketch(Union sketch) {
val result = sketch.getResult();
return UniqueCountSummary.newBuilder()
.setEstimate(result.getEstimate())
.setUpper(result.getUpperBound(1))
.setLower(result.getLowerBound(1))
.build();
}
public static StringsSummary fromStringTracker(StringTracker tracker) {
if (tracker == null) {
return null;
}
if (tracker.getCount() == 0) {
return null;
}
val uniqueCount = fromSketch(tracker.getThetaSketch());
val builder =
StringsSummary.newBuilder()
.setUniqueCount(uniqueCount)
.setLength(fromNumberTracker(tracker.getLength()))
.setTokenLength(fromNumberTracker(tracker.getTokenLength()))
.setCharPosTracker(tracker.getCharPosTracker().toSummary());
// TODO: make this value (100) configurable
if (uniqueCount.getEstimate() < 100) {
val frequentStrings = fromStringSketch(tracker.getItems());
if (frequentStrings != null) {
builder.setFrequent(frequentStrings);
}
}
return builder.build();
}
public static SchemaSummary.Builder fromSchemaTracker(SchemaTracker tracker) {
val typeCounts = tracker.getTypeCounts();
val typeCountWithNames =
typeCounts.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().name(), Entry::getValue));
return SchemaSummary.newBuilder()
.setInferredType(tracker.getInferredType())
.putAllTypeCounts(typeCountWithNames);
}
public static NumberSummary fromNumberTracker(NumberTracker numberTracker) {
if (numberTracker == null) {
return null;
}
long count = numberTracker.getVariance().getCount();
if (count == 0) {
return null;
}
double stddev = numberTracker.getVariance().stddev();
double mean, min, max;
val doubles = numberTracker.getDoubles().toProtobuf();
if (doubles.getCount() > 0) {
mean = doubles.getSum() / doubles.getCount();
min = doubles.getMin();
max = doubles.getMax();
} else {
mean = numberTracker.getLongs().getMean();
min = (double) numberTracker.getLongs().getMin();
max = (double) numberTracker.getLongs().getMax();
}
val histogram = fromUpdateDoublesSketch(numberTracker.getHistogram());
val result = numberTracker.getThetaSketch().getResult();
val uniqueCountSummary =
UniqueCountSummary.newBuilder()
.setEstimate(result.getEstimate())
.setLower(result.getLowerBound(1))
.setUpper(result.getUpperBound(1));
// some unfortunate type mismatches requires conversions.
val QUANTILES = new double[] {0.0, 0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99, 1.0};
val boxedQuantiles = toObject(QUANTILES);
// unfortunately ArrayUtils does not have a static utility for converting float[] -> double[].
val qvals = numberTracker.getHistogram().getQuantiles(QUANTILES);
val len = qvals.length;
val boxedQvals = new Double[len];
for (int index = 0; index < qvals.length; index++) {
boxedQvals[index] = (double) (qvals[index]);
}
val quantileSummary =
QuantileSummary.newBuilder()
.addAllQuantiles(Arrays.asList(boxedQuantiles))
.addAllQuantileValues(Arrays.asList(boxedQvals));
return NumberSummary.newBuilder()
.setCount(count)
.setStddev(stddev)
.setMin(min)
.setMax(max)
.setMean(mean)
.setHistogram(histogram)
.setUniqueCount(uniqueCountSummary)
.setQuantiles(quantileSummary)
.setIsDiscrete(false) // TODO: migrate Python code over
.build();
}
public static FrequentStringsSummary fromStringSketch(ItemsSketch<String> sketch) {
val frequentItems = sketch.getFrequentItems(ErrorType.NO_FALSE_NEGATIVES);
if (frequentItems.length == 0) {
return null;
}
val result =
Stream.of(frequentItems)
.map(SummaryConverters::toFrequentItem)
.collect(Collectors.toList());
return FrequentStringsSummary.newBuilder().addAllItems(result).build();
}
private static FrequentStringsSummary.FrequentItem toFrequentItem(Row<String> row) {
return FrequentStringsSummary.FrequentItem.newBuilder()
.setValue(row.getItem())
.setEstimate(row.getEstimate())
.build();
}
public static HistogramSummary fromUpdateDoublesSketch(final KllFloatsSketch sketch) {
return fromUpdateDoublesSketch(sketch, 30);
}
public static HistogramSummary fromUpdateDoublesSketch(
final KllFloatsSketch sketch, float[] splitpoints) {
return fromUpdateDoublesSketch(sketch, 0, splitpoints);
}
public static HistogramSummary fromUpdateDoublesSketch(
final KllFloatsSketch sketch, final int nBins) {
return fromUpdateDoublesSketch(sketch, nBins, null);
}
private static HistogramSummary fromUpdateDoublesSketch(
final KllFloatsSketch sketch, int nBins, @Nullable float[] splitPoints) {
nBins = splitPoints != null ? splitPoints.length + 1 : (nBins > 0 ? nBins : 30);
if (nBins < 2) {
throw new IllegalArgumentException("at least 2 bins expected");
}
val builder = HistogramSummary.newBuilder();
if (sketch.isEmpty()) {
return builder.build();
}
val n = sketch.getN();
float start = noNan(sketch.getMinValue());
float end = noNan(sketch.getMaxValue());
builder
.setN(n) //
.setMin(start) //
.setMax(end);
// calculate equally spaced points between [start, end]
float width = (end - start) / nBins;
width = Math.max(width, Math.ulp(start)); // min width in case start==end
builder.setWidth(width);
if (splitPoints != null) {
builder.addBins(sketch.getMinValue());
for (float splitPoint : splitPoints) {
builder.addBins(splitPoint);
}
builder.addBins(sketch.getMaxValue());
} else {
// calculate equally spaced points between [start, end]
// splitPoints must be unique and monotonically increasing
final int noSplitPoints = nBins - 1;
splitPoints = new float[noSplitPoints];
builder.addBins(start);
for (int i = 0; i < noSplitPoints; i++) {
splitPoints[i] = start + (i + 1) * width;
builder.addBins(splitPoints[i]);
}
builder.addBins(end);
}
for (double v : sketch.getPMF(splitPoints)) {
// scale fractions to counts
builder.addCounts(Math.round(noNan(v) * n));
}
return builder.build();
}
// noNan for Double streams
public static double noNan(double value) {
if (Double.isNaN(value) || Double.isInfinite(value)) {
return 0f;
}
return value;
}
// noNan for Float streams
public static float noNan(float value) {
if (Float.isNaN(value) || Float.isInfinite(value)) {
return 0f;
}
return value;
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/metrics/ClassificationMetrics.java | package com.whylogs.core.metrics;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.whylogs.core.message.ScoreMatrixMessage;
import com.whylogs.core.statistics.NumberTracker;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
@Slf4j
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public class ClassificationMetrics {
private List<String> labels;
private final String predictionField;
private final String targetField;
private final String scoreField;
private NumberTracker[][] values;
public ClassificationMetrics(String predictionField, String targetField, String scoreField) {
this(Lists.newArrayList(), predictionField, targetField, scoreField, newMatrix(0));
}
public List<String> getLabels() {
return Collections.unmodifiableList(labels);
}
public long[][] getConfusionMatrix() {
final int len = labels.size();
val res = new long[len][len];
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
res[i][j] = values[i][j].getDoubles().getCount();
}
}
return res;
}
private static NumberTracker[][] newMatrix(int len) {
val res = new NumberTracker[len][len];
if (len == 0) {
return res;
}
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
res[i][j] = new NumberTracker();
}
}
return res;
}
public void track(Map<String, ?> columns) {
Preconditions.checkState(predictionField != null);
Preconditions.checkState(targetField != null);
val prediction = columns.get(predictionField);
val target = columns.get(targetField);
val scoreRaw = columns.get(scoreField);
double score = 0;
if (scoreRaw instanceof Number) {
score = ((Number) scoreRaw).doubleValue();
} else if (scoreRaw != null) {
try {
score = Double.parseDouble(scoreRaw.toString());
} catch (NumberFormatException e) {
log.warn("Failed to parse score: {}", scoreRaw, e);
}
}
this.update(prediction, target, score);
}
public <T> void update(T prediction, T target, double score) {
val predictionText = textValue(prediction);
val targetText = textValue(target);
val x = labels.indexOf(predictionText);
val y = labels.indexOf(targetText);
if (x >= 0 && y >= 0) {
// happy case
values[x][y].track(score);
} else {
val newLabelsSet = Sets.newHashSet(labels);
if (x < 0) {
newLabelsSet.add(predictionText);
}
if (y < 0) {
newLabelsSet.add(targetText);
}
val newLabels = Lists.newArrayList(newLabelsSet);
Collections.sort(newLabels);
final int newDim = newLabelsSet.size();
val newValues = newMatrix(newDim);
// first copy existing values to the new matrix
addMatrix(labels, values, newLabels, newValues);
val i = newLabels.indexOf(predictionText);
val j = newLabels.indexOf(targetText);
newValues[i][j].track(score);
this.labels = newLabels;
this.values = newValues;
}
}
private static String textValue(Object value) {
if (value == null) {
return null;
}
if (value instanceof Boolean) {
val boolVal = (Boolean) value;
return boolVal ? "1" : "0";
}
return value.toString();
}
@Override
public String toString() {
val builder = new StringBuilder();
builder.append("Labels: ");
labels.forEach(
it -> {
builder.append(it);
builder.append(", ");
});
builder.append('\n');
final int len = labels.size();
for (int i = 0; i < len; i++) {
builder.append('[');
for (int j = 0; j < len; j++) {
builder.append(values[i][j]);
if (j + 1 < len) {
builder.append(", ");
}
}
builder.append("]\n");
}
return builder.toString();
}
public ClassificationMetrics merge(ClassificationMetrics other) {
if (other == null) {
return copy();
}
val allLabels = Sets.newHashSet(this.labels);
allLabels.addAll(other.labels);
val newLabels = Lists.newArrayList(allLabels);
Collections.sort(newLabels);
val newValues = newMatrix(newLabels.size());
// copy the current object
addMatrix(labels, values, newLabels, newValues);
// copy the other object
addMatrix(other.labels, other.values, newLabels, newValues);
return new ClassificationMetrics(
newLabels, targetField, predictionField, scoreField, newValues);
}
private void addMatrix(
List<String> oldLabels,
NumberTracker[][] oldValues,
List<String> newLabels,
NumberTracker[][] newValues) {
for (int i = 0; i < oldLabels.size(); i++) {
val iLabel = oldLabels.get(i);
final int newI = newLabels.indexOf(iLabel);
for (int j = 0; j < oldLabels.size(); j++) {
val jLabel = oldLabels.get(j);
int newJ = newLabels.indexOf(jLabel);
newValues[newI][newJ] = newValues[newI][newJ].merge(oldValues[i][j]);
}
}
}
@NonNull
public ClassificationMetrics copy() {
final int len = this.labels.size();
val copyValues = newMatrix(len);
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
copyValues[i][j] = copyValues[i][j].merge(values[i][j]);
}
}
return new ClassificationMetrics(
Lists.newArrayList(this.labels), predictionField, targetField, scoreField, copyValues);
}
@NonNull
@SuppressWarnings("UnstableApiUsage")
public ScoreMatrixMessage.Builder toProtobuf() {
val builder = ScoreMatrixMessage.newBuilder();
labels.stream().map(Object::toString).forEach(builder::addLabels);
val len = labels.size();
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
builder.addScores(values[i][j].toProtobuf());
}
}
builder.setPredictionField(predictionField);
builder.setTargetField(targetField);
builder.setScoreField(scoreField);
return builder;
}
@Nullable
public static ClassificationMetrics fromProtobuf(@Nullable ScoreMatrixMessage msg) {
if (msg == null || msg.getSerializedSize() == 0) {
return null;
}
val labels = Lists.<String>newArrayList();
for (int i = 0; i < msg.getLabelsCount(); i++) {
labels.add(msg.getLabels(i));
}
if (msg.getLabelsCount() == 0 && msg.getScoresCount() > 0) {
// Not valid to have score without labels.
log.warn("Skipping classification ScoreMatrix: has scores but no labels");
return null;
}
final int n = labels.size();
val values = newMatrix(n);
for (int i = 0; i < msg.getScoresCount(); i++) {
int row = i / n;
int col = i % n;
values[row][col] = NumberTracker.fromProtobuf(msg.getScores(i));
}
return new ClassificationMetrics(
labels, msg.getPredictionField(), msg.getTargetField(), msg.getScoreField(), values);
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/metrics/ModelMetrics.java | package com.whylogs.core.metrics;
import com.google.common.base.Preconditions;
import com.whylogs.core.message.ModelMetricsMessage;
import com.whylogs.core.message.ModelType;
import java.util.Map;
import javax.annotation.Nullable;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.val;
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class ModelMetrics {
@Getter private final ModelType modelType;
@Getter private final ClassificationMetrics classificationMetrics;
@Getter private final RegressionMetrics regressionMetrics;
public ModelMetrics(String predictionField, String targetField, String scoreField) {
this(
ModelType.CLASSIFICATION,
new ClassificationMetrics(predictionField, targetField, scoreField),
null);
}
public ModelMetrics(String predictionField, String targetField) {
this(ModelType.REGRESSION, null, new RegressionMetrics(predictionField, targetField));
}
public void track(Map<String, ?> columns) {
switch (modelType) {
case CLASSIFICATION:
this.classificationMetrics.track(columns);
break;
case REGRESSION:
this.regressionMetrics.track(columns);
break;
default:
throw new IllegalArgumentException("Unsupported model type: " + modelType);
}
}
public ModelMetricsMessage.Builder toProtobuf() {
val res = ModelMetricsMessage.newBuilder().setModelType(this.modelType);
if (classificationMetrics != null) {
res.setScoreMatrix(classificationMetrics.toProtobuf());
}
if (regressionMetrics != null) {
res.setRegressionMetrics(regressionMetrics.toProtobuf());
}
return res;
}
public ModelMetrics merge(ModelMetrics other) {
if (other == null) {
return this;
}
Preconditions.checkArgument(
this.modelType == other.modelType,
"Mismatched model type: expected %s, got %s",
this.modelType,
other.modelType);
switch (this.modelType) {
case CLASSIFICATION:
val mergedMatrix = classificationMetrics.merge(other.classificationMetrics);
return new ModelMetrics(this.modelType, mergedMatrix, null);
case REGRESSION:
val mergedRegressionMetrics = regressionMetrics.merge(other.regressionMetrics);
return new ModelMetrics(this.modelType, null, mergedRegressionMetrics);
default:
throw new IllegalArgumentException("Unsupported model type: " + this.modelType);
}
}
public ModelMetrics copy() {
switch (this.modelType) {
case CLASSIFICATION:
return new ModelMetrics(this.modelType, this.classificationMetrics.copy(), null);
case REGRESSION:
return new ModelMetrics(this.modelType, null, this.regressionMetrics.copy());
default:
throw new IllegalArgumentException("Unsupported model type: " + this.modelType);
}
}
@Nullable
public static ModelMetrics fromProtobuf(@Nullable ModelMetricsMessage msg) {
if (msg == null || msg.getSerializedSize() == 0) {
return null;
}
val classificationMetrics = ClassificationMetrics.fromProtobuf(msg.getScoreMatrix());
val regressionMetrics = RegressionMetrics.fromProtobuf(msg.getRegressionMetrics());
final ModelType modelType = msg.getModelType();
switch (modelType) {
case CLASSIFICATION:
if (classificationMetrics != null) {
return new ModelMetrics(modelType, classificationMetrics, null);
}
case REGRESSION:
if (regressionMetrics != null) {
return new ModelMetrics(modelType, null, regressionMetrics);
}
}
return null;
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/metrics/RegressionMetrics.java | package com.whylogs.core.metrics;
import com.google.common.base.Preconditions;
import com.whylogs.core.message.RegressionMetricsMessage;
import java.util.Map;
import java.util.Objects;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
@RequiredArgsConstructor
@Getter
@Slf4j
public class RegressionMetrics {
@NonNull private final String predictionField;
@NonNull private final String targetField;
private double sumAbsDiff;
private double sumDiff;
private double sum2Diff;
private long count;
public void track(Map<String, ?> columns) {
val prediction = (Number) columns.get(predictionField);
val target = (Number) columns.get(targetField);
final double diff = prediction.doubleValue() - target.doubleValue();
this.sumAbsDiff += Math.abs(diff);
this.sumDiff += diff;
this.sum2Diff += diff * diff;
this.count++;
}
public RegressionMetrics copy() {
val res = new RegressionMetrics(this.predictionField, this.targetField);
res.sumAbsDiff = this.sumAbsDiff;
res.sumDiff = this.sumDiff;
res.sum2Diff = this.sum2Diff;
res.count = this.count;
return res;
}
public RegressionMetrics merge(RegressionMetrics other) {
if (other == null) {
return this.copy();
}
Preconditions.checkState(
Objects.equals(this.predictionField, other.predictionField),
"Mismatched prediction fields: %s vs %s",
this.predictionField,
other.predictionField);
Preconditions.checkState(
Objects.equals(this.targetField, other.targetField),
"Mismatched target fields: %s vs %s",
this.targetField,
other.targetField);
val result = new RegressionMetrics(this.predictionField, this.targetField);
result.sumAbsDiff = this.sumAbsDiff + other.sumAbsDiff;
result.sumDiff = this.sumDiff + other.sumDiff;
result.sum2Diff = this.sum2Diff + other.sum2Diff;
result.count = this.count + other.count;
return result;
}
public RegressionMetricsMessage.Builder toProtobuf() {
return RegressionMetricsMessage.newBuilder()
.setPredictionField(this.predictionField)
.setTargetField(this.targetField)
.setSumAbsDiff(this.sumAbsDiff)
.setSumDiff(this.sumDiff)
.setSum2Diff(this.sum2Diff)
.setCount(this.count);
}
public static RegressionMetrics fromProtobuf(RegressionMetricsMessage msg) {
if (msg == null || msg.getSerializedSize() == 0) {
return null;
}
if ("".equals(msg.getPredictionField()) || "".equals(msg.getTargetField())) {
log.warn("Skipping Regression metrics: prediction or target field not set");
return null;
}
val res = new RegressionMetrics(msg.getPredictionField(), msg.getTargetField());
res.sumAbsDiff = msg.getSumAbsDiff();
res.sumDiff = msg.getSumDiff();
res.sum2Diff = msg.getSum2Diff();
res.count = msg.getCount();
return res;
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/statistics/CountersTracker.java | package com.whylogs.core.statistics;
import com.google.protobuf.Int64Value;
import com.whylogs.core.message.Counters;
import java.util.Optional;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import lombok.val;
@EqualsAndHashCode
@Getter
@FieldDefaults(level = AccessLevel.PRIVATE)
public class CountersTracker {
long count;
long trueCount;
public void incrementCount() {
count++;
}
public void incrementTrue() {
trueCount++;
}
public void add(CountersTracker other) {
this.count += other.count;
this.trueCount += other.trueCount;
}
public CountersTracker merge(CountersTracker other) {
val result = new CountersTracker();
result.count = this.count + other.count;
result.trueCount = this.trueCount + other.trueCount;
return result;
}
public Counters.Builder toProtobuf() {
val countersBuilder = Counters.newBuilder().setCount(count);
if (trueCount > 0) {
countersBuilder.setTrueCount(Int64Value.of(trueCount));
}
return countersBuilder;
}
public static CountersTracker fromProtobuf(Counters message) {
val tracker = new CountersTracker();
tracker.count = message.getCount();
tracker.trueCount = Optional.of(message.getTrueCount()).map(Int64Value::getValue).orElse(0L);
return tracker;
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/statistics/NumberTracker.java | package com.whylogs.core.statistics;
import com.google.protobuf.ByteString;
import com.whylogs.core.message.NumbersMessage;
import com.whylogs.core.statistics.datatypes.DoubleTracker;
import com.whylogs.core.statistics.datatypes.LongTracker;
import com.whylogs.core.statistics.datatypes.VarianceTracker;
import com.whylogs.core.utils.sketches.ThetaSketch;
import java.util.Optional;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.val;
import org.apache.datasketches.kll.KllFloatsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.theta.Union;
@Getter
@Builder(setterPrefix = "set")
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class NumberTracker {
// our own trackers
VarianceTracker variance;
DoubleTracker doubles;
LongTracker longs;
// sketches
KllFloatsSketch histogram; // histogram
Union thetaSketch; // theta sketch for cardinality
public NumberTracker() {
this.variance = new VarianceTracker();
this.doubles = new DoubleTracker();
this.longs = new LongTracker();
this.histogram = new KllFloatsSketch(256);
this.thetaSketch = Union.builder().buildUnion();
}
public void track(Number number) {
double dValue = number.doubleValue();
variance.update(dValue);
histogram.update((float) dValue);
thetaSketch.update(dValue);
if (doubles.getCount() > 0) {
doubles.update(dValue);
} else if (number instanceof Long || number instanceof Integer) {
longs.update(number.longValue());
} else {
doubles.addLongs(longs);
longs.reset();
doubles.update(dValue);
}
}
public void add(NumberTracker other) {
if (other == null) {
return;
}
this.variance.add(other.variance);
this.doubles.add(other.doubles);
this.longs.add(other.longs);
this.histogram.merge(other.histogram);
}
@NonNull
public NumberTracker merge(NumberTracker other) {
if (other == null) {
return this;
}
val unionHistogram = KllFloatsSketch.heapify(Memory.wrap(this.histogram.toByteArray()));
unionHistogram.merge(other.histogram);
val thetaUnion = Union.builder().buildUnion();
thetaUnion.update(this.thetaSketch.getResult());
thetaUnion.update(other.thetaSketch.getResult());
return NumberTracker.builder()
.setVariance(this.variance.merge(other.variance))
.setDoubles(this.doubles.merge(other.doubles))
.setLongs(this.longs.merge(other.longs))
.setThetaSketch(thetaUnion)
.setHistogram(unionHistogram)
.build();
}
public NumbersMessage.Builder toProtobuf() {
val builder =
NumbersMessage.newBuilder()
.setVariance(variance.toProtobuf())
.setHistogram(ByteString.copyFrom(histogram.toByteArray()));
if (this.doubles.getCount() > 0) {
builder.setDoubles(this.doubles.toProtobuf());
} else if (this.longs.getCount() > 0) {
builder.setLongs(this.longs.toProtobuf());
}
builder.setCompactTheta(ThetaSketch.serialize(thetaSketch));
return builder;
}
@NonNull
public static NumberTracker fromProtobuf(NumbersMessage message) {
val hMem = Memory.wrap(message.getHistogram().toByteArray());
val builder =
NumberTracker.builder()
.setHistogram(KllFloatsSketch.heapify(hMem))
.setVariance(VarianceTracker.fromProtobuf(message.getVariance()));
Optional.ofNullable(message.getDoubles())
.map(DoubleTracker::fromProtobuf)
.ifPresent(builder::setDoubles);
Optional.ofNullable(message.getLongs())
.map(LongTracker::fromProtobuf)
.ifPresent(builder::setLongs);
builder.setThetaSketch(ThetaSketch.deserialize(message.getCompactTheta()));
return builder.build();
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/statistics/SchemaTracker.java | package com.whylogs.core.statistics;
import com.google.common.collect.Maps;
import com.whylogs.core.message.InferredType;
import com.whylogs.core.message.SchemaMessage;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.val;
@EqualsAndHashCode
@RequiredArgsConstructor
public class SchemaTracker {
private static final InferredType.Builder UNKNOWN_TYPE_BUILDER =
InferredType.newBuilder().setType(InferredType.Type.UNKNOWN);
private final Map<InferredType.Type, Long> typeCounts;
public SchemaTracker() {
this.typeCounts = new HashMap<>(InferredType.Type.values().length, 1.0f);
}
public void track(InferredType.Type type) {
typeCounts.merge(type, 1L, Long::sum);
}
long getCount(InferredType.Type type) {
return typeCounts.getOrDefault(type, 0L);
}
public Map<InferredType.Type, Long> getTypeCounts() {
return Collections.unmodifiableMap(typeCounts);
}
public InferredType getInferredType() {
val totalCount = typeCounts.values().stream().mapToLong(Long::longValue).sum();
if (totalCount == 0) {
return UNKNOWN_TYPE_BUILDER.build();
}
// first figure out the most popular type and its count
val candidate = getMostPopularType(totalCount);
if (candidate.getRatio() > 0.7) {
return candidate.build();
}
// integral is a subset of fractional
val fractionalCount =
Stream.of(InferredType.Type.INTEGRAL, InferredType.Type.FRACTIONAL)
.mapToLong(type -> typeCounts.getOrDefault(type, 0L))
.sum();
// Handling String case first
// it has to have more entries than fractional values
val candidateType = candidate.getType();
if (candidateType == InferredType.Type.STRING
&& typeCounts.get(InferredType.Type.STRING) > fractionalCount) {
// treat everything else as "String" except UNKNOWN
val coercedCount =
Stream.of(
InferredType.Type.STRING,
InferredType.Type.INTEGRAL,
InferredType.Type.FRACTIONAL,
InferredType.Type.BOOLEAN)
.mapToLong(type -> typeCounts.getOrDefault(type, 0L))
.sum();
val actualRatio = coercedCount / (double) totalCount;
return InferredType.newBuilder()
.setType(InferredType.Type.STRING)
.setRatio(actualRatio)
.build();
}
// if not string but another type with majority
if (candidate.getRatio() > 0.5) {
long actualCount = typeCounts.get(candidateType);
if (candidateType == InferredType.Type.FRACTIONAL) {
actualCount = fractionalCount;
}
return InferredType.newBuilder()
.setType(candidateType)
.setRatio(actualCount / (double) totalCount)
.build();
}
// Otherwise, if fractional count is the majority, then likely this is a fractional type
final double fractionalRatio = fractionalCount / (double) totalCount;
if (fractionalRatio > 0.5) {
return InferredType.newBuilder()
.setType(InferredType.Type.FRACTIONAL)
.setRatio(fractionalRatio)
.build();
}
// we can't infer any type
return InferredType.newBuilder().setType(InferredType.Type.UNKNOWN).setRatio(1.0).build();
}
public SchemaMessage.Builder toProtobuf() {
val protobufFriendlyMap =
typeCounts.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().getNumber(), Entry::getValue));
return SchemaMessage.newBuilder().putAllTypeCounts(protobufFriendlyMap);
}
public static SchemaTracker fromProtobuf(SchemaMessage message) {
return fromProtobuf(message, 0L);
}
// Legacy handle for this bug https://github.com/whylabs/whylogs/issues/232
public static SchemaTracker fromProtobuf(SchemaMessage message, long legacyNullCount) {
val schemaTracker = new SchemaTracker();
message
.getTypeCountsMap()
.forEach((k, v) -> schemaTracker.typeCounts.put(InferredType.Type.forNumber(k), v));
if (legacyNullCount > 0L) {
schemaTracker.typeCounts.compute(
InferredType.Type.NULL,
(type, existingValue) -> Optional.ofNullable(existingValue).orElse(0L) + legacyNullCount);
}
return schemaTracker;
}
private InferredType.Builder getMostPopularType(long totalCount) {
val mostPopularType =
typeCounts.entrySet().stream()
.max((e1, e2) -> (int) (e1.getValue() - e2.getValue()))
.map(Entry::getKey)
.orElse(InferredType.Type.UNKNOWN);
val count = typeCounts.getOrDefault(mostPopularType, 0L);
val ratio = count * 1.0 / totalCount;
return InferredType.newBuilder().setType(mostPopularType).setRatio(ratio);
}
public void add(SchemaTracker other) {
final InferredType.Type[] allTypes = InferredType.Type.values();
for (val type : allTypes) {
if (this.typeCounts.containsKey(type) || other.typeCounts.containsKey(type)) {
this.typeCounts.merge(type, other.getCount(type), Long::sum);
}
}
}
public SchemaTracker merge(SchemaTracker other) {
val thisCopy = new SchemaTracker(Maps.newHashMap(typeCounts));
final InferredType.Type[] allTypes = InferredType.Type.values();
for (val type : allTypes) {
if (this.typeCounts.containsKey(type) || other.typeCounts.containsKey(type)) {
thisCopy.typeCounts.merge(type, other.getCount(type), Long::sum);
}
}
return thisCopy;
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/statistics | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/statistics/datatypes/CharPosTracker.java | package com.whylogs.core.statistics.datatypes;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet;
import com.google.common.base.Joiner;
import com.whylogs.core.SummaryConverters;
import com.whylogs.core.message.CharPosMessage;
import com.whylogs.core.message.CharPosSummary;
import com.whylogs.core.message.NumberSummary;
import com.whylogs.core.statistics.NumberTracker;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
@Slf4j
@AllArgsConstructor
public class CharPosTracker {
private Set<Character> characterList;
@Getter private final Map<Character, NumberTracker> charPosMap;
CharPosTracker(Set<Character> characterList) {
this.characterList = characterList;
this.charPosMap = newHashMap();
}
CharPosTracker(String charString, Map<Character, NumberTracker> charPosMap) {
this.characterList =
charString
.chars()
.mapToObj(chr -> (char) chr) // autoboxed to Character
.collect(Collectors.toSet());
this.charPosMap = charPosMap;
}
CharPosTracker(String charString) {
this(
charString
.chars()
.mapToObj(chr -> (char) chr) // autoboxed to Character
.collect(Collectors.toSet()));
}
CharPosTracker() {
this("abcdefghijklmnopqrstuvwzyz0123456789-@!#$%^&*()[]{}");
}
private void update(int idx, char c) {
if (characterList != null && characterList.contains(c)) {
if (!charPosMap.containsKey(c)) {
charPosMap.put(c, new NumberTracker());
}
charPosMap.get(c).track(idx);
} else {
if (!charPosMap.containsKey((char) 0)) {
charPosMap.put((char) 0, new NumberTracker());
}
charPosMap.get((char) 0).track(idx);
}
}
private void update(int idx, int codePoint) {
val chars = Character.toChars(codePoint);
if (chars.length == 1) {
update(idx, Character.toLowerCase(chars[0]));
} else {
if (!charPosMap.containsKey((char) 0)) {
charPosMap.put((char) 0, new NumberTracker());
}
charPosMap.get((char) 0).track(idx);
}
}
/**
* Track statistical properties of characters in a string.
*
* <p>`value` is a Unicode string. Position and frequency of all unicode codepoints in `value`
* that are contained in `characterList` will be tracked. Variants of this function signature
* allow modification of tracked character set during updates. Unless otherwise specified,
* `characterList` defaults to alpha-numeric lower-case characters.
*
* @param value string
*/
public void update(String value) {
val cp = value.codePoints().toArray();
for (int i = 0; i < cp.length; i++) {
update(i, cp[i]);
}
}
/**
* Track statistical properties of characters in a string.
*
* <p>`value` is a Unicode string. Position and frequency of all unicode codepoints in `value`
* that are contained in `characterList` will be tracked.
*
* @param value string
* @param charString string - Set of characters that should be tracked. all others will be tracked
* as 'NITL'
*/
public void update(String value, String charString) {
if (charString != null) {
val newSet =
charString
.chars()
.mapToObj(chr -> (char) chr) // autoboxed to Character
.collect(Collectors.toSet());
if (!characterList.equals(newSet)) {
if (!charPosMap.isEmpty()) {
log.warn(
"Changing character list, a non-empty character position tracker is being reset to remove ambiguities");
}
characterList = newSet;
charPosMap.clear();
}
}
val cp = value.codePoints().toArray();
for (int i = 0; i < cp.length; i++) {
update(i, cp[i]);
}
}
public CharPosTracker merge(CharPosTracker other) {
if (other == null) {
return this;
}
if (characterList != other.characterList && (charPosMap == null || other.charPosMap == null)) {
log.error("Merging two non-empty Character position tracker with different character lists");
}
Set<Character> newCharacterList = newHashSet();
newCharacterList.addAll(characterList);
newCharacterList.addAll(other.characterList);
// merge
Map<Character, NumberTracker> newCharPosMap = newHashMap();
newCharacterList.forEach(
c -> {
val tracker = charPosMap.get(c);
val otherTracker = other.charPosMap.get(c);
if (tracker != null && otherTracker != null) {
newCharPosMap.put(c, tracker.merge(otherTracker));
} else if (tracker != null) {
newCharPosMap.put(c, tracker);
} else if (otherTracker != null) {
newCharPosMap.put(c, otherTracker);
}
});
// merge not in the list
val nitlTracker = charPosMap.get((char) 0);
val otherNitlTracker = other.charPosMap.get((char) 0);
if (nitlTracker != null && otherNitlTracker != null) {
newCharPosMap.put((char) 0, nitlTracker.merge(otherNitlTracker));
} else if (nitlTracker != null) {
newCharPosMap.put((char) 0, nitlTracker);
} else if (otherNitlTracker != null) {
newCharPosMap.put((char) 0, otherNitlTracker);
}
return new CharPosTracker(newCharacterList, newCharPosMap);
}
public CharPosMessage toProtobuf() {
val mapMsg =
charPosMap.entrySet().stream()
.collect(
Collectors.toMap(
e -> e.getKey().toString(), e -> e.getValue().toProtobuf().build()));
return CharPosMessage.newBuilder()
.putAllCharPosMap(mapMsg)
.setCharList(Joiner.on("").join(characterList))
.build();
}
public static CharPosTracker fromProtobuf(CharPosMessage msg) {
Map<Character, NumberTracker> map = newHashMap();
msg.getCharPosMapMap().forEach((k, v) -> map.put(k.charAt(0), NumberTracker.fromProtobuf(v)));
return new CharPosTracker(msg.getCharList(), map);
}
public CharPosSummary toSummary() {
Map<String, NumberSummary> map = newHashMap();
// Internally characters that are not in `characterList` are tracked as the null character.
// In summary results, the catch-all tracker is called 'NITL', or Not-In-The-List.
val nullChar = new Character((char) 0);
charPosMap.forEach(
(k, v) ->
map.put(
k.equals(nullChar) ? "NITL" : k.toString(),
SummaryConverters.fromNumberTracker(v)));
return CharPosSummary.newBuilder()
.setCharacterList(Joiner.on("").join(characterList))
.putAllCharPosMap(map)
.build();
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/statistics | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/statistics/datatypes/StringTracker.java | package com.whylogs.core.statistics.datatypes;
import com.google.protobuf.ByteString;
import com.whylogs.core.message.StringsMessage;
import com.whylogs.core.statistics.NumberTracker;
import com.whylogs.core.utils.sketches.ThetaSketch;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.val;
import org.apache.datasketches.ArrayOfStringsSerDe;
import org.apache.datasketches.frequencies.ItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.theta.Union;
@Builder
@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public final class StringTracker {
public static Function<String, List<String>> TOKENIZER = str -> Arrays.asList(str.split(" "));
public static final ArrayOfStringsSerDe ARRAY_OF_STRINGS_SER_DE = new ArrayOfStringsSerDe();
// be careful to not use 32 here - somehow the sketches are empty
public static final int MAX_FREQUENT_ITEM_SIZE = 128;
private long count;
// sketches
private final ItemsSketch<String> items;
private final Union thetaSketch;
private final NumberTracker length;
private final NumberTracker tokenLength;
private final CharPosTracker charPosTracker;
@Builder.Default private Function<String, List<String>> tokenizer = TOKENIZER;
public StringTracker() {
this.count = 0L;
this.items = new ItemsSketch<>(MAX_FREQUENT_ITEM_SIZE); // TODO: make this value configurable
this.thetaSketch = Union.builder().buildUnion();
this.length = new NumberTracker();
this.tokenLength = new NumberTracker();
this.charPosTracker = new CharPosTracker();
this.tokenizer = TOKENIZER;
}
/**
* Track statistical properties of characters in a string.
*
* <p>`value` is a Unicode string. `value` is tokenized and tokens are passed to CharPosTracker
* for tracking of position and frequency of unicode codepoints in the token.
*
* <p>Variants of this function signature allow modification of tokenizer and tracked character
* set during updates. Unless overridden by one of the other update routines, uses a tokenizer
* that breaks strings at spaces, and tracks alphanumeric lowercase characters.
*
* @param value string
*/
public void update(String value) {
update(value, null);
}
/**
* Track statistical properties of just the characters from a given character set.
*
* <p>`value` is tokenized, and position and frequency of unicode codepoints within tokens are
* tracked if they appear in `charString`. If set, `charString` will be applied to subsequent
* calls to update, overriding the default character set.
*
* @param value string Unicode string to be tracked
* @param charString string - Set of characters that should be tracked. all others will be tracked
* as 'NITL'
*/
public void update(String value, String charString) {
if (value == null) {
return;
}
count++;
thetaSketch.update(value);
items.update(value);
charPosTracker.update(value, charString);
length.track(value.length());
// TODO allow updates of tokenizer
tokenLength.track(tokenizer.apply(value).size());
}
/**
* Track statistical properties of a string. Allows control over characters to be tracked and
* tokenizer function.
*
* <p>`value` is tokenized according to `tokenizer`. Position and frequency of unicode codepoints
* within tokens are tracked if they appear in `charString`. If set, `charString` and/or
* `tokenizer` will be used for subsequent calls to `update`
*
* @param value string
* @param charString string - Set of characters that should be tracked. all others will be tracked
* as 'NITL'
* @param tokenizer function taking string and returning list of strings.
*/
public void update(String value, String charString, Function<String, List<String>> tokenizer) {
if (tokenizer != null) {
this.tokenizer = tokenizer;
}
update(value, charString);
}
/**
* Merge this StringTracker object with another. This merges the sketches as well
*
* @param other the other String tracker to merge
* @return a new StringTracker object
*/
public StringTracker merge(StringTracker other) {
ItemsSketch<String> itemsCopy = null;
if (other == null) {
return this;
}
if (this.items != null) {
val bytes = this.items.toByteArray(ARRAY_OF_STRINGS_SER_DE);
itemsCopy = ItemsSketch.getInstance(WritableMemory.wrap(bytes), ARRAY_OF_STRINGS_SER_DE);
itemsCopy.merge(other.items);
} else if (other.items != null) {
val bytes = other.items.toByteArray(ARRAY_OF_STRINGS_SER_DE);
itemsCopy = ItemsSketch.getInstance(WritableMemory.wrap(bytes), ARRAY_OF_STRINGS_SER_DE);
}
val thetaUnion = Union.builder().buildUnion();
thetaUnion.update(this.thetaSketch.getResult());
thetaUnion.update(other.thetaSketch.getResult());
NumberTracker newLength = length;
if (length != null && other != null) {
newLength = length.merge(other.length);
}
NumberTracker newTokenLength = tokenLength;
if (tokenLength != null && other != null) {
newTokenLength = tokenLength.merge(other.tokenLength);
}
CharPosTracker newCharPostTracker = charPosTracker;
if (charPosTracker != null && other != null) {
newCharPostTracker = charPosTracker.merge(other.charPosTracker);
}
return StringTracker.builder()
.count(this.count + other.count)
.items(itemsCopy)
.thetaSketch(thetaUnion)
.length(newLength)
.tokenLength(newTokenLength)
.charPosTracker(newCharPostTracker)
.build();
}
public StringsMessage.Builder toProtobuf() {
val builder = StringsMessage.newBuilder().setCount(count);
if (length != null) {
builder.setLength(length.toProtobuf());
}
if (tokenLength != null) {
builder.setTokenLength(tokenLength.toProtobuf());
}
if (charPosTracker != null) {
builder.setCharPosTracker(charPosTracker.toProtobuf());
}
if (thetaSketch != null) {
builder.setCompactTheta(ThetaSketch.serialize(thetaSketch));
}
if (items != null) {
builder.setItems(ByteString.copyFrom(items.toByteArray(ARRAY_OF_STRINGS_SER_DE)));
}
return builder;
}
public static StringTracker fromProtobuf(StringsMessage message) {
ItemsSketch<String> items = null;
val ba = message.getItems().toByteArray();
if (ba.length > 8) {
val iMem = Memory.wrap(ba);
items = ItemsSketch.getInstance(iMem, ARRAY_OF_STRINGS_SER_DE);
}
val builder =
StringTracker.builder()
.count(message.getCount())
.items(items)
.thetaSketch(ThetaSketch.deserialize(message.getCompactTheta()));
// backward compatibility - only decode these messages if they exist
// older profiles written by python library may not have these fields.
if (message.hasLength()) {
builder
.length(NumberTracker.fromProtobuf(message.getLength()))
.tokenLength(NumberTracker.fromProtobuf(message.getTokenLength()))
.charPosTracker(CharPosTracker.fromProtobuf(message.getCharPosTracker()));
}
return builder.build();
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/statistics | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/statistics/datatypes/VarianceTracker.java | package com.whylogs.core.statistics.datatypes;
import com.whylogs.core.message.VarianceMessage;
import lombok.Getter;
import lombok.val;
@Getter
public class VarianceTracker {
long count;
double sum; // sample variance * (n-1)
double mean;
public VarianceTracker() {
this.count = 0L;
this.sum = 0L;
this.mean = 0L;
}
// Based on
// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
public void update(double newValue) {
count++;
double delta = newValue - mean;
mean += delta / count;
double delta2 = newValue - mean;
sum += delta * delta2;
}
/** @return sample standard deviation */
public double stddev() {
return Math.sqrt(this.variance());
}
/** @return the sample variance */
public double variance() {
if (count == 0) {
return Double.NaN;
}
if (count == 1) {
return 0;
}
return sum / (count - 1.0);
}
/** https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm */
public void add(VarianceTracker other) {
if (other == null || other.count == 0L) {
return;
}
if (this.count == 0L) {
this.count = other.count;
this.mean = other.mean;
this.sum = other.sum;
return;
}
val delta = this.mean - other.mean;
val totalCount = this.count + other.count;
this.sum += other.sum + Math.pow(delta, 2) * this.count * other.count / (double) totalCount;
val thisRatio = this.count / (double) totalCount;
val otherRatio = 1.0 - thisRatio;
this.mean = this.mean * thisRatio + other.mean * otherRatio;
this.count += other.count;
}
public VarianceTracker merge(VarianceTracker other) {
final VarianceTracker thisCopy = this.copy();
thisCopy.add(other);
return thisCopy;
}
VarianceTracker copy() {
val result = new VarianceTracker();
result.count = this.count;
result.sum = this.sum;
result.mean = this.mean;
return result;
}
public VarianceMessage.Builder toProtobuf() {
return VarianceMessage.newBuilder().setCount(count).setMean(mean).setSum(sum);
}
public static VarianceTracker fromProtobuf(VarianceMessage message) {
final VarianceTracker tracker = new VarianceTracker();
tracker.count = message.getCount();
tracker.mean = message.getMean();
tracker.sum = message.getSum();
return tracker;
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/types/TypedDataConverter.java | package com.whylogs.core.types;
import static java.util.stream.Collectors.toSet;
import com.whylogs.core.message.InferredType;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import lombok.experimental.UtilityClass;
import lombok.val;
@UtilityClass
public class TypedDataConverter {
public static final Set<InferredType.Type> NUMERIC_TYPES =
Stream.of(InferredType.Type.FRACTIONAL, InferredType.Type.INTEGRAL).collect(toSet());
private final Pattern FRACTIONAL = Pattern.compile("^[-+]? ?\\d+[.]\\d+$");
private final Pattern INTEGRAL = Pattern.compile("^[-+]? ?\\d+$");
private final Pattern BOOLEAN = Pattern.compile("^(?i)true|false$");
private final Pattern EMPTY_SPACES = Pattern.compile("\\s");
private final ThreadLocal<Matcher> FRACTIONAL_MATCHER =
ThreadLocal.withInitial(() -> FRACTIONAL.matcher(""));
private final ThreadLocal<Matcher> INTEGRAL_MATCHER =
ThreadLocal.withInitial(() -> INTEGRAL.matcher(""));
private final ThreadLocal<Matcher> BOOLEAN_MATCHER =
ThreadLocal.withInitial(() -> BOOLEAN.matcher(""));
private final ThreadLocal<Matcher> EMPTY_SPACES_REMOVER =
ThreadLocal.withInitial(() -> EMPTY_SPACES.matcher(""));
public TypedData convert(Object data) {
if (data == null) {
return null;
}
if (data instanceof TypedData) {
return (TypedData) data;
}
if (data instanceof String) {
return getTypedStringData((String) data);
}
if (data instanceof Double || data instanceof Float) {
final double doubleValue = ((Number) data).doubleValue();
return TypedData.fractionalValue(doubleValue);
}
if (data instanceof Integer || data instanceof Long || data instanceof Short) {
final long longValue = ((Number) data).longValue();
return TypedData.integralValue(longValue);
}
if (data instanceof Boolean) {
return TypedData.booleanValue((boolean) data);
}
return TypedData.unknownValue();
}
private TypedData getTypedStringData(String data) {
if (System.getenv().get("WHYLOGS_ENABLE_STRING_MATCHING") != null) {
INTEGRAL_MATCHER.get().reset(data);
if (INTEGRAL_MATCHER.get().matches()) {
val trimmedText = EMPTY_SPACES_REMOVER.get().reset(data).replaceAll("");
return TypedData.integralValue(Long.parseLong(trimmedText));
}
FRACTIONAL_MATCHER.get().reset(data);
if (FRACTIONAL_MATCHER.get().matches()) {
val trimmedText = EMPTY_SPACES_REMOVER.get().reset(data).replaceAll("");
return TypedData.fractionalValue(Double.parseDouble(trimmedText));
}
BOOLEAN_MATCHER.get().reset(data);
if (BOOLEAN_MATCHER.get().matches()) {
val trimmedText = EMPTY_SPACES_REMOVER.get().reset(data).replaceAll("");
return TypedData.booleanValue(Boolean.parseBoolean(trimmedText));
}
}
return TypedData.stringValue(data);
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/utils | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/utils/sketches/FrequentStringsSketch.java | package com.whylogs.core.utils.sketches;
import com.google.protobuf.ByteString;
import com.whylogs.core.message.FrequentItemsSketchMessage;
import com.whylogs.core.message.FrequentNumbersSketchMessage;
import lombok.experimental.UtilityClass;
import lombok.val;
import org.apache.datasketches.ArrayOfStringsSerDe;
import org.apache.datasketches.frequencies.ItemsSketch;
import org.apache.datasketches.memory.Memory;
@UtilityClass
public class FrequentStringsSketch {
public static final int FREQUENT_MAX_LG_K = 7;
public static final ArrayOfStringsSerDe ARRAY_OF_STRINGS_SER_DE = new ArrayOfStringsSerDe();
public ItemsSketch<String> create() {
return new ItemsSketch<>((int) Math.pow(2, FREQUENT_MAX_LG_K));
}
public ByteString serialize(ItemsSketch<String> sketch) {
return ByteString.copyFrom(sketch.toByteArray(ARRAY_OF_STRINGS_SER_DE));
}
public FrequentItemsSketchMessage.Builder toStringSketch(ItemsSketch<String> sketch) {
return FrequentItemsSketchMessage.newBuilder()
.setLgMaxK(FREQUENT_MAX_LG_K)
.setSketch(ByteString.copyFrom(sketch.toByteArray(ARRAY_OF_STRINGS_SER_DE)));
}
public FrequentNumbersSketchMessage.Builder toNumbersMessage(ItemsSketch<String> sketch) {
return FrequentNumbersSketchMessage.newBuilder()
.setLgMaxK(FREQUENT_MAX_LG_K)
.setSketch(ByteString.copyFrom(sketch.toByteArray(ARRAY_OF_STRINGS_SER_DE)));
}
public ItemsSketch<String> deserialize(ByteString bytes) {
val data = bytes.toByteArray();
ItemsSketch<String> freqNumbers;
if (data.length > 8) {
return ItemsSketch.getInstance(Memory.wrap(data), ARRAY_OF_STRINGS_SER_DE);
} else {
// Create an empty sketch
return create();
}
}
}
|
0 | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/utils | java-sources/ai/whylabs/whylogs-java-core/0.1.8-b0/com/whylogs/core/utils/sketches/ThetaSketch.java | package com.whylogs.core.utils.sketches;
import com.google.protobuf.ByteString;
import lombok.experimental.UtilityClass;
import lombok.val;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.theta.Sketch;
import org.apache.datasketches.theta.Union;
@UtilityClass
public class ThetaSketch {
public ByteString serialize(Union thetaUnionSketch) {
return ByteString.copyFrom(thetaUnionSketch.getResult().toByteArray());
}
public Union deserialize(ByteString data) {
val sketch = Sketch.heapify(Memory.wrap(data.toByteArray()));
val union = Union.builder().buildUnion();
union.update(sketch);
return union;
}
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/Concept.java | package ai.xpl.android.client;
public class Concept {
public String displayName;
public String conceptId;
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/Config.java | package ai.xpl.android.client;
import android.content.Context;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Config {
public static final String DATA_API_URI = "https://dataapi-dev-7mvc6un3ya-ez.a.run.app";
public static final String ROOT_DIR = "xplai";
public static final String CONFIG_FILE_NAME = "config.json";
private static final Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setPrettyPrinting()
.create();
private static Config config;
public Map<String, TaskData> tasksDataObjects = new ConcurrentHashMap<>();
private Config(Map<String, TaskData> taskDataObjects) {
this.tasksDataObjects = taskDataObjects;
}
private void save(Context context) {
try {
String json = gson.toJson(this.tasksDataObjects);
File dir = context.getDir(ROOT_DIR, Context.MODE_PRIVATE);
File configFile = new File(dir, CONFIG_FILE_NAME);
FileOutputStream outputStream = new FileOutputStream(configFile);
outputStream.write(json.getBytes(StandardCharsets.UTF_8));
outputStream.close();
}
catch (Exception ignored){
ignored.printStackTrace();
}
}
public void putTaskData(Context context, TaskData taskData) {
tasksDataObjects.put(taskData.taskId, taskData);
save(context);
}
public TaskData getTaskData(String taskId){
if (tasksDataObjects.containsKey(taskId)){
return tasksDataObjects.get(taskId);
}
return null;
}
public static Config getInstance(Context context){
if (Config.config != null){
//// Config has been already loaded
return Config.config;
}
//// Config wasn't loaded before
if (Config.configFileExists(context)){
//// Config file exists, hence load from file
try {
File dir = context.getDir(ROOT_DIR, Context.MODE_PRIVATE);
File configFile = new File(dir, CONFIG_FILE_NAME);
FileInputStream fileInputStream = new FileInputStream(configFile);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
ConcurrentHashMap<String, TaskData> data = gson.fromJson(inputStreamReader, new TypeToken<ConcurrentHashMap<String, TaskData>>() {}.getType());
Config.config = new Config(data);
inputStreamReader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
else {
//// Config has never been on the device, hence create new.
Config.config = new Config(new ConcurrentHashMap<>());
}
//// at this point config has been initialized one way or another.
return Config.config;
}
private static boolean configFileExists(Context context) {
File dir = context.getDir(ROOT_DIR, Context.MODE_PRIVATE);
File configFile = new File(dir, CONFIG_FILE_NAME);
return configFile.exists();
}
} |
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/DataApiClient.java | package ai.xpl.android.client;
import android.graphics.Bitmap;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class DataApiClient {
private static final Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setPrettyPrinting()
.create();
public static void postDataPoint(RequestQueue requestQueue, DataPoint dataPoint, String taskApiKey){
String url = Config.DATA_API_URI + "/upload/" + dataPoint.taskId + "/" + dataPoint.dataPointId;
Map<String, byte[]> binaries = dataPoint.binaries;
dataPoint.binaries = null;
Map<String, Bitmap> bitmaps = dataPoint.bitmaps;
dataPoint.bitmaps = null;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
response -> {
HashMap<String, ResourceForUpload> resoucesForUpload =
gson.fromJson(response, new TypeToken<HashMap<String, ResourceForUpload>>() {}.getType());
//// upload binaries
for(String fileName : binaries.keySet()){
// byte[] binary = binaries.get(fileName);
byte[] binary = makePng(bitmaps.get(fileName));
if (resoucesForUpload.containsKey(fileName)) {
dataPoint.fileUris.add(resoucesForUpload.get(fileName).url);
postBinary(requestQueue, binary, resoucesForUpload.get(fileName).urlForUpload);
}
}
//// upload data_point.json
if (resoucesForUpload.containsKey("data_point.json")) {
byte[] binary = gson.toJson(dataPoint).getBytes(StandardCharsets.UTF_8);
postBinary(requestQueue, binary, resoucesForUpload.get("data_point.json").urlForUpload);
}
postDataPointMetadata(requestQueue, dataPoint, taskApiKey);
},
error -> { error.printStackTrace(); }
) {
@Override
public byte[] getBody() {
Object [] keyArray = binaries.keySet().toArray();
ArrayList<Object> fileNames = new ArrayList<>(Arrays.asList(keyArray));
fileNames.add("data_point.json");
String json = gson.toJson(fileNames.toArray());
return json.getBytes(StandardCharsets.UTF_8);
}
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("task_api_key", taskApiKey);
params.put("content-type", "application/json");
return params;
}
};
requestQueue.add(stringRequest);
}
private static void postBinary(RequestQueue requestQueue, byte[] binary, String url){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
response -> {
},
error -> {
error.printStackTrace();
}) {
@Override
public byte[] getBody() {
return binary;
}
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("content-type", "image/png");
return params;
}
};
requestQueue.add(stringRequest);
}
private static void postDataPointMetadata(RequestQueue requestQueue, DataPoint dataPoint, String taskApiKey) {
String url = Config.DATA_API_URI + "/datapoints";
dataPoint.binaries = null;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
response -> {
},
error -> { error.printStackTrace(); }
) {
@Override
public byte[] getBody() {
DataPoint [] dataPoints = new DataPoint[] {dataPoint};
String json = gson.toJson(dataPoints);
return json.getBytes(StandardCharsets.UTF_8);
}
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("task_api_key", taskApiKey);
params.put("content-type", "application/json");
return params;
}
};
requestQueue.add(stringRequest);
}
private static byte[] makePng(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] result = byteArrayOutputStream.toByteArray();
return result;
}
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/DataItem.java | package ai.xpl.android.client;
import java.util.Map;
public class DataItem {
public String conceptId;
public String instanceId;
public String predictorType;
public String predictorId;
public String inputSet;
public float logInformativeness;
public float logitConfidence;
public Map<String, Float> location;
public String text;
public float value;
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/DataPoint.java | package ai.xpl.android.client;
import android.graphics.Bitmap;
import java.util.List;
import java.util.Map;
public class DataPoint {
public String dataPointId;
public String taskId;
public Map<String, byte[]> binaries;
public Map<String, Bitmap> bitmaps;
public String localFilename;
public List<String> fileUris;
public List<DataItem> dataItems;
public String previousDataPointId;
public String nextDataPointId;
public String collectedByDeviceFingerprintId;
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/InputStreamVolleyRequest.java | package ai.xpl.android.client;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import java.util.HashMap;
import java.util.Map;
class InputStreamVolleyRequest extends Request<byte[]> {
private final Response.Listener<byte[]> mListener;
private Map<String, String> mParams;
//create a static map for directly accessing headers
public Map<String, String> responseHeaders ;
public InputStreamVolleyRequest(int method, String mUrl ,Response.Listener<byte[]> listener,
Response.ErrorListener errorListener, HashMap<String, String> params) {
// TODO Auto-generated constructor stub
super(method, mUrl, errorListener);
// this request would never use cache.
setShouldCache(false);
mListener = listener;
mParams=params;
}
@Override
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return mParams;
};
@Override
protected void deliverResponse(byte[] response) {
mListener.onResponse(response);
}
@Override
protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
//Initialise local responseHeaders map with response headers received
responseHeaders = response.headers;
//Pass the response data here
return Response.success( response.data, HttpHeaderParser.parseCacheHeaders(response));
}
} |
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/Location.java | package ai.xpl.android.client;
public class Location {
public Double centerX;
public Double centerY;
public Double halfWidth;
public Double halfHeight;
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/Model.java | package ai.xpl.android.client;
import java.util.HashMap;
public class Model {
public String modelId;
public HashMap<String, ModelComponent> components;
public HashMap<String, String> output;
public int version;
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/ModelComponent.java | package ai.xpl.android.client;
public class ModelComponent {
public String urlForDownload;
public String name;
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/PredictedInstance.java | package ai.xpl.android.client;
public class PredictedInstance {
public String instanceId;
public String conceptId;
public String conceptDisplayName;
public Location location;
public String text;
public float value;
public String comment;
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/ResourceForUpload.java | package ai.xpl.android.client;
public class ResourceForUpload {
public String urlForUpload;
public String url;
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/Task.java | package ai.xpl.android.client;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.pytorch.Device;
import org.pytorch.IValue;
import org.pytorch.LiteModuleLoader;
import org.pytorch.Module;
import org.pytorch.Tensor;
import org.pytorch.torchvision.TensorImageUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
public class Task {
static float[] NO_MEAN_RGB = new float[] {0.0f, 0.0f, 0.0f};
static float[] NO_STD_RGB = new float[] {1.0f, 1.0f, 1.0f};
public TaskData data;
private String deviceFingerprints;
private Context context;
private RequestQueue requestQueue;
private Map<String, Concept> concepts = new HashMap<>();
public Map<String, Module> modules = new HashMap<>();
public Task(TaskData taskData, Context context, RequestQueue requestQueue){
this.data = taskData;
for(Concept concept : data.concepts){
concepts.put(concept.conceptId, concept);
}
this.context = context;
this.requestQueue = requestQueue;
this.deviceFingerprints = GetMacAddress();
}
public List<PredictedInstance> execute(Bitmap bitmap) {
List<PredictedInstance> result = new ArrayList<>();
StringBuilder performance_metrics = new StringBuilder();
// 1.
long start = System.currentTimeMillis();
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 320,512, true);
Tensor inputTensor = TensorImageUtils.bitmapToFloat32Tensor(resizedBitmap, NO_MEAN_RGB, NO_STD_RGB);
Map<String, IValue> input = new HashMap<>();
input.put("image", IValue.from(inputTensor));
IValue inputs = IValue.dictStringKeyFrom(input);
// Module tail = this.modules.get(getTailComponentName());
Module head = this.modules.get(getHeadComponentName());
//
// performance_metrics.append("1. Preparing input " + Long.toString(System.currentTimeMillis() - start) + "ms\n");
//
// // 2.
// start = System.currentTimeMillis();
//
// IValue output = tail.forward(inputs);
//
// performance_metrics.append("2. tail.forward " + Long.toString(System.currentTimeMillis() - start) + "ms\n");
// 3.
start = System.currentTimeMillis();
IValue output = head.forward(inputs);
IValue[] outputList = output.toList();
for (IValue prediction: outputList) {
Map<String,IValue> predictionDict = prediction.toDictStringKey();
PredictedInstance instance = new PredictedInstance();
instance.conceptId = predictionDict.get("concept_id").toStr();
instance.text = predictionDict.get("text").toStr();
instance.conceptDisplayName = this.concepts.get(instance.conceptId).displayName;
instance.location = new Location();
instance.location.centerX = predictionDict.get("center_x").toDouble();
instance.location.centerY = predictionDict.get("center_y").toDouble();
instance.location.halfWidth = predictionDict.get("hallf_width").toDouble();
instance.location.halfHeight = predictionDict.get("half_height").toDouble();
result.add(instance);
}
performance_metrics.append("3. head.forward " + Long.toString(System.currentTimeMillis() - start) + "ms\n");
// 4.
start = System.currentTimeMillis();
// Map<String, IValue> dictOutput = output.toDictStringKey();
// Tensor locationsTensor = dictOutput.get("pred_" + data.name+ "_locations").toTensor();
// Tensor labelTensor = dictOutput.get("pred_" + data.name + "_label").toTensor();
// Tensor objectivenessTensor = dictOutput.get("pred_" + data.name + "_objectiveness").toTensor();
// IValue informativeness = dictOutput.get("pred_" + data.name + "_informativeness");
// if (locationsTensor != null) { // test stub
//// if (informativeness != null) {
//// if (this.shouldSample(informativeness.toTensor())){
// if (this.shouldSample(locationsTensor)){
// this.sendSampleDataPoint(bitmap, locationsTensor, labelTensor, objectivenessTensor);
// }
// }
performance_metrics.append("4.Taking sample " + Long.toString(System.currentTimeMillis() - start) + "ms\n");
if (result.size() > 0){
result.get(0).comment = performance_metrics.toString();
}
return result;
}
public List<PredictedInstance> execute(String text) {
List<PredictedInstance> result = new ArrayList<>();
return result;
}
private Boolean shouldSample(Tensor informativeness){
return true;
}
private void sendSampleDataPoint(Bitmap imageSample, Tensor location, Tensor label, Tensor confidence) {
DataPoint dataPoint = new DataPoint();
dataPoint.dataPointId = UUID.randomUUID().toString().replace("-", "");;
dataPoint.taskId = this.data.taskId;
dataPoint.dataItems = new ArrayList<>();
dataPoint.collectedByDeviceFingerprintId = this.deviceFingerprints;
dataPoint.fileUris = new ArrayList<>();
DataItem dataItem = new DataItem();
dataItem.conceptId = "test_mobile_concept";
dataItem.instanceId = UUID.randomUUID().toString().replace("-", "");;
dataItem.predictorType = "model";
dataItem.predictorId = this.data.model.modelId;
dataItem.inputSet = "train";
dataItem.logInformativeness = 0.5f;
dataItem.logitConfidence = 0.5f;
dataItem.location = new HashMap<>();
dataItem.text = "Test text";
dataItem.value = 0.12345f;
dataItem.location.put("center_x", 0.5f);
dataItem.location.put("center_y", 0.5f);
dataItem.location.put("half_width", 0.5f);
dataItem.location.put("half_height", 0.5f);
dataPoint.dataItems.add(dataItem);
dataPoint.bitmaps = new HashMap<>();
dataPoint.bitmaps.put("input.png", imageSample);
dataPoint.binaries = new HashMap<>();
dataPoint.binaries.put("input.png", new byte[] {1});
// dataPoint.binaries.put("input.png", makePng(imageSample));
DataApiClient.postDataPoint(this.requestQueue, dataPoint, this.data.taskApiKey);
}
private String GetMacAddress() {
WifiManager manager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
return info.getMacAddress();
}
private byte[] makePng(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] result = byteArrayOutputStream.toByteArray();
return result;
}
public void loadComponents(Context context) throws Exception {
for (ModelComponent component: this.data.model.components.values()){
if (this.modules.get(component.name) == null) {
File dir = context.getDir("xplai", Context.MODE_PRIVATE);
String filename = getComponentFileName(component.name);
if (!fileExists(context, filename)){
throw new Exception("Component file '" + filename + "' is not present on device.");
}
File componentFile = new File(dir, filename);
Module module = LiteModuleLoader.load(componentFile.getAbsolutePath(), new HashMap<>(), Device.CPU);
modules.put(component.name, module);
}
}
}
public void downloadModelComponent(Context context, RequestQueue requestQueue, String componentName) {
String url = Objects.requireNonNull(this.data.model.components.get(componentName)).urlForDownload;
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, url,
new Response.Listener<byte[]>() {
@Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response!=null) {
File dir = context.getDir(Config.ROOT_DIR, Context.MODE_PRIVATE);
String fileName = getComponentFileName(componentName);
File componentFile = new File(dir, fileName);
FileOutputStream outputStream = new FileOutputStream(componentFile);
outputStream.write(response);
outputStream.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
} ,new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
requestQueue.add(request);
}
public boolean componentFileExists(Context context, String componentName){
String componentFileName = getComponentFileName(componentName);
return fileExists(context, componentFileName);
}
private boolean fileExists(Context context, String filename){
File dir = context.getDir("xplai", Context.MODE_PRIVATE);
File componentFile = new File(dir, filename);
return componentFile.exists();
}
public String getComponentFileName(String componentName){
componentName = Objects.requireNonNull(this.data.model.components.get(componentName)).name;
return this.data.taskId + "__" + "v" + this.data.model.version + "__" + componentName;
}
private String getTailComponentName() {
return this.data.modality + "_rep.ptl";
}
private String getHeadComponentName() {
return this.data.name + "_head.ptl";
}
private String getModelSingleComponentName() {
return this.data.name + ".ptl";
}
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/TaskData.java | package ai.xpl.android.client;
import java.util.ArrayList;
/**
* A DTO object to hold task related data
*/
public class TaskData {
public String taskId;
public String name;
public ArrayList<Concept> concepts;
public String modelId;
public String modelVersion;
public String modality = "image";
public Model model;
public String taskApiKey;
}
|
0 | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android | java-sources/ai/xpl/xpl-android-client/1.0.0.0/ai/xpl/android/client/TaskPool.java | package ai.xpl.android.client;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class TaskPool {
static String USER_API_URI = "https://userapi-dev-7mvc6un3ya-ez.a.run.app";
static Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
static RequestQueue requestQueue;
static Config config;
static Boolean poolInitialized;
public static void registerTask(Context context, String taskId, String taskApiKey) {
if (TaskPool.requestQueue == null) {
TaskPool.requestQueue = Volley.newRequestQueue(context);
}
if (TaskPool.config == null){
TaskPool.config = Config.getInstance(context);
}
TaskPool.poolInitialized = true;
reloadTask(context, taskId, taskApiKey);
}
public static Task getTask(Context context, String taskId) throws Exception {
if (!poolInitialized) {
throw new Exception("TaskPool has not been initialized. Initialize task pool" +
"by TaskPool.registerInstance for at least 1 Task");
}
TaskData taskData = TaskPool.config.getTaskData(taskId);
if (taskData == null) {
throw new Exception("Task wasn't registered in the pool." +
"Use TaskPool.registerInstance to register task.");
}
Task task = new Task(taskData, context, requestQueue);
task.loadComponents(context);
return task;
}
private static void reloadTask(Context context, String taskId, String taskApiKey) {
TaskData localTaskData = TaskPool.config.getTaskData(taskId);
String url = USER_API_URI + "/task/" + taskId;
TaskData finalLocalTaskData = localTaskData;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
response -> {
TaskData remoteTaskData = gson.fromJson(response, TaskData.class);
//// Only leave _cpu.ptl files and ignore the rest
ArrayList<String> removeComponents = new ArrayList<>();
for (ModelComponent modelComponent: remoteTaskData.model.components.values()) {
if (!modelComponent.name.endsWith(".ptl")) {
removeComponents.add(modelComponent.name);
}
}
for (String componentName: removeComponents){
remoteTaskData.model.components.remove(componentName);
}
// if (finalLocalTaskData != null && remoteTaskData.model.version != finalLocalTaskData.model.version){
// //// Task exists locally, but there is a new version remotely.
// tasksPendingUpdate.put(taskId, remoteTaskData);
// }
if (finalLocalTaskData == null) {
remoteTaskData.taskApiKey = taskApiKey;
TaskPool.config.putTaskData(context, remoteTaskData);
}
Task remoteTask = new Task(remoteTaskData, context, requestQueue);
for (String modelComponentKey: remoteTaskData.model.components.keySet()){
if (!remoteTask.componentFileExists(context, modelComponentKey)) {
remoteTask.downloadModelComponent(context, requestQueue, modelComponentKey);
}
}
},
error -> {
error.printStackTrace();
// Handle error states
// if response.status_code == 404:
// raise TaskNotFoundException(f'Task "{task_id}" not found.')
//
// elif response.status_code != 200:
// raise Exception(f'Http error {response.status_code}.')
}) {
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("task_api_key", taskApiKey);
return params;
}
};
requestQueue.add(stringRequest);
}
}
|
0 | java-sources/ai/yda-framework/channel-core/0.1.0/ai/yda/framework/channel | java-sources/ai/yda-framework/channel-core/0.1.0/ai/yda/framework/channel/core/Channel.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.channel.core;
/**
* Provides a generic interface for implementing communication gateways to the Assistant.
*
* @param <REQUEST> the generic type of the Request from the User.
* @param <RESPONSE> the generic type of the Response that will be generated based on the given Request.
* @author Nikita Litvinov
* @see StreamingChannel
* @since 0.1.0
*/
public interface Channel<REQUEST, RESPONSE> {
/**
* Processes Request data involving the Assistant.
*
* @param request the Request object to be processed.
* @return the Response object generated after processing the Request.
*/
RESPONSE processRequest(REQUEST request);
}
|
0 | java-sources/ai/yda-framework/channel-core/0.1.0/ai/yda/framework/channel | java-sources/ai/yda-framework/channel-core/0.1.0/ai/yda/framework/channel/core/StreamingChannel.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.channel.core;
import reactor.core.publisher.Flux;
/**
* Provides a generic interface for implementing communication gateways to the streaming Assistant.
*
* @param <REQUEST> the generic type of the Request from the User.
* @param <RESPONSE> the generic type of the Response that will be generated based on the given Request.
* @author Nikita Litvinov
* @see Channel
* @since 0.1.0
*/
public interface StreamingChannel<REQUEST, RESPONSE> {
Flux<RESPONSE> processRequest(REQUEST request);
}
|
0 | java-sources/ai/yda-framework/channel-shared/0.1.0/ai/yda/framework/channel | java-sources/ai/yda-framework/channel-shared/0.1.0/ai/yda/framework/channel/shared/RestChannelProperties.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.channel.shared;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
/**
* Abstract class providing common properties for REST Channel configurations.
*
* @author Nikita Litvinov
* @since 0.1.0
*/
@Setter
@Getter
public abstract class RestChannelProperties {
/**
* The default relative path for the REST endpoint.
*/
public static final String DEFAULT_ENDPOINT_RELATIVE_PATH = "/";
/**
* The relative path for the REST endpoint. This path can be customized based on specific configurations.
* By default, it is set to {@link #DEFAULT_ENDPOINT_RELATIVE_PATH}.
*/
private String endpointRelativePath = RestChannelProperties.DEFAULT_ENDPOINT_RELATIVE_PATH;
/**
* The security token used for authenticating requests to the REST endpoint.
* This token is expected to be provided by the client for authorization purposes.
*/
private String securityToken;
/**
* Enable or disable CORS.
*/
private Boolean corsEnabled = Boolean.TRUE;
/**
* List of allowed origins for CORS.
*/
private List<String> allowedOrigins = List.of("*");
/**
* List of allowed methods for CORS.
*/
private List<String> allowedMethods = List.of("GET", "POST", "PUT", "DELETE");
}
|
0 | java-sources/ai/yda-framework/channel-shared/0.1.0/ai/yda/framework/channel | java-sources/ai/yda-framework/channel-shared/0.1.0/ai/yda/framework/channel/shared/TokenAuthentication.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.channel.shared;
import java.io.Serial;
import java.io.Serializable;
import java.util.Collection;
import lombok.Getter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.util.Assert;
/**
* Represents a bearer token based Authentication.
*
* @author Nikita Litvinov
* @since 0.1.0
*/
@Getter
public class TokenAuthentication extends AbstractAuthenticationToken implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* Multiplier used in hash code calculations to ensure uniqueness.
*/
private static final Short HASH_CODE_MULTIPLIER = 31;
/**
* The principal (e.g., username) associated with the authentication token.
*/
private final Object principal;
/**
* A hash of the key, used to verify the integrity of the token.
*/
private final int keyHash;
/**
* Constructs a new {@link TokenAuthentication} instance with the specified key.
* The token itself is not stored in this instance; instead, only its hash is stored.
* The principal is set to "anonymousUser" and the authorities are set to "ROLE_ANONYMOUS".
*
* @param key the authentication key.
*/
public TokenAuthentication(final String key) {
this(extractKeyHash(key), "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
}
/**
* Constructs new {@link TokenAuthentication} instance with the specified key, principal, and authorities.
*
* @param key the authentication key.
* @param principal the principal (e.g., username).
* @param authorities the authorities granted to the principal.
*/
public TokenAuthentication(
final String key, final Object principal, final Collection<? extends GrantedAuthority> authorities) {
this(extractKeyHash(key), principal, authorities);
}
/**
* Constructs new {@link TokenAuthentication} with the specified key hash, principal, and authorities. The token is
* set as authenticated.
*
* @param keyHash the hash of the authentication key.
* @param principal the principal (e.g., username).
* @param authorities the authorities granted to the principal.
*/
private TokenAuthentication(
final Integer keyHash, final Object principal, final Collection<? extends GrantedAuthority> authorities) {
super(authorities);
Assert.isTrue(principal != null && !"".equals(principal), "principal cannot be null or empty");
Assert.notEmpty(authorities, "authorities cannot be null or empty");
this.keyHash = keyHash;
this.principal = principal;
setAuthenticated(true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object obj) {
if (!super.equals(obj)) {
return false;
}
if (obj instanceof TokenAuthentication test) {
return this.getKeyHash() == test.getKeyHash();
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int result = super.hashCode();
result = TokenAuthentication.HASH_CODE_MULTIPLIER * result + this.keyHash;
return result;
}
/**
* {@inheritDoc}
*/
@Override
public Object getCredentials() {
return keyHash;
}
/**
* Extracts the hash code of the specified key.
*
* @param key the key for which to extract the hash code.
* @return the hash code of the key.
*/
public static Integer extractKeyHash(final String key) {
Assert.hasLength(key, "key cannot be empty or null");
return key.hashCode();
}
}
|
0 | java-sources/ai/yda-framework/channel-shared/0.1.0/ai/yda/framework/channel | java-sources/ai/yda-framework/channel-shared/0.1.0/ai/yda/framework/channel/shared/TokenAuthenticationException.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.channel.shared;
import org.springframework.security.core.AuthenticationException;
/**
* Thrown if an authentication request is rejected because the token is invalid.
*
* @author Nikita Litvinov
* @since 0.1.0
*/
public class TokenAuthenticationException extends AuthenticationException {
/**
* Constructs a new {@link TokenAuthenticationException} instance with the predefined message "Authentication token
* is invalid".
*/
public TokenAuthenticationException() {
super("Authentication token is invalid");
}
}
|
0 | java-sources/ai/yda-framework/filesystem-retriever/0.1.0/ai/yda/framework/rag/retriever | java-sources/ai/yda-framework/filesystem-retriever/0.1.0/ai/yda/framework/rag/retriever/filesystem/FilesystemRetriever.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.retriever.filesystem;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.lang.NonNull;
import ai.yda.framework.rag.core.model.RagContext;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.retriever.Retriever;
import ai.yda.framework.rag.retriever.filesystem.service.FilesystemService;
/**
* Retrieves filesystem Context data from a Vector Store based on a Request. It processes files stored in a specified
* directory and uses a Vector Store to perform similarity searches. If file processing is enabled, it processes files
* in the storage folder during initialization.
*
* @author Dmitry Marchuk
* @author Iryna Kopchak
* @see FilesystemService
* @see VectorStore
* @since 0.1.0
*/
@Slf4j
public class FilesystemRetriever implements Retriever<RagRequest, RagContext> {
/**
* The Vector Store used to retrieve Context data for User Request through similarity search.
*/
private final VectorStore vectorStore;
/**
* The path to the directory where files are stored.
*/
private final Path fileStoragePath;
/**
* The number of top results to retrieve from the Vector Store.
*/
private final Integer topK;
private final FilesystemService filesystemService = new FilesystemService();
/**
* Constructs a new {@link FilesystemRetriever} instance with the specified vectorStore, fileStoragePath, topK and
* isProcessingEnabled parameters.
*
* @param vectorStore the {@link VectorStore} instance used for storing and retrieving vector data.
* This parameter cannot be {@code null} and is used to interact with the Vector Store.
* @param fileStoragePath the path to the directory where files are stored. This parameter cannot be
* {@code null} and is used to process and store files to the Vector Store.
* @param topK the number of top results to retrieve from the Vector Store. This value must be a
* positive integer.
* @param isProcessingEnabled a {@link Boolean} flag indicating whether file processing should be enabled during
* initialization. If {@code true}, the method {@link #processFileStorageFolder()} will
* be called to process the files in the specified storage path.
* @throws IllegalArgumentException if {@code topK} is not a positive number.
*/
public FilesystemRetriever(
final @NonNull VectorStore vectorStore,
final @NonNull String fileStoragePath,
final @NonNull Integer topK,
final @NonNull Boolean isProcessingEnabled) {
if (topK <= 0) {
throw new IllegalArgumentException("TopK must be a positive number.");
}
this.vectorStore = vectorStore;
this.fileStoragePath = Paths.get(fileStoragePath);
this.topK = topK;
if (isProcessingEnabled) {
processFileStorageFolder();
}
}
/**
* Retrieves Context data based on the given Request by performing a similarity search in the Vector Store.
*
* @param request the {@link RagRequest} object containing the User query for the similarity search.
* @return a {@link RagContext} object containing the Knowledge obtained from the similarity search.
*/
@Override
public RagContext retrieve(final RagRequest request) {
return RagContext.builder()
.knowledge(
vectorStore
.similaritySearch(
SearchRequest.query(request.getQuery()).withTopK(topK))
.parallelStream()
.map(document -> {
log.debug("Document metadata: {}", document.getMetadata());
return document.getContent();
})
.toList())
.build();
}
/**
* Lists all regular files in the local directory, processes each file to create chunks, and then adds these chunks
* to the vector store.
*
* @throws RuntimeException if an I/O error occurs when processing file storage folder.
*/
private void processFileStorageFolder() {
try (var paths = Files.list(fileStoragePath)) {
var fileList = paths.filter(Files::isRegularFile).toList();
if (fileList.isEmpty()) {
log.debug("No files to process in directory: {}", fileStoragePath);
return;
}
var documents = filesystemService.createChunkDocumentsFromFiles(fileList);
vectorStore.add(documents);
moveFilesToProcessedFolder(fileList);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Moves all files from the local directory to the "processed" folder.
*
* @throws IOException if an I/O error occurs when accessing or moving the files.
*/
private void moveFilesToProcessedFolder(final List<Path> fileList) throws IOException {
var processedDir = fileStoragePath.resolveSibling("processed");
if (!Files.exists(processedDir)) {
Files.createDirectory(processedDir);
}
fileList.parallelStream().forEach(file -> {
try {
Files.move(file, processedDir.resolve(file.getFileName()), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
log.error("Failed to move file {} to processed directory: {}", file, e);
}
});
}
}
|
0 | java-sources/ai/yda-framework/filesystem-retriever/0.1.0/ai/yda/framework/rag/retriever/filesystem | java-sources/ai/yda-framework/filesystem-retriever/0.1.0/ai/yda/framework/rag/retriever/filesystem/exception/FileReadException.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.retriever.filesystem.exception;
/**
* Thrown to indicate that file read operation has failed.
*
* @author Dmitry Marchuk
* @since 0.1.0
*/
public class FileReadException extends RuntimeException {
/**
* Constructs a new {@link FileReadException}instance with the specified cause.
* This constructor initializes the exception with a predefined message "Failed to read file".
*
* @param cause the cause of the exception, which can be retrieved later using {@link Throwable#getCause()}.
*/
public FileReadException(final Throwable cause) {
super("Failed to read file", cause);
}
}
|
0 | java-sources/ai/yda-framework/filesystem-retriever/0.1.0/ai/yda/framework/rag/retriever/filesystem | java-sources/ai/yda-framework/filesystem-retriever/0.1.0/ai/yda/framework/rag/retriever/filesystem/service/FilesystemService.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.retriever.filesystem.service;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import ai.yda.framework.rag.core.util.ContentUtil;
import ai.yda.framework.rag.retriever.filesystem.util.FileUtil;
/**
* Provides methods to process files from the filesystem, specifically for creating chunked documents from files.
* This class handles the reading, preprocessing, and splitting of files into smaller chunks, which are then
* converted into {@link Document} objects. It is used to manage and transform file contents to facilitate further
* processing or retrieval.
*
* @author Iryna Kopchak
* @author Dmitry Marchuk
* @see FileUtil
* @see ContentUtil
* @since 0.1.0
*/
@Slf4j
public class FilesystemService {
/**
* The maximum length of a chunk in characters.
*/
private static final int CHUNK_MAX_LENGTH = 1000;
/**
* Default constructor for {@link FilesystemService}.
*/
public FilesystemService() {}
/**
* Processes a list of file paths, reads each file, preprocesses the content, splits it into chunks, and then
* converts each chunk into a {@link Document} object.
*
* @param filePathList a list of {@link Path} to the files to be processed.
* @return a list of {@link Document} objects created from the chunks of files.
*/
public List<Document> createChunkDocumentsFromFiles(final List<Path> filePathList) {
return filePathList.parallelStream()
.map(this::splitFileIntoChunkDocuments)
.flatMap(List::stream)
.toList();
}
/**
* Preprocesses and split of each file into chunks of a maximum length defined by {@link #CHUNK_MAX_LENGTH}. The
* method reads the content of a PDF file, preprocesses it to clean and format the text, and then splits the
* preprocessed content into smaller chunks based on the maximum length. Each chunk is converted into a
* {@link Document} object with associated metadata.
*
* @param filePath the {@link Path} of the file to be processed.
* @return a list of {@link Document} objects created from the chunks of the file.
*/
private List<Document> splitFileIntoChunkDocuments(final Path filePath) {
var pdfContent = FileUtil.readPdf(filePath.toFile());
var fileName = filePath.getFileName();
log.debug("Processing file: {}", fileName);
return ContentUtil.preprocessAndSplitContent(pdfContent, CHUNK_MAX_LENGTH).parallelStream()
.map(documentChunk -> new Document(documentChunk, Map.of("fileName", fileName)))
.toList();
}
}
|
0 | java-sources/ai/yda-framework/filesystem-retriever/0.1.0/ai/yda/framework/rag/retriever/filesystem | java-sources/ai/yda-framework/filesystem-retriever/0.1.0/ai/yda/framework/rag/retriever/filesystem/util/FileUtil.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.retriever.filesystem.util;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.text.PDFTextStripper;
import ai.yda.framework.rag.retriever.filesystem.exception.FileReadException;
/**
* Provides utility method for reading files and returning their content as a string.
*
* @author Dmitry Marchuk
* @see Loader
* @see PDFTextStripper
* @since 0.1.0
*/
public final class FileUtil {
/**
* Reads the content of a PDF file and returns it as a string.
*
* @param file the PDF {@link File} to be read.
* @return the text content of the PDF file as a string.
* @throws FileReadException if an error occurs while reading the file.
*/
public static String readPdf(final File file) {
try (var document = Loader.loadPDF(file)) {
return new PDFTextStripper().getText(document);
} catch (final IOException exception) {
throw new FileReadException(exception);
}
}
private FileUtil() {}
}
|
0 | java-sources/ai/yda-framework/filesystem-retriever-starter/0.1.0/ai/yda/framework/rag/retriever/filesystem | java-sources/ai/yda-framework/filesystem-retriever-starter/0.1.0/ai/yda/framework/rag/retriever/filesystem/autoconfigure/RetrieverFilesystemAutoConfiguration.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.retriever.filesystem.autoconfigure;
import org.springframework.ai.autoconfigure.openai.OpenAiConnectionProperties;
import org.springframework.ai.autoconfigure.openai.OpenAiEmbeddingProperties;
import org.springframework.ai.autoconfigure.vectorstore.milvus.MilvusServiceClientProperties;
import org.springframework.ai.autoconfigure.vectorstore.milvus.MilvusVectorStoreProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import ai.yda.framework.rag.retriever.filesystem.FilesystemRetriever;
import ai.yda.framework.rag.retriever.shared.MilvusVectorStoreUtil;
/**
* Autoconfiguration class for setting up the {@link FilesystemRetriever} bean with the necessary properties and
* dependencies. The configuration is based on properties defined in the external configuration files
* <p>
* The configuration is based on properties defined in the external configuration files (e.g., application.properties
* or application.yml) under {@link RetrieverFilesystemProperties#CONFIG_PREFIX},
* {@link MilvusVectorStoreProperties#CONFIG_PREFIX} and {@link OpenAiConnectionProperties#CONFIG_PREFIX} namespaces.
* </p>
*
* @author Iryna Kopchak
* @author Dmitry Marchuk
* @see FilesystemRetriever
* @see RetrieverFilesystemProperties
* @see MilvusVectorStoreProperties
* @see MilvusServiceClientProperties
* @see OpenAiConnectionProperties
* @see OpenAiEmbeddingProperties
* @since 1.0.0
*/
@AutoConfiguration
@EnableConfigurationProperties(RetrieverFilesystemProperties.class)
public class RetrieverFilesystemAutoConfiguration {
/**
* Default constructor for {@link RetrieverFilesystemAutoConfiguration}.
*/
public RetrieverFilesystemAutoConfiguration() {}
/**
* Creates and configures an instance of {@link FilesystemRetriever} using the provided properties and services.
*
* <p>This method performs the following steps:</p>
* <ul>
* <li>Creates a {@code MilvusVectorStore} instance using the provided properties and services.</li>
* <li>Initializes the {@code MilvusVectorStore} instance by calling {@code afterPropertiesSet()}.</li>
* <li>Creates and returns a {@link FilesystemRetriever} instance with the initialized parameters</li>
* </ul>
*
* @param filesystemProperties properties for configuring the {@link FilesystemRetriever}, including
* collectionName, topK, isProcessingEnabled, clearCollectionOnStartup and
* fileStoragePath settings.
* @param milvusProperties properties for configuring the Milvus Vector Store.
* @param milvusClientProperties properties for configuring the Milvus Service Client.
* @param openAiConnectionProperties properties for configuring the OpenAI connection.
* @param openAiEmbeddingProperties properties for configuring the OpenAI Embeddings.
* @return a fully configured {@link FilesystemRetriever} instance.
* @throws Exception if an error occurs during initialization.
*/
@Bean
public FilesystemRetriever filesystemRetriever(
final RetrieverFilesystemProperties filesystemProperties,
final MilvusVectorStoreProperties milvusProperties,
final MilvusServiceClientProperties milvusClientProperties,
final OpenAiConnectionProperties openAiConnectionProperties,
final OpenAiEmbeddingProperties openAiEmbeddingProperties)
throws Exception {
var milvusVectorStore = MilvusVectorStoreUtil.createMilvusVectorStore(
filesystemProperties,
milvusProperties,
milvusClientProperties,
openAiConnectionProperties,
openAiEmbeddingProperties);
milvusVectorStore.afterPropertiesSet();
return new FilesystemRetriever(
milvusVectorStore,
filesystemProperties.getFileStoragePath(),
filesystemProperties.getTopK(),
filesystemProperties.getIsProcessingEnabled());
}
}
|
0 | java-sources/ai/yda-framework/filesystem-retriever-starter/0.1.0/ai/yda/framework/rag/retriever/filesystem | java-sources/ai/yda-framework/filesystem-retriever-starter/0.1.0/ai/yda/framework/rag/retriever/filesystem/autoconfigure/RetrieverFilesystemProperties.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.retriever.filesystem.autoconfigure;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import ai.yda.framework.rag.retriever.shared.RetrieverProperties;
/**
* Provides configuration properties for filesystem Retriever. These properties can be customized through the
* application’s external configuration, such as a properties file, YAML file, or environment variables. The
* properties include collectionName, topK, isProcessingEnabled, clearCollectionOnStartup and fileStoragePath settings.
* <p>
* The properties are prefixed with {@link #CONFIG_PREFIX} and can be customized by defining values under this prefix
* in the external configuration.
* <pre>
* Example configuration in a YAML file:
* ai:
* yda:
* framework:
* rag:
* retriever:
* filesystem:
* collectionName: your-collection-name
* topK: your-top-k
* isProcessingEnabled: true/false
* clearCollectionOnStartup: true/false
* fileStoragePath: your-file-storage-path
* </pre>
*
* @author Dmitry Marchuk
* @author Iryna Kopchak
* @since 0.1.0
*/
@Setter
@Getter
@ConfigurationProperties(RetrieverFilesystemProperties.CONFIG_PREFIX)
public class RetrieverFilesystemProperties extends RetrieverProperties {
/**
* The configuration prefix used to reference properties related to the filesystem Retriever in application
* configurations. This prefix is used for binding properties within the particular namespace.
*/
public static final String CONFIG_PREFIX = "ai.yda.framework.rag.retriever.filesystem";
private String fileStoragePath;
/**
* Default constructor for {@link RetrieverFilesystemProperties}.
*/
public RetrieverFilesystemProperties() {}
}
|
0 | java-sources/ai/yda-framework/framework-core/0.1.0/ai/yda/framework/core | java-sources/ai/yda-framework/framework-core/0.1.0/ai/yda/framework/core/assistant/Assistant.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.core.assistant;
/**
* Represents an Assistant that processes User Requests and provides appropriate Responses.
*
* @param <REQUEST> the generic type of the Request from the User.
* @param <RESPONSE> the generic type of the Response that will be generated based on the given Request.
* @author Nikita Litvinov
* @see StreamingAssistant
* @see RagAssistant
* @since 0.1.0
*/
public interface Assistant<REQUEST, RESPONSE> {
/**
* Processes the given Request and returns a corresponding Response.
*
* @param request the Request to be processed.
* @return the Response generated from processing the Request.
*/
RESPONSE assist(REQUEST request);
}
|
0 | java-sources/ai/yda-framework/framework-core/0.1.0/ai/yda/framework/core | java-sources/ai/yda-framework/framework-core/0.1.0/ai/yda/framework/core/assistant/RagAssistant.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.core.assistant;
import ai.yda.framework.rag.core.Rag;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
/**
* Represents a RAG Assistant that processes a Request and returns a Response. This class delegates the Request
* processing to the {@link Rag} instance provided via constructor injection.
*
* @author Nikita Litvinov
* @see Rag
* @see StreamingRagAssistant
* @since 0.1.0
*/
public class RagAssistant implements Assistant<RagRequest, RagResponse> {
/**
* The {@link Rag} instance responsible for processing the {@link RagRequest} and generating the
* {@link RagResponse}.
*/
private final Rag<RagRequest, RagResponse> rag;
/**
* Constructs a new {@link RagAssistant} instance with the specified {@link Rag} instance.
*
* @param rag the {@link Rag} instance used to handle {@link RagRequest} and {@link RagResponse} processing.
*/
public RagAssistant(final Rag<RagRequest, RagResponse> rag) {
this.rag = rag;
}
/**
* Processes the given {@link RagRequest} by delegating to the {@link Rag#doRag(RagRequest)} method and returns the
* resulting {@link RagResponse}.
*
* @param request the {@link RagRequest} to be processed.
* @return the {@link RagResponse} generated from processing the request.
*/
@Override
public RagResponse assist(final RagRequest request) {
return rag.doRag(request);
}
}
|
0 | java-sources/ai/yda-framework/framework-core/0.1.0/ai/yda/framework/core | java-sources/ai/yda-framework/framework-core/0.1.0/ai/yda/framework/core/assistant/StreamingAssistant.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.core.assistant;
import reactor.core.publisher.Flux;
/**
* Represents an Assistant that processes a Request and returns a Response in a streaming manner.
* <p>
* This class is useful when Responses need to be generated progressively, such as when dealing with large amounts of
* data or when the Response is expected to be produced in chunks.
* </p>
*
* @param <REQUEST> the generic type of the Request from the User.
* @param <RESPONSE> the generic type of the Response that will be generated based on the given Request.
* @author Nikita Litvinov
* @see Assistant
* @see StreamingRagAssistant
* @since 0.1.0
*/
public interface StreamingAssistant<REQUEST, RESPONSE> {
/**
* Processes the given Request and returns a corresponding Response in a streaming manner.
*
* @param request the Request to be processed.
* @return a {@link Flux stream} of Response objects generated from processing the Request.
*/
Flux<RESPONSE> streamAssistance(REQUEST request);
}
|
0 | java-sources/ai/yda-framework/framework-core/0.1.0/ai/yda/framework/core | java-sources/ai/yda-framework/framework-core/0.1.0/ai/yda/framework/core/assistant/StreamingRagAssistant.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.core.assistant;
import reactor.core.publisher.Flux;
import ai.yda.framework.rag.core.StreamingRag;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
/**
* Represents a streaming RAG Assistant that processes a Request and returns a Response in a streaming manner. This
* class delegates the Request processing to the {@link StreamingRag} instance provided via constructor injection.
* <p>
* This class is useful when Responses need to be generated progressively, such as when dealing with large amounts of
* data or when the Response is expected to be produced in chunks.
* </p>
*
* @author Nikita Litvinov
* @see StreamingRag
* @see RagAssistant
* @since 0.1.0
*/
public class StreamingRagAssistant implements StreamingAssistant<RagRequest, RagResponse> {
/**
* The {@link StreamingRag} instance responsible for processing the {@link RagRequest} and generating the
* {@link RagResponse} in streaming manner.
*/
private final StreamingRag<RagRequest, RagResponse> rag;
/**
* Constructs a new {@link StreamingRagAssistant} instance with the specified {@link StreamingRag} instance.
*
* @param rag the {@link StreamingRag} instance used to handle {@link RagRequest} and {@link RagResponse}
* processing. This parameter cannot be {@code null}.
*/
public StreamingRagAssistant(final StreamingRag<RagRequest, RagResponse> rag) {
this.rag = rag;
}
@Override
public Flux<RagResponse> streamAssistance(final RagRequest request) {
return rag.streamRag(request);
}
}
|
0 | java-sources/ai/yda-framework/generator-shared/0.1.0/ai/yda/framework/rag/generator | java-sources/ai/yda-framework/generator-shared/0.1.0/ai/yda/framework/rag/generator/shared/AzureOpenAiAssistantService.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.generator.shared;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import com.azure.ai.openai.assistants.AssistantsClient;
import com.azure.ai.openai.assistants.AssistantsClientBuilder;
import com.azure.ai.openai.assistants.models.AssistantThread;
import com.azure.ai.openai.assistants.models.AssistantThreadCreationOptions;
import com.azure.ai.openai.assistants.models.CreateRunOptions;
import com.azure.ai.openai.assistants.models.MessageDeltaChunk;
import com.azure.ai.openai.assistants.models.MessageDeltaTextContentObject;
import com.azure.ai.openai.assistants.models.MessageRole;
import com.azure.ai.openai.assistants.models.MessageTextContent;
import com.azure.ai.openai.assistants.models.RunStatus;
import com.azure.ai.openai.assistants.models.StreamMessageUpdate;
import com.azure.ai.openai.assistants.models.ThreadMessageOptions;
import com.azure.ai.openai.assistants.models.ThreadRun;
import com.azure.core.credential.KeyCredential;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
/**
* Provides methods to interact with the Azure OpenAI Assistant API. It facilitates creating and managing conversation
* Threads, sending messages, and retrieving Responses from the Assistant service.
* <p>
* This service uses an {@link AssistantsClient} to perform operations such as creating Threads, adding messages,
* and running Assistant tasks. It also supports streaming Responses for real-time updates.
* </p>
*
* @author Nikita Litvinov
* @author Iryna Kopchak
* @see AssistantsClient
* @see AssistantThread
* @since 0.1.0
*/
public class AzureOpenAiAssistantService {
private final AssistantsClient assistantsClient;
/**
* Constructs a new {@link AzureOpenAiAssistantService} instance with the specified API key.
* Initializes the {@link AssistantsClient} with the provided API key for authentication.
*
* @param apiKey the API key for authenticating to the OpenAI Assistant API.
*/
public AzureOpenAiAssistantService(final String apiKey) {
this.assistantsClient = new AssistantsClientBuilder()
.credential(new KeyCredential(apiKey))
.buildClient();
}
/**
* Creates a new Thread in the Azure OpenAI Assistant Service with an initial message.
*
* @param content the content of the initial message to include in the Thread.
* @return the {@link AssistantThread} representing the created Thread.
*/
public AssistantThread createThread(final String content) {
var threadMessageOptions = new ThreadMessageOptions(MessageRole.USER, content);
var creationOptions = new AssistantThreadCreationOptions().setMessages(List.of(threadMessageOptions));
return assistantsClient.createThread(creationOptions);
}
/**
* Adds a message to an existing Thread in the Azure OpenAI Assistant Service.
*
* @param threadId the ID of the Thread to which the message should be added.
* @param content the content of the message to add.
*/
public void addMessageToThread(final String threadId, final String content) {
var threadMessageOptions = new ThreadMessageOptions(MessageRole.USER, content);
assistantsClient.createMessage(threadId, threadMessageOptions);
}
/**
* Creates a run for a given Thread and waits for the Response.
*
* @param threadId the ID of the Thread in which to create the run.
* @param assistantId the ID of the Assistant to use for the run.
* @param context additional instructions to include in the run.
* @return the content of the last message in the Thread after the run completes.
*/
public String createRunAndWaitForResponse(final String threadId, final String assistantId, final String context) {
var createRunOptions = new CreateRunOptions(assistantId).setAdditionalInstructions(context);
var threadRun = assistantsClient.createRun(threadId, createRunOptions);
threadRun = waitForRunToFinish(threadRun);
return getLastMessage(threadRun.getThreadId());
}
/**
* Streams responses from the Azure OpenAI Assistant Service for a given run.
*
* @param threadId the ID of the Thread for which to stream Responses.
* @param assistantId the ID of the Assistant to use for the run.
* @param context additional instructions to include in the run.
* @return a {@link Flux stream} of Response content updates as they are received.
*/
public Flux<String> createRunStream(final String threadId, final String assistantId, final String context) {
var createRunOptions = new CreateRunOptions(assistantId).setAdditionalInstructions(context);
return Flux.fromIterable(assistantsClient.createRunStream(threadId, createRunOptions))
.subscribeOn(Schedulers.boundedElastic())
.filter(streamUpdate -> streamUpdate instanceof StreamMessageUpdate)
.map(deltaMessage -> extractDeltaContent(((StreamMessageUpdate) deltaMessage).getMessage()));
}
/**
* Waits for the completion of a given Thread run. It periodically polls the status of the Thread run until it is
* no longer in the QUEUED or IN_PROGRESS states. The Thread run is updated with the final
* {@code progressThreadRun} once the polling completes.
*
* @param threadRun the initial {@link ThreadRun} object representing the run to be monitored.
* @return the updated {@link ThreadRun} object once the run has completed.
* @throws RuntimeException if an error occurs while waiting for the Thread run to finish.
*/
private ThreadRun waitForRunToFinish(final ThreadRun threadRun) {
var atomicThreadRun = new AtomicReference<>(threadRun);
try {
var executor = Executors.newSingleThreadScheduledExecutor();
var schedule = executor.scheduleAtFixedRate(
() -> {
var progressThreadRun = assistantsClient.getRun(threadRun.getThreadId(), threadRun.getId());
var progressStatus = progressThreadRun.getStatus();
if (progressStatus != RunStatus.QUEUED && progressStatus != RunStatus.IN_PROGRESS) {
atomicThreadRun.set(progressThreadRun);
executor.shutdown();
}
},
1,
1,
TimeUnit.SECONDS);
schedule.get();
executor.shutdown();
} catch (ExecutionException | InterruptedException exception) {
throw new RuntimeException(
String.format(
"Error while waiting for thread run: threadId - %s, runId - %s",
threadRun.getThreadId(), threadRun.getId()),
exception);
} catch (CancellationException ignored) {
}
return atomicThreadRun.get();
}
/**
* Queries all messages in the specified Thread and returns the content of the most recent message.
*
* @param threadId the ID of the Thread from which to retrieve the last message.
* @return the content of the last message in the Thread.
*/
private String getLastMessage(final String threadId) {
var messages = assistantsClient.listMessages(threadId);
return messages.getData().get(0).getContent().stream()
.map(content -> ((MessageTextContent) content).getText().getValue())
.collect(Collectors.joining(". "));
}
/**
* Processes a {@link MessageDeltaChunk} to extract the text content updates and concatenates them into a single
* string.
*
* @param delta the {@link MessageDeltaChunk} containing delta content updates.
* @return the concatenated delta content as a string.
*/
private String extractDeltaContent(final MessageDeltaChunk delta) {
return delta.getDelta().getContent().parallelStream()
.map(content ->
((MessageDeltaTextContentObject) content).getText().getValue())
.collect(Collectors.joining(". "));
}
}
|
0 | java-sources/ai/yda-framework/openai-assistant-generator/0.1.0/ai/yda/framework/rag/generator/assistant | java-sources/ai/yda-framework/openai-assistant-generator/0.1.0/ai/yda/framework/rag/generator/assistant/openai/OpenAiAssistantGenerator.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.generator.assistant.openai;
import lombok.extern.slf4j.Slf4j;
import ai.yda.framework.rag.core.generator.Generator;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
import ai.yda.framework.rag.generator.shared.AzureOpenAiAssistantService;
import ai.yda.framework.session.core.SessionProvider;
/**
* Generates responses to the User Request by sending queries to the Assistant Service. The class relies on the
* {@link AzureOpenAiAssistantService} for communicating with the Assistant, and uses a {@code assistantId} field to
* identify the Assistant being used.
*
* @author Iryna Kopchak
* @author Nikita Litvinov
* @see AzureOpenAiAssistantService
* @since 0.1.0
*/
@Slf4j
public class OpenAiAssistantGenerator implements Generator<RagRequest, RagResponse> {
/**
* The constant representing the thead id key.
*/
private static final String THREAD_ID_KEY = "threadId";
private final AzureOpenAiAssistantService assistantService;
/**
* The ID of the Assistant to be used.
*/
private final String assistantId;
/**
* The provider responsible for managing Session data.
*/
private final SessionProvider sessionProvider;
/**
* Constructs a new {@link OpenAiAssistantGenerator} instance with the specified apiKey, assistantId,
* sessionProvider.
*
* @param apiKey the API key used to authenticate with the Azure OpenAI Service.
* @param assistantId the unique identifier for the Assistant that will be used to interact with the Azure
* OpenAI Service. This ID is required to specify which Assistant to use when making
* requests.
* @param sessionProvider the {@link SessionProvider} instance responsible for providing and managing Sessions. It
* is used to manage User Sessions and maintain context between interactions with the
* Assistant.
*/
public OpenAiAssistantGenerator(
final String apiKey, final String assistantId, final SessionProvider sessionProvider) {
this.assistantService = new AzureOpenAiAssistantService(apiKey);
this.assistantId = assistantId;
this.sessionProvider = sessionProvider;
}
/**
* Generates a Response for a given Request using the OpenAI Assistant Service. This involves either retrieving an
* existing Thread ID from the Session Provider or creating a new Thread, sending the Request query to the
* Assistant, and obtaining the Response.
*
* @param request the {@link RagRequest} object containing the query from the User.
* @param context the Context to be included in the Request to the Assistant.
* @return a {@link RagResponse} containing the result of the Assistant's Response.
*/
@Override
public RagResponse generate(final RagRequest request, final String context) {
var requestQuery = request.getQuery();
var threadId = sessionProvider
.get(THREAD_ID_KEY)
.map(Object::toString)
.map(id -> {
assistantService.addMessageToThread(id, requestQuery);
return id;
})
.orElseGet(() -> {
var newThreadId =
assistantService.createThread(requestQuery).getId();
sessionProvider.put(THREAD_ID_KEY, newThreadId);
return newThreadId;
});
log.debug("Thread ID: {}", threadId);
return RagResponse.builder()
.result(assistantService.createRunAndWaitForResponse(threadId, assistantId, context))
.build();
}
}
|
0 | java-sources/ai/yda-framework/openai-assistant-generator-starter/0.1.0/ai/yda/framework/rag/generator/assistant/openai | java-sources/ai/yda-framework/openai-assistant-generator-starter/0.1.0/ai/yda/framework/rag/generator/assistant/openai/autoconfigure/OpenAiAssistantGeneratorAutoConfiguration.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.generator.assistant.openai.autoconfigure;
import org.springframework.ai.autoconfigure.openai.OpenAiConnectionProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import ai.yda.framework.rag.generator.assistant.openai.OpenAiAssistantGenerator;
import ai.yda.framework.session.core.SessionProvider;
/**
* Autoconfiguration class for setting up an {@link OpenAiAssistantGenerator} bean. This class automatically configures
* the necessary components for integrating with the OpenAI API to create an assistant generator. The configuration is
* based on properties defined in the external configuration files (e.g., application.properties or application.yml)
* under {@link OpenAiConnectionProperties#CONFIG_PREFIX} and {@link OpenAiAssistantGeneratorProperties#CONFIG_PREFIX}
* namespaces.
*
* @author Iryna Kopchak
* @author Dmitry Marchuk
* @see OpenAiAssistantGenerator
* @see OpenAiAssistantGeneratorProperties
* @see OpenAiConnectionProperties
* @see SessionProvider
* @since 0.1.0
*/
@AutoConfiguration
@EnableConfigurationProperties({OpenAiAssistantGeneratorProperties.class, OpenAiConnectionProperties.class})
public class OpenAiAssistantGeneratorAutoConfiguration {
/**
* Default constructor for {@link OpenAiAssistantGeneratorAutoConfiguration}.
*/
public OpenAiAssistantGeneratorAutoConfiguration() {}
/**
* Defines an {@link OpenAiAssistantGenerator} bean. This bean is configured using the provided properties for the
* Assistant Generator and the OpenAI connection. The Generator requires an API key and an Assistant ID, which are
* retrieved from the external configuration, and a {@link SessionProvider} for managing user Sessions.
*
* @param assistantGeneratorProperties the properties related to the Assistant Generator, providing Assistant ID
* configuration.
* @param openAiProperties the properties related to the OpenAI connection, including the API key.
* @param sessionProvider the Session Provider responsible for managing User Sessions.
* @return a configured {@link OpenAiAssistantGenerator} bean ready for use in the application.
*/
@Bean
public OpenAiAssistantGenerator openAiGenerator(
final OpenAiAssistantGeneratorProperties assistantGeneratorProperties,
final OpenAiConnectionProperties openAiProperties,
final SessionProvider sessionProvider) {
return new OpenAiAssistantGenerator(
openAiProperties.getApiKey(), assistantGeneratorProperties.getAssistantId(), sessionProvider);
}
}
|
0 | java-sources/ai/yda-framework/openai-assistant-generator-starter/0.1.0/ai/yda/framework/rag/generator/assistant/openai | java-sources/ai/yda-framework/openai-assistant-generator-starter/0.1.0/ai/yda/framework/rag/generator/assistant/openai/autoconfigure/OpenAiAssistantGeneratorProperties.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.generator.assistant.openai.autoconfigure;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Provides configuration properties for OpenAi Assistant Generator. These properties can be customized through the
* application’s external configuration, such as a properties file, YAML file, or environment variables. The properties
* include Assistant id settings.
* <p>
* The properties are prefixed with {@link #CONFIG_PREFIX} and can be customized by defining values under this prefix
* in the external configuration.
* <pre>
* Example configuration in a YAML file:
*
* ai:
* yda:
* framework:
* rag:
* generator:
* assistant:
* openai:
* assistantId: your-assistant-id
* </pre>
*
* @author Iryna Kopchak
* @author Dmitry Marchuk
* @since 0.1.0
*/
@Setter
@Getter
@ConfigurationProperties(OpenAiAssistantGeneratorProperties.CONFIG_PREFIX)
public class OpenAiAssistantGeneratorProperties {
/**
* The configuration prefix used to reference properties related to the Assistant Generator in application
* configurations. This prefix is used for binding properties within the particular namespace.
*/
public static final String CONFIG_PREFIX = "ai.yda.framework.rag.generator.assistant.openai";
private String assistantId;
/**
* Default constructor for {@link OpenAiAssistantGeneratorProperties}.
*/
public OpenAiAssistantGeneratorProperties() {}
}
|
0 | java-sources/ai/yda-framework/openai-assistant-streaming-generator/0.1.0/ai/yda/framework/rag/generator/assistant/openai | java-sources/ai/yda-framework/openai-assistant-streaming-generator/0.1.0/ai/yda/framework/rag/generator/assistant/openai/streaming/OpenAiAssistantStreamingGenerator.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.generator.assistant.openai.streaming;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import ai.yda.framework.rag.core.generator.StreamingGenerator;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
import ai.yda.framework.rag.generator.shared.AzureOpenAiAssistantService;
import ai.yda.framework.session.core.ReactiveSessionProvider;
/**
* Generates Responses to user queries in a streaming manner by sending queries to the Assistant Service. The class
* relies on the {@link AzureOpenAiAssistantService} for communicating with the Assistant, and uses a
* {@code assistantId} field to identify the Assistant being used.
*
* @author Nikita Litvinov
* @see AzureOpenAiAssistantService
* @since 0.1.0
*/
@Slf4j
public class OpenAiAssistantStreamingGenerator implements StreamingGenerator<RagRequest, RagResponse> {
/**
* The constant representing the thead id key.
*/
private static final String THREAD_ID_KEY = "threadId";
private final AzureOpenAiAssistantService assistantService;
/**
* The ID of the Assistant to be used.
*/
private final String assistantId;
/**
* The reactive provider responsible for managing Session data.
*/
private final ReactiveSessionProvider sessionProvider;
/**
* Constructs a new {@link OpenAiAssistantStreamingGenerator} instance with the specified apiKey, assistantId,
* sessionProvider.
*
* @param apiKey the API key used to authenticate with the Azure OpenAI Service.
* @param assistantId the unique identifier for the Assistant that will be used to interact with the Azure
* OpenAI Service. This ID is required to specify which Assistant to use when making
* Requests.
* @param sessionProvider the {@link ReactiveSessionProvider} instance responsible for providing and managing
* Sessions. It is used to manage User Sessions and maintain Context between interactions
* with the Assistant.
*/
public OpenAiAssistantStreamingGenerator(
final String apiKey, final String assistantId, final ReactiveSessionProvider sessionProvider) {
this.assistantService = new AzureOpenAiAssistantService(apiKey);
this.assistantId = assistantId;
this.sessionProvider = sessionProvider;
}
/**
* Generates a Response for a given Request using the OpenAI Assistant Service in a streaming manner. This involves
* either retrieving an existing Thread ID from the Session Provider or creating a new Thread, sending the Request
* query to the Assistant, and obtaining the Response.
*
* @param request the {@link RagRequest} object containing the query from the User.
* @param context the Context to be included in the Request to the Assistant.
* @return a {@link Flux stream} of {@link RagResponse} objects containing the result of the Assistant's Response.
*/
@Override
public Flux<RagResponse> streamGeneration(final RagRequest request, final String context) {
return sessionProvider
.get(THREAD_ID_KEY)
.map(Object::toString)
.flatMap(threadId -> Mono.fromRunnable(
() -> assistantService.addMessageToThread(threadId, request.getQuery()))
.subscribeOn(Schedulers.boundedElastic())
.thenReturn(threadId))
.switchIfEmpty(Mono.defer(() -> Mono.fromCallable(() -> assistantService
.createThread(request.getQuery())
.getId())
.subscribeOn(Schedulers.boundedElastic())
.flatMap(threadId ->
sessionProvider.put(THREAD_ID_KEY, threadId).thenReturn(threadId))))
.doOnNext(threadId -> log.debug("Thread ID: {}", threadId))
.flatMapMany(threadId -> assistantService.createRunStream(threadId, assistantId, context))
.map(deltaMessage -> RagResponse.builder().result(deltaMessage).build());
}
}
|
0 | java-sources/ai/yda-framework/openai-assistant-streaming-generator-starter/0.1.0/ai/yda/framework/rag/generator/assistant/openai/streaming | java-sources/ai/yda-framework/openai-assistant-streaming-generator-starter/0.1.0/ai/yda/framework/rag/generator/assistant/openai/streaming/autoconfigure/OpenAiAssistantStreamingGeneratorAutoConfiguration.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.generator.assistant.openai.streaming.autoconfigure;
import org.springframework.ai.autoconfigure.openai.OpenAiConnectionProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestClient;
import ai.yda.framework.rag.generator.assistant.openai.streaming.OpenAiAssistantStreamingGenerator;
import ai.yda.framework.session.core.ReactiveSessionProvider;
/**
* Autoconfiguration class for setting up an {@link OpenAiAssistantStreamingGenerator} bean. This class automatically
* configures the necessary components for integrating with the OpenAI API to create a streaming Assistant Generator.
* The configuration is based on properties defined in the external configuration files (e.g., application.properties or
* application.yml) under {@link OpenAiConnectionProperties#CONFIG_PREFIX} and
* {@link OpenAiAssistantStreamingGeneratorProperties#CONFIG_PREFIX} namespaces.
*
* @author Nikita Litvinov
* @see OpenAiAssistantStreamingGenerator
* @see OpenAiAssistantStreamingGeneratorProperties
* @see OpenAiConnectionProperties
* @see ReactiveSessionProvider
* @since 0.1.0
*/
@AutoConfiguration
@EnableConfigurationProperties({OpenAiAssistantStreamingGeneratorProperties.class, OpenAiConnectionProperties.class})
public class OpenAiAssistantStreamingGeneratorAutoConfiguration {
/**
* Default constructor for {@link OpenAiAssistantStreamingGeneratorAutoConfiguration}.
*/
public OpenAiAssistantStreamingGeneratorAutoConfiguration() {}
/**
* Defines an {@link OpenAiAssistantStreamingGenerator} bean. This bean is configured using the provided properties
* for the streaming Assistant Generator and the OpenAI connection. The generator requires an API key and an
* Assistant ID, which are retrieved from the external configuration, and a {@link ReactiveSessionProvider} for
* managing User Sessions.
*
* @param assistantGeneratorProperties the properties related to the Assistant Generator, providing Assistant ID
* configuration.
* @param openAiProperties the properties related to the OpenAI connection, including the API key.
* @param sessionProvider the Session Provider responsible for managing User Sessions.
* @return a configured {@link OpenAiAssistantStreamingGenerator} bean ready for use in the application.
*/
@Bean
public OpenAiAssistantStreamingGenerator openAiGenerator(
final OpenAiAssistantStreamingGeneratorProperties assistantGeneratorProperties,
final OpenAiConnectionProperties openAiProperties,
final ReactiveSessionProvider sessionProvider) {
return new OpenAiAssistantStreamingGenerator(
openAiProperties.getApiKey(), assistantGeneratorProperties.getAssistantId(), sessionProvider);
}
/**
* Defines a {@link RestClient.Builder} bean if none is provided.
*
* @return Rest Client builder
*/
@Bean
@ConditionalOnMissingBean
public RestClient.Builder restClientBuilder() {
return RestClient.builder();
}
}
|
0 | java-sources/ai/yda-framework/openai-assistant-streaming-generator-starter/0.1.0/ai/yda/framework/rag/generator/assistant/openai/streaming | java-sources/ai/yda-framework/openai-assistant-streaming-generator-starter/0.1.0/ai/yda/framework/rag/generator/assistant/openai/streaming/autoconfigure/OpenAiAssistantStreamingGeneratorProperties.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.generator.assistant.openai.streaming.autoconfigure;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Provides configuration properties for streaming OpenAi Assistant Generator. These properties can be customized
* through the application’s external configuration, such as a properties file, YAML file, or environment variables. The
* properties include assistantId settings.
* <p>
* The properties are prefixed with {@link #CONFIG_PREFIX} and can be customized by defining values under this prefix
* in the external configuration.
* <pre>
* Example configuration in a YAML file:
*
* ai:
* yda:
* framework:
* rag:
* generator:
* assistant:
* openai:
* streaming:
* assistantId: your-assistant-id
* </pre>
*
* @author Nikita Litvinov
* @since 0.1.0
*/
@Setter
@Getter
@ConfigurationProperties(OpenAiAssistantStreamingGeneratorProperties.CONFIG_PREFIX)
public class OpenAiAssistantStreamingGeneratorProperties {
/**
* The configuration prefix used to reference properties related to the streaming Assistant Generator in
* application configurations. This prefix is used for binding properties within the particular namespace.
*/
public static final String CONFIG_PREFIX = "ai.yda.framework.rag.generator.assistant.openai.streaming";
private String assistantId;
/**
* Default constructor for {@link OpenAiAssistantStreamingGeneratorProperties}.
*/
public OpenAiAssistantStreamingGeneratorProperties() {}
}
|
0 | java-sources/ai/yda-framework/openai-chat-generator/0.1.0/ai/yda/framework/rag/generator/chat | java-sources/ai/yda-framework/openai-chat-generator/0.1.0/ai/yda/framework/rag/generator/chat/openai/OpenAiChatGenerator.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.generator.chat.openai;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import ai.yda.framework.rag.core.generator.Generator;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
/**
* Generates Responses using an OpenAI Chat Model. This class is designed to interact with a Chat Model to process User
* Requests and generate Responses based on the provided Context.
* <p>
* The class relies on the {@link OpenAiChatModel} for interacting with the Chat service, which processes the User's
* Requests and generates a Responses.
* </p>
*
* @author Iryna Kopchak
* @author Nikita Litvinov
* @see OpenAiChatModel
* @since 0.1.0
*/
public class OpenAiChatGenerator implements Generator<RagRequest, RagResponse> {
private final OpenAiChatModel chatModel;
/**
* Constructs a new {@link OpenAiChatGenerator} instance with the specified Chat Model.
*
* @param chatModel the {@link OpenAiChatModel} instance that defines the configuration and behavior of the Chat
* Model. This Model is used by the {@link OpenAiChatGenerator} to generate and manage Chat
* interactions.
*/
public OpenAiChatGenerator(final OpenAiChatModel chatModel) {
this.chatModel = chatModel;
}
/**
* Generates a Response for a given Request using the OpenAI Chat Model.
*
* @param request the {@link RagRequest} object containing the query from the User.
* @param context the Context to be included in the Request to the Chat Model.
* @return a {@link RagResponse} containing the Content of the Chat Model's Response.
*/
@Override
public RagResponse generate(final RagRequest request, final String context) {
var prompt = new Prompt(new UserMessage(request.getQuery()));
var response = chatModel.call(prompt).getResult().getOutput();
return RagResponse.builder().result(response.getContent()).build();
}
}
|
0 | java-sources/ai/yda-framework/openai-chat-generator-starter/0.1.0/ai/yda/framework/rag/generator/chat/openai | java-sources/ai/yda-framework/openai-chat-generator-starter/0.1.0/ai/yda/framework/rag/generator/chat/openai/autoconfigure/OpenAiChatGeneratorAutoConfiguration.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.generator.chat.openai.autoconfigure;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import ai.yda.framework.rag.core.generator.Generator;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
import ai.yda.framework.rag.generator.chat.openai.OpenAiChatGenerator;
/**
* Autoconfiguration class for setting up a {@link Generator} bean that uses the OpenAI Chat model. This class
* automatically configures a {@link Generator} for generating responses using OpenAI's Chat model. The configuration
* relies on an {@link OpenAiChatModel} instance, which contains the necessary configurations and parameters to interact
* with the OpenAI API.
*
* @author Dmitry Marchuk
* @author Iryna Kopchak
* @see Generator
* @see OpenAiChatModel
* @since 0.1.0
*/
@AutoConfiguration
public class OpenAiChatGeneratorAutoConfiguration {
/**
* Default constructor for {@link OpenAiChatGeneratorAutoConfiguration}.
*/
public OpenAiChatGeneratorAutoConfiguration() {}
/**
* Defines a {@link Generator} bean that utilizes an {@link OpenAiChatModel} to generate Responses. This method
* creates and returns an instance of {@link OpenAiChatGenerator}, which is a concrete implementation of
* {@link Generator}. It uses the provided {@link OpenAiChatModel} to interact with OpenAI's Chat model and generate
* Responses based on the input Requests.
*
* @param chatModel the {@link OpenAiChatModel} instance that provides configurations and parameters for interacting
* with the OpenAI API.
* @return a {@link Generator} instance that generates Responses using the OpenAI Chat model.
*/
@Bean
public Generator<RagRequest, RagResponse> openAiGenerator(final OpenAiChatModel chatModel) {
return new OpenAiChatGenerator(chatModel);
}
}
|
0 | java-sources/ai/yda-framework/rag-assistant-starter/0.1.0/ai/yda/framework/assistant/rag | java-sources/ai/yda-framework/rag-assistant-starter/0.1.0/ai/yda/framework/assistant/rag/autoconfigure/RagAssistantAutoConfiguration.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.assistant.rag.autoconfigure;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import ai.yda.framework.core.assistant.RagAssistant;
import ai.yda.framework.rag.core.Rag;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
/**
* Autoconfiguration class for setting up the {@link RagAssistant} bean. This class is responsible for automatically
* configuring a {@link RagAssistant} instance within the Spring application context. The {@link RagAssistant} bean is
* created using a provided {@link Rag} instance, which is injected as a dependency. The configuration is applied
* automatically when the application starts, thanks to the {@link AutoConfiguration} annotation.
* <p>
* This setup allows the {@link RagAssistant} to be readily available for use in the application wherever it's needed,
* without requiring manual bean configuration.
* </p>
*
* @author Nikita Litvinov
* @see RagAssistant
* @see Rag
* @since 0.1.0
*/
@AutoConfiguration
public class RagAssistantAutoConfiguration {
/**
* Default constructor for {@link RagAssistantAutoConfiguration}.
*/
public RagAssistantAutoConfiguration() {}
/**
* Creates and configures a {@link RagAssistant} bean in the Spring application context.
*
* @param rag the {@link Rag} instance used by the {@link RagAssistant} to perform its operations.
* This parameter is expected to be provided by the application or other autoconfiguration.
* @return a configured {@link RagAssistant} bean.
*/
@Bean
public RagAssistant ragAssistant(final Rag<RagRequest, RagResponse> rag) {
return new RagAssistant(rag);
}
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/DefaultRag.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.Getter;
import ai.yda.framework.rag.core.augmenter.Augmenter;
import ai.yda.framework.rag.core.generator.Generator;
import ai.yda.framework.rag.core.model.RagContext;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
import ai.yda.framework.rag.core.retriever.Retriever;
import ai.yda.framework.rag.core.util.ContentUtil;
/**
* Provides a default mechanism for executing a Retrieval-Augmented Generation (RAG) process.
* <p>
* The RAG process is executed by retrieving relevant Contexts using a list of Retrievers, augmenting these Contexts
* using a list of Augmenters, and generating a Response using a Generator.
* </p>
*
* @author Nikita Litvinov
* @see Retriever
* @see Augmenter
* @see Generator
* @see DefaultStreamingRag
* @since 0.1.0
*/
@Getter(AccessLevel.PROTECTED)
public class DefaultRag implements Rag<RagRequest, RagResponse> {
private final List<Retriever<RagRequest, RagContext>> retrievers;
private final List<Augmenter<RagRequest, RagContext>> augmenters;
private final Generator<RagRequest, RagResponse> generator;
/**
* Constructs a new {@link DefaultRag} instance with the specified Retrievers, Augmenters and Generator.
*
* @param retrievers the list of {@link Retriever} objects used to retrieve {@link RagContext} data based on the
* {@link RagRequest}.
* @param augmenters the list of {@link Augmenter} objects used to augment or modify the list {@link RagContext}
* based on the {@link RagRequest}.
* @param generator the {@link Generator} object that generates the {@link RagResponse} based on the
* {@link RagRequest}.
*/
public DefaultRag(
final List<Retriever<RagRequest, RagContext>> retrievers,
final List<Augmenter<RagRequest, RagContext>> augmenters,
final Generator<RagRequest, RagResponse> generator) {
this.retrievers = retrievers;
this.augmenters = augmenters;
this.generator = generator;
}
/**
* Executes the Retrieval-Augmented Generation (RAG) process by retrieving relevant Contexts using a list of
* Retrievers, augmenting these Contexts using a list of Augmenters, and generating a Response using a Generator.
*
* @param request the {@link RagRequest} object from the User.
* @return the {@link RagResponse} object containing the results of the RAG operation.
*/
@Override
public RagResponse doRag(final RagRequest request) {
var contexts = retrievers.parallelStream()
.map(retriever -> retriever.retrieve(request))
.collect(Collectors.toUnmodifiableList());
for (var augmenter : augmenters) {
contexts = augmenter.augment(request, contexts);
}
return generator.generate(request, mergeContexts(contexts));
}
/**
* Merges the Knowledge from the list of {@link RagContext} objects into a single string. Each piece of Knowledge is
* separated by a point character.
*
* @param contexts the list of {@link RagContext} objects containing Knowledge data.
* @return a string that combines all pieces of Knowledge from the Contexts.
*/
protected String mergeContexts(final List<RagContext> contexts) {
return contexts.parallelStream()
.map(ragContext -> String.join(ContentUtil.SENTENCE_SEPARATOR, ragContext.getKnowledge()))
.collect(Collectors.joining(ContentUtil.SENTENCE_SEPARATOR));
}
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/DefaultStreamingRag.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.Getter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import ai.yda.framework.rag.core.augmenter.Augmenter;
import ai.yda.framework.rag.core.generator.StreamingGenerator;
import ai.yda.framework.rag.core.model.RagContext;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
import ai.yda.framework.rag.core.retriever.Retriever;
import ai.yda.framework.rag.core.util.ContentUtil;
/**
* Provides a default mechanism for executing a Retrieval-Augmented Generation (RAG) process in a streaming manner.
* <p>
* This class is useful when Responses need to be generated progressively, such as when dealing with large amounts of
* data or when the Response is expected to be produced in chunks. The streaming rag process is executed by retrieving
* relevant Contexts using a list of Retrievers, augmenting these Contexts using a list of Augmenters, and generating a
* Response using a Generator in a streaming manner.
* </p>
*
* @author Nikita Litvinov
* @see Retriever
* @see Augmenter
* @see StreamingGenerator
* @since 0.1.0
*/
@Getter(AccessLevel.PROTECTED)
public class DefaultStreamingRag implements StreamingRag<RagRequest, RagResponse> {
private final List<Retriever<RagRequest, RagContext>> retrievers;
private final List<Augmenter<RagRequest, RagContext>> augmenters;
private final StreamingGenerator<RagRequest, RagResponse> generator;
/**
* Constructs a new {@link DefaultStreamingRag} instance with the specified retrievers, augmenters and generator.
*
* @param retrievers the list of {@link Retriever} objects used to retrieve {@link RagContext} data based on the
* {@link RagRequest}.
* @param augmenters the list of {@link Augmenter} objects used to augment or modify the list {@link RagContext}
* based on the {@link RagRequest}.
* @param generator the {@link StreamingGenerator} object that generates the {@link Flux stream} of the of
* {@link RagResponse} objects based on the {@link RagRequest}.
*/
public DefaultStreamingRag(
final List<Retriever<RagRequest, RagContext>> retrievers,
final List<Augmenter<RagRequest, RagContext>> augmenters,
final StreamingGenerator<RagRequest, RagResponse> generator) {
this.retrievers = retrievers;
this.augmenters = augmenters;
this.generator = generator;
}
/**
* Executes the Retrieval-Augmented Generation (RAG) process by retrieving relevant Contexts using a list of
* Retrievers, augmenting these Contexts using a list of Augmenters, and generating a Response using a streaming
* Generator.
*
* @param request the {@link RagRequest} object from the User.
* @return a {@link Flux stream} of {@link RagResponse} objects containing the results of the RAG operation.
*/
@Override
public Flux<RagResponse> streamRag(final RagRequest request) {
return Flux.fromStream(retrievers.parallelStream())
.flatMap(retriever -> Mono.fromCallable(() -> retriever.retrieve(request)))
.collectList()
.flatMap(contexts -> {
for (var augmenter : augmenters) {
contexts = augmenter.augment(request, contexts);
}
return Mono.just(contexts);
})
.flatMap(this::mergeContexts)
.flatMapMany(context -> generator.streamGeneration(request, context));
}
/**
* Merges the knowledge into a single string. Each piece of knowledge is separated by a point character.
*
* @param contexts the list of {@link RagContext} objects containing knowledge data. Each piece of knowledge is
* separated by a point character.
* @return a {@link Mono<String>} that emits a single string, which is the result of combining all pieces of
* knowledge from the provided contexts.
*/
protected Mono<String> mergeContexts(final List<RagContext> contexts) {
return Flux.fromStream(contexts.parallelStream())
.map(ragContext -> String.join(ContentUtil.SENTENCE_SEPARATOR, ragContext.getKnowledge()))
.collect(Collectors.joining(ContentUtil.SENTENCE_SEPARATOR));
}
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/Rag.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
/**
* Provides a generic mechanism that coordinates the retrieval, augmentation, and generation processes to produce a
* final Response based on the User Request.
*
* @param <REQUEST> the generic type of the Request from the User, which must extend {@link RagRequest}.
* @param <RESPONSE> the generic type of the Response generated based on the given Request, which must extend
* {@link RagResponse}.
* @author Nikita Litvinov
* @see StreamingRag
* @see RagRequest
* @see RagResponse
* @since 0.1.0
*/
public interface Rag<REQUEST extends RagRequest, RESPONSE extends RagResponse> {
/**
* Performs a Retrieval-Augmented Generation (RAG) operation based on the provided Request.
*
* @param request the Request query from the User.
* @return the Response object containing the results of the RAG operation.
*/
RESPONSE doRag(REQUEST request);
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/StreamingRag.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core;
import reactor.core.publisher.Flux;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
/**
* Provides a generic mechanism that coordinates the retrieval, augmentation, and generation processes to produce a
* final Response based on the User Request in a streaming manner.
* <p>
* This class is useful when Responses need to be generated progressively, such as when dealing with large amounts of
* data or when the Response is expected to be produced in chunks.
* </p>
*
* @param <REQUEST> the generic type of the Request from the User, which must extend {@link RagRequest}.
* @param <RESPONSE> the generic type of the Response generated based on the given Request, which must extend
* {@link RagResponse}.
* @author Nikita Litvinov
* @see Rag
* @see RagRequest
* @see RagResponse
* @since 0.1.0
*/
public interface StreamingRag<REQUEST extends RagRequest, RESPONSE extends RagResponse> {
/**
* Performs a Retrieval-Augmented Generation (RAG) operation in a streaming manner based on the provided Request.
*
* @param request the Request object containing the necessary information for performing the RAG operation.
* @return a {@link Flux stream} of Response objects containing the results of the RAG operation.
*/
Flux<RESPONSE> streamRag(REQUEST request);
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/augmenter/Augmenter.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core.augmenter;
import java.util.List;
import ai.yda.framework.rag.core.model.RagContext;
import ai.yda.framework.rag.core.model.RagRequest;
/**
* Provides a generic mechanism for modifying or enriching the retrieved Contexts to enhance the final Response
* generation. This can involve filtering, re-ranking, or adding new information.
*
* @param <REQUEST> the generic type of the Request from the User, which must extend {@link RagRequest}.
* @param <CONTEXT> the generic type of the Context data that will be augmented or enhanced based on the given Request,
* which must extend {@link RagContext}.
* @author Nikita Litvinov
* @see RagRequest
* @see RagContext
* @since 0.1.0
*/
public interface Augmenter<REQUEST extends RagRequest, CONTEXT extends RagContext> {
/**
* Augments the given list of Context objects based on the provided Request.
*
* @param request the Request object that contains query data from the User.
* @param contexts a list of Context objects to be augmented. These Contexts are modified or enriched according to
* the logic defined in the implementation of this method.
* @return a list of augmented Context objects, which may be the same as the input list or a modified version,
* depending on the augmentation logic.
*/
List<CONTEXT> augment(REQUEST request, List<CONTEXT> contexts);
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/generator/Generator.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core.generator;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
/**
* Provides a generic mechanism that takes the User's Request and the retrieved Context to produce a final Response,
* often by leveraging a language model or other generative mechanism.
*
* @param <REQUEST> the generic type of the Request from the User, which must extend {@link RagRequest}.
* @param <RESPONSE> the generic type of the Response generated based on the given Request, which must extend
* {@link RagResponse}.
* @author Nikita Litvinov
* @see RagRequest
* @see RagResponse
* @see StreamingGenerator
* @since 0.1.0
*/
public interface Generator<REQUEST extends RagRequest, RESPONSE extends RagResponse> {
/**
* Generates Response based on the provided Request and Context.
*
* @param request the Request object that contains query data from the User.
* @param context the Context object that helps to better understand or interpret a Request that the User
* provides.
* @return the Response object generated as a result of processing the Request and Context. The Response should
* encapsulate the output generated by the mechanism used, such as a language model, and reflect the final answer or
* action based on the User's Request and the given Context.
*/
RESPONSE generate(REQUEST request, String context);
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/generator/StreamingGenerator.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core.generator;
import reactor.core.publisher.Flux;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
/**
* Provides a generic mechanism that takes the User's Request and the retrieved Context to produce a final Response,
* often by leveraging a language model or other generative mechanism.
* <p>
* This interface allow to generate responses in a streaming manner and is useful when Responses need to be generated
* progressively, such as when dealing with large amounts of data or when the Response is expected to be produced in
* chunks.
* </p>
*
* @param <REQUEST> the generic type of the Request from the User, which must extend {@link RagRequest}.
* @param <RESPONSE> the generic type of the Response generated based on the given Request, which must extend
* {@link RagResponse}.
* @author Nikita Litvinov
* @see RagRequest
* @see RagResponse
* @see Generator
* @since 0.1.0
*/
public interface StreamingGenerator<REQUEST extends RagRequest, RESPONSE extends RagResponse> {
/**
* Streams Responses based on the provided Request and Context. The method returns a Flux that emits a sequence of
* Responses, allowing for the processing of data in a non-blocking and incremental manner.
*
* @param request the Request object that contains query data from the User.
* @param context the Context object that helps to better understand or interpret a Request that the User
* provides.
* @return a {@link Flux stream} of Responses generated as a result of processing the Request and Context. Each
* response in the Flux represents a part of the overall Response, allowing for the incremental delivery of results.
*/
Flux<RESPONSE> streamGeneration(REQUEST request, String context);
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/model/RagContext.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core.model;
import java.util.List;
import java.util.Map;
import lombok.Builder;
import lombok.Getter;
/**
* Represents the Context data associated with a particular user query. It encapsulates both the Knowledge, which is
* typically a list of strings retrieved from external sources, and metadata, which contains additional key-value pairs
* providing context or other relevant information.
*
* @author Dmitry Marchuk
* @author Nikita Litvinov
* @since 0.1.0
*/
@Getter
@Builder(toBuilder = true)
public class RagContext {
/**
* A list of strings representing the retrieved Knowledge or information relevant to the User's query.
*/
private final List<String> knowledge;
/**
* A map containing metadata related to the Context. The keys are strings, and the values can be of any object type,
* allowing for flexible storage of various types of supplementary information.
*/
private final Map<String, Object> metadata;
/**
* Constructs a new {@link RagContext} instance with the specified Knowledge and metadata.
*
* @param knowledge the list of strings representing the retrieved information relevant to the User's query.
* @param metadata the map containing metadata related to the Context.
*/
public RagContext(final List<String> knowledge, final Map<String, Object> metadata) {
this.knowledge = knowledge;
this.metadata = metadata;
}
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/model/RagRequest.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
/**
* Represents a Request object that encapsulates the User's query.
*
* @author Dmitry Marchuk
* @author Nikita Litvinov
* @since 0.1.0
*/
@Getter
@Builder(toBuilder = true)
public class RagRequest {
/**
* The query string provided by the User, which is used as input for the retrieval and generation processes.
*/
private final String query;
/**
* Constructs a new {@link RagRequest} instance with the User's query.
*
* @param query the Request query from the User.
*/
@JsonCreator
public RagRequest(@JsonProperty("query") final String query) {
this.query = query;
}
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/model/RagResponse.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core.model;
import lombok.Builder;
import lombok.Getter;
/**
* Represents a Response object generated as a result of processing the Request and Context. The Response should
* encapsulate the output generated by the mechanism used, such as a language model, and reflect the final answer or
* action based on the User's Request and the given Context.
*
* @author Nikita Litvinov
* @since 0.1.0
*/
@Getter
@Builder(toBuilder = true)
public class RagResponse {
/**
* The result string generated by the mechanism used, such as a language model, and reflect the final answer or
* action based on the User's Request and the given Context.
*/
private final String result;
/**
* Constructs a new {@link RagResponse} instance with the result.
*
* @param result the result string generated based on the User's Request and the given Context.
*/
public RagResponse(final String result) {
this.result = result;
}
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/retriever/Retriever.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core.retriever;
import ai.yda.framework.rag.core.model.RagContext;
import ai.yda.framework.rag.core.model.RagRequest;
/**
* Provides a generic mechanism for fetching relevant data or documents that can provide Context based on the User
* Request.
*
* @param <REQUEST> the generic type of the Request from the User, which must extend {@link RagRequest}.
* @param <CONTEXT> the generic type of the Context data that will be retrieved based on the given Request, which must
* extend {@link RagContext}.
* @author Nikita Litvinov
* @see RagRequest
* @see RagContext
* @since 0.1.0
*/
public interface Retriever<REQUEST extends RagRequest, CONTEXT extends RagContext> {
/**
* Fetches relevant data or documents that can provide additional information based on the User Request.
*
* @param request the Request object that contains query data from the User.
* @return the Context object generated that contains additional information based on the User Request.
*/
CONTEXT retrieve(REQUEST request);
}
|
0 | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core | java-sources/ai/yda-framework/rag-core/0.1.0/ai/yda/framework/rag/core/util/ContentUtil.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.core.util;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
/**
* Provides utility methods to preprocess textual content.
*
* @author Iryna Kopchak
* @author Nikita Litvinov
* @since 0.1.0
*/
public final class ContentUtil {
/**
* A constant representing the period (.) character.
*/
public static final String SENTENCE_SEPARATOR = ".";
/**
* Preprocesses the provided content by converting it to UTF-8, formatting it to lowercase, normalizing whitespaces,
* removing HTML tags and splitting it into chunks of a specified maximum length.
*
* @param content the textual content to be preprocessed.
* @param maxCharacters the maximum number of characters per chunk.
* @return a list of strings where each string is a chunk of the processed content. The list is unmodifiable.
*/
public static List<String> preprocessAndSplitContent(final String content, final Integer maxCharacters) {
var preprocessedContent = new String(content.getBytes(), StandardCharsets.UTF_8).toLowerCase();
preprocessedContent = normalizeWhitespaces(preprocessedContent);
preprocessedContent = removeHtmlTags(preprocessedContent);
var contentChunks = new ArrayList<String>();
for (int i = 0; i < preprocessedContent.length(); i += maxCharacters) {
contentChunks.add(
preprocessedContent.substring(i, Math.min(preprocessedContent.length(), i + maxCharacters)));
}
return contentChunks;
}
/**
* Normalizes whitespaces in the given content by replacing all sequences of whitespace characters (such as spaces,
* tabs, and newlines) with a single space.
*
* @param content the textual content to be normalized.
* @return the normalized content with sequences of whitespace replaced by a single space.
*/
private static String normalizeWhitespaces(final String content) {
return content.replaceAll("\\s+", " ");
}
/**
* Removes all HTML tags from the content.
*
* @param content the input textual content from which HTML tags will be removed.
* @return the content with all HTML tags removed.
*/
private static String removeHtmlTags(final String content) {
var document = Jsoup.parse(content);
return document.text();
}
private ContentUtil() {}
}
|
0 | java-sources/ai/yda-framework/rag-starter/0.1.0/ai/yda/framework/rag | java-sources/ai/yda-framework/rag-starter/0.1.0/ai/yda/framework/rag/autoconfigure/RagAutoConfiguration.java | /*
* YDA - Open-Source Java AI Assistant.
* Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/>
* This file is part of YDA.
* YDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* YDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with YDA. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.yda.framework.rag.autoconfigure;
import java.util.List;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import ai.yda.framework.rag.core.DefaultRag;
import ai.yda.framework.rag.core.augmenter.Augmenter;
import ai.yda.framework.rag.core.generator.Generator;
import ai.yda.framework.rag.core.model.RagContext;
import ai.yda.framework.rag.core.model.RagRequest;
import ai.yda.framework.rag.core.model.RagResponse;
import ai.yda.framework.rag.core.retriever.Retriever;
/**
* Autoconfiguration class for setting up a {@link DefaultRag} bean. This class provides the automatic configuration for
* a {@link DefaultRag} instance, which is a key component in the Retrieval-Augmented Generation (RAG) framework. The
* {@link DefaultRag} is configured with a list of Retrievers that fetch relevant Context, Augmenters that enhance
* the Context, and a Generator that produces the final Response based on the augmented Context.
*
* @author Nikita Litvinov
* @see DefaultRag
* @see Retriever
* @see Augmenter
* @see Generator
* @since 0.1.0
*/
@AutoConfiguration
public class RagAutoConfiguration {
/**
* Default constructor for {@link RagAutoConfiguration}.
*/
public RagAutoConfiguration() {}
/**
* Defines a {@link DefaultRag} bean, which is configured with the provided lists of {@link Retriever} and
* {@link Augmenter}, along with the {@link Generator} used to generate Responses.
*
* @param retrievers the list of {@link Retriever} beans used for retrieving Context based on the Request.
* @param augmenters the list of {@link Augmenter} beans used for enhancing the retrieved Context.
* @param generator the {@link Generator} bean used for generating Responses based on the augmented Context.
* @return a configured {@link DefaultRag} instance.
*/
@Bean
public DefaultRag defaultRag(
final List<Retriever<RagRequest, RagContext>> retrievers,
final List<Augmenter<RagRequest, RagContext>> augmenters,
final Generator<RagRequest, RagResponse> generator) {
return new DefaultRag(retrievers, augmenters, generator);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.