import pickle as pkl
import numpy as np
import faiss
import math

class Faiss_cluster:
    
    @classmethod
    def compute_centroid(cls, cluster_vector, vector_post):
        """
            create centroid vector with new post
        """
        vectors = []
        vectors.append(cluster_vector)
        vectors.append(vector_post)
        vectors = np.asarray(vectors, dtype=np.float32)
        dimension = 300
        ncentroids = 1
        verbose = False
        kmeans = faiss.Kmeans(dimension, ncentroids, verbose=verbose)
        kmeans.train(np.ascontiguousarray(vectors))
        
        return kmeans.centroids[0]
    
    
    @classmethod
    def faiss_search_similarity(cls, vectors, vector_post):
        """
            INDEX by faiss to quick search similar vectors
        """
        vectors = vectors.astype('float32')
        dimension = 300
        quantiser = faiss.IndexFlatL2(dimension)  
        index = faiss.IndexIVFFlat(quantiser, dimension, faiss.METRIC_L2)
        index.train(np.ascontiguousarray(vectors))
        index.add(np.ascontiguousarray(vectors))
        k = 1
        D, I = index.search(np.ascontiguousarray(vector_post), k)
        proba_sqrt = float(D[0][0] * 10)
        if proba_sqrt < 2.5:
            return I[0][0]
        else:
            return False