import { Image , Partition , Category } from '@piximi/types' ; import { compileExpression } from 'filtrex' ; let changeImagesVisibilityFunction ; let invisibleImages = [ ] ; const categoryDict = { } ; const flattendedImages = [ ] ; export const ImageSearch = ( searchInput ) => { try { var searchFunction = compileExpression ( searchInput ) ; } catch ( error ) { alert ( 'invalid search input' ) ; return true ; } const negativeSearchResults = [ ] ; const positiveSearchResults = [ ] ; flattendedImages . forEach ( image => { if ( searchFunction ( image ) === 0 ) { negativeSearchResults . push ( image . identifier ) ; } else { positiveSearchResults . push ( image . identifier ) ; } } ) ; changeImagesVisibilityFunction ( negativeSearchResults , false ) ; changeImagesVisibilityFunction ( positiveSearchResults , true ) ; invisibleImages = negativeSearchResults ; return invisibleImages . length !== 0 ; } ; export const ClearSearch = ( ) => { changeImagesVisibilityFunction ( invisibleImages , true ) ; } ; export const InitializeSearch = ( categories , images , changeImagesVisibility ) => { changeImagesVisibilityFunction = changeImagesVisibility ; categories . forEach ( ( category ) => { categoryDict [ category . identifier ] = category . description ; } ) ; images . forEach ( ( image ) => flattenImage ( image ) ) ; } ; const getPrediction = ( image ) => { let maxScore = 0 ; let lableIndex = 0 ; for ( let i = 0 ; i < image . scores . length ; i ++ ) { if ( image . scores [ i ] . probability > maxScore ) { maxScore = image . scores [ i ] . probability ; lableIndex = i ; } } return { prediction : image . scores [ lableIndex ] . categoryIdentifier , probability : image . scores [ lableIndex ] . probability } ; } ; const flattenImage = ( image ) => { let probability ; let prediction ; if ( image . scores . length === 0 ) { probability = - 1 ; prediction = 'none' ; } else { const imagePrediction = getPrediction ( image ) ; probability = imagePrediction . probability ; prediction = imagePrediction . prediction ; } const category = categoryDict [ image . categoryIdentifier ] ; const partition = Partition [ image . partition ] . toLowerCase ( ) ; flattendedImages . push ( { identifier : image . identifier , category : category , probability : probability , prediction : prediction , partition : partition } ) ; } ;