-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Added feature modules for OpenAI CLIP * Minor refactoring of utility classes * Refactored common image preprocessing logic into helper class Co-authored-by: Silvan Heller <[email protected]> Co-authored-by: Florian Spiess <[email protected]> Former-commit-id: c2315f0
- Loading branch information
1 parent
2bd8d51
commit b504855
Showing
46 changed files
with
698 additions
and
94 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
111 changes: 111 additions & 0 deletions
111
cineast-core/src/main/java/org/vitrivr/cineast/core/features/CLIPImage.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
package org.vitrivr.cineast.core.features; | ||
|
||
import org.apache.logging.log4j.LogManager; | ||
import org.apache.logging.log4j.Logger; | ||
import org.tensorflow.SavedModelBundle; | ||
import org.tensorflow.Tensor; | ||
import org.tensorflow.ndarray.Shape; | ||
import org.tensorflow.ndarray.buffer.DataBuffers; | ||
import org.tensorflow.ndarray.buffer.FloatDataBuffer; | ||
import org.tensorflow.types.TFloat16; | ||
import org.vitrivr.cineast.core.config.QueryConfig; | ||
import org.vitrivr.cineast.core.config.ReadableQueryConfig; | ||
import org.vitrivr.cineast.core.data.FloatVectorImpl; | ||
import org.vitrivr.cineast.core.data.frames.VideoFrame; | ||
import org.vitrivr.cineast.core.data.score.ScoreElement; | ||
import org.vitrivr.cineast.core.data.segments.SegmentContainer; | ||
import org.vitrivr.cineast.core.features.abstracts.AbstractFeatureModule; | ||
import org.vitrivr.cineast.core.util.images.ImagePreprocessingHelper; | ||
|
||
import java.awt.image.BufferedImage; | ||
import java.util.Collections; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
|
||
public class CLIPImage extends AbstractFeatureModule { | ||
|
||
private static final Logger LOGGER = LogManager.getLogger(); | ||
|
||
private static final int EMBEDDING_SIZE = 512; | ||
private static final String TABLE_NAME = "features_clip"; | ||
private static final ReadableQueryConfig.Distance DISTANCE = ReadableQueryConfig.Distance.cosine; | ||
|
||
private static final int IMAGE_SIZE = 224; | ||
|
||
private static final String RESOURCE_PATH = "resources/CLIP/"; | ||
private static final String EMBEDDING_MODEL = "clip-image-vit-32-tf"; | ||
|
||
private static final String EMBEDDING_INPUT = "input"; | ||
private static final String EMBEDDING_OUTPUT = "output"; | ||
|
||
private static final float[] MEAN = new float[]{0.48145466f, 0.4578275f, 0.40821073f}; | ||
private static final float[] STD = new float[]{0.26862954f, 0.26130258f, 0.27577711f}; | ||
|
||
private SavedModelBundle model; | ||
|
||
public CLIPImage() { | ||
super(TABLE_NAME, 1f, EMBEDDING_SIZE); | ||
model = SavedModelBundle.load(RESOURCE_PATH + EMBEDDING_MODEL); | ||
} | ||
|
||
@Override | ||
public void processSegment(SegmentContainer shot) { | ||
|
||
if (shot.getMostRepresentativeFrame() == VideoFrame.EMPTY_VIDEO_FRAME) { | ||
return; | ||
} | ||
|
||
float[] embeddingArray = embedImage(shot.getMostRepresentativeFrame().getImage().getBufferedImage()); | ||
this.persist(shot.getId(), new FloatVectorImpl(embeddingArray)); | ||
|
||
} | ||
|
||
@Override | ||
protected ReadableQueryConfig setQueryConfig(ReadableQueryConfig qc) { | ||
return QueryConfig.clone(qc).setDistance(DISTANCE); | ||
} | ||
|
||
@Override | ||
public List<ScoreElement> getSimilar(SegmentContainer sc, ReadableQueryConfig qc) { | ||
|
||
if (sc.getMostRepresentativeFrame() == VideoFrame.EMPTY_VIDEO_FRAME) { | ||
return Collections.emptyList(); | ||
} | ||
|
||
QueryConfig queryConfig = QueryConfig.clone(qc); | ||
queryConfig.setDistance(DISTANCE); | ||
|
||
float[] embeddingArray = embedImage(sc.getMostRepresentativeFrame().getImage().getBufferedImage()); | ||
|
||
return getSimilar(embeddingArray, queryConfig); | ||
} | ||
|
||
private float[] embedImage(BufferedImage img) { | ||
|
||
float[] rgb = prepareImage(img); | ||
|
||
try (TFloat16 imageTensor = TFloat16.tensorOf(Shape.of(1, 3, IMAGE_SIZE, IMAGE_SIZE), DataBuffers.of(rgb))) { | ||
HashMap<String, Tensor> inputMap = new HashMap<>(); | ||
inputMap.put(EMBEDDING_INPUT, imageTensor); | ||
|
||
Map<String, Tensor> resultMap = model.call(inputMap); | ||
|
||
try (TFloat16 encoding = (TFloat16) resultMap.get(EMBEDDING_OUTPUT)) { | ||
|
||
float[] embeddingArray = new float[EMBEDDING_SIZE]; | ||
FloatDataBuffer floatBuffer = DataBuffers.of(embeddingArray); | ||
encoding.read(floatBuffer); | ||
|
||
return embeddingArray; | ||
|
||
} | ||
} | ||
} | ||
|
||
private static float[] prepareImage(BufferedImage img) { | ||
return ImagePreprocessingHelper.imageToCHWArray( | ||
ImagePreprocessingHelper.squaredScaleCenterCrop(img, IMAGE_SIZE), | ||
MEAN, STD); | ||
} | ||
} |
149 changes: 149 additions & 0 deletions
149
cineast-core/src/main/java/org/vitrivr/cineast/core/features/CLIPText.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
package org.vitrivr.cineast.core.features; | ||
|
||
import org.apache.logging.log4j.LogManager; | ||
import org.apache.logging.log4j.Logger; | ||
import org.tensorflow.SavedModelBundle; | ||
import org.tensorflow.Tensor; | ||
import org.tensorflow.ndarray.LongNdArray; | ||
import org.tensorflow.ndarray.NdArrays; | ||
import org.tensorflow.ndarray.Shape; | ||
import org.tensorflow.ndarray.buffer.DataBuffers; | ||
import org.tensorflow.ndarray.buffer.FloatDataBuffer; | ||
import org.tensorflow.types.TFloat16; | ||
import org.tensorflow.types.TInt64; | ||
import org.vitrivr.cineast.core.config.QueryConfig; | ||
import org.vitrivr.cineast.core.config.ReadableQueryConfig; | ||
import org.vitrivr.cineast.core.data.CorrespondenceFunction; | ||
import org.vitrivr.cineast.core.data.distance.DistanceElement; | ||
import org.vitrivr.cineast.core.data.distance.SegmentDistanceElement; | ||
import org.vitrivr.cineast.core.data.providers.primitive.FloatArrayTypeProvider; | ||
import org.vitrivr.cineast.core.data.providers.primitive.PrimitiveTypeProvider; | ||
import org.vitrivr.cineast.core.data.providers.primitive.StringTypeProvider; | ||
import org.vitrivr.cineast.core.data.score.ScoreElement; | ||
import org.vitrivr.cineast.core.data.segments.SegmentContainer; | ||
import org.vitrivr.cineast.core.db.DBSelector; | ||
import org.vitrivr.cineast.core.db.DBSelectorSupplier; | ||
import org.vitrivr.cineast.core.db.setup.EntityCreator; | ||
import org.vitrivr.cineast.core.features.retriever.Retriever; | ||
import org.vitrivr.cineast.core.util.text.ClipTokenizer; | ||
|
||
import java.util.Collections; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.function.Supplier; | ||
|
||
import static org.vitrivr.cineast.core.util.CineastConstants.FEATURE_COLUMN_QUALIFIER; | ||
import static org.vitrivr.cineast.core.util.CineastConstants.GENERIC_ID_COLUMN_QUALIFIER; | ||
|
||
public class CLIPText implements Retriever { | ||
|
||
private static final Logger LOGGER = LogManager.getLogger(); | ||
|
||
private static final int EMBEDDING_SIZE = 512; | ||
private static final String TABLE_NAME = "features_clip"; | ||
private static final ReadableQueryConfig.Distance DISTANCE = ReadableQueryConfig.Distance.cosine; | ||
|
||
private static final String RESOURCE_PATH = "resources/CLIP/"; | ||
private static final String EMBEDDING_MODEL = "clip-text-vit-32-tf"; | ||
|
||
private static final String EMBEDDING_INPUT = "input"; | ||
private static final String EMBEDDING_OUTPUT = "output"; | ||
|
||
private static final CorrespondenceFunction CORRESPONDENCE = CorrespondenceFunction.linear(1f); | ||
|
||
private static SavedModelBundle model; | ||
|
||
private DBSelector selector; | ||
private ClipTokenizer ct = new ClipTokenizer(); | ||
|
||
private static void init() { | ||
if (model == null) { | ||
model = SavedModelBundle.load(RESOURCE_PATH + EMBEDDING_MODEL); | ||
} | ||
} | ||
|
||
public CLIPText() { | ||
init(); | ||
} | ||
|
||
@Override | ||
public void initalizePersistentLayer(Supplier<EntityCreator> supply) { | ||
supply.get().createFeatureEntity(TABLE_NAME, true, EMBEDDING_SIZE); | ||
} | ||
|
||
@Override | ||
public void dropPersistentLayer(Supplier<EntityCreator> supply) { | ||
supply.get().dropEntity(TABLE_NAME); | ||
} | ||
|
||
@Override | ||
public void init(DBSelectorSupplier selectorSupply) { | ||
this.selector = selectorSupply.get(); | ||
this.selector.open(TABLE_NAME); | ||
} | ||
|
||
@Override | ||
public List<ScoreElement> getSimilar(SegmentContainer sc, ReadableQueryConfig qc) { | ||
|
||
String text = sc.getText(); | ||
|
||
if (text == null || text.isBlank()) { | ||
return Collections.emptyList(); | ||
} | ||
|
||
return getSimilar(new FloatArrayTypeProvider(embedText(text)), qc); | ||
} | ||
|
||
private float[] embedText(String text) { | ||
|
||
long[] tokens = ct.clipTokenize(text); | ||
|
||
LongNdArray arr = NdArrays.ofLongs(Shape.of(1, tokens.length)); | ||
for (int i = 0; i < tokens.length; i++) { | ||
arr.setLong(tokens[i], 0, i); | ||
} | ||
|
||
try (TInt64 textTensor = TInt64.tensorOf(arr)) { | ||
|
||
HashMap<String, Tensor> inputMap = new HashMap<>(); | ||
inputMap.put(EMBEDDING_INPUT, textTensor); | ||
|
||
Map<String, Tensor> resultMap = model.call(inputMap); | ||
|
||
try (TFloat16 embedding = (TFloat16) resultMap.get(EMBEDDING_OUTPUT)) { | ||
|
||
float[] embeddingArray = new float[EMBEDDING_SIZE]; | ||
FloatDataBuffer floatBuffer = DataBuffers.of(embeddingArray); | ||
embedding.read(floatBuffer); | ||
return embeddingArray; | ||
|
||
} | ||
} | ||
} | ||
|
||
@Override | ||
public List<ScoreElement> getSimilar(String segmentId, ReadableQueryConfig qc) { | ||
List<PrimitiveTypeProvider> list = this.selector.getFeatureVectorsGeneric(GENERIC_ID_COLUMN_QUALIFIER, new StringTypeProvider(segmentId), FEATURE_COLUMN_QUALIFIER); | ||
if (list.isEmpty()) { | ||
LOGGER.warn("No feature vector for shotId {} found, returning empty result-list", segmentId); | ||
return Collections.emptyList(); | ||
} | ||
return getSimilar(list.get(0), qc); | ||
} | ||
|
||
private List<ScoreElement> getSimilar(PrimitiveTypeProvider queryProvider, ReadableQueryConfig qc) { | ||
ReadableQueryConfig qcc = QueryConfig.clone(qc).setDistance(DISTANCE); | ||
List<SegmentDistanceElement> distances = this.selector.getNearestNeighboursGeneric(qc.getResultsPerModule(), queryProvider, FEATURE_COLUMN_QUALIFIER, SegmentDistanceElement.class, qcc); | ||
CorrespondenceFunction function = qcc.getCorrespondenceFunction().orElse(CORRESPONDENCE); | ||
return DistanceElement.toScore(distances, function); | ||
} | ||
|
||
@Override | ||
public void finish() { | ||
if (this.selector != null) { | ||
this.selector.close(); | ||
this.selector = null; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
cineast-core/src/main/java/org/vitrivr/cineast/core/features/HOGMirflickr25K256.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
cineast-core/src/main/java/org/vitrivr/cineast/core/features/HOGMirflickr25K512.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.