def add_file_manually(textfile_path, original_images_path, image_path, imagename):
    '''
    This function opens a text file and wtries the crop points and RGB colors
    as extracted from the palette by opening each of the design-seed images
    already saved to the disk. It will open an image as specified in the input
    path one by one and send to for processing. After the images processed from
    the process_image() function it will write the contents of it to the file.

    Args:
        textfile: A file pointer object for creating and opening a file to
                  write.
        original_images_path: Absolute path of the location where design-seed
                              images are stored on the local disk.

    Returns:
        None
    '''
    appendfile = open(textfile_path, "a+")
    #check if already exists
    lines = appendfile.readlines()
    exists =0
    for line in lines:
        if imagename in line:
            print(imagename, "already in file!")
            exists =1
            break
    if not exists:
        # Image processing locally
        i = Image.open(image_path + imagename)

        appendfile.write(imagename + ' I:' + str(0) + ' P:'
                           + str(0) + '\n')

        #use clustering to get palette
        lab_values=cluster_image(i, k_clusters=5)
        rgb_values =[]
        for l in lab_values:
            print(l)
            rgb=LAB_to_RGB(l)      
            rgb_values.append(rgb)
        print(rgb_values)   
        appendfile.write(str(rgb_values).strip("[]"))
        appendfile.write('\n')
        i.save(original_images_path + "slices/" + imagename)
        # # Create a visible palette for visualing the retrieved colors
        palette_im = Image.new('RGB', (500, 300))
        draw = ImageDraw.Draw(palette_im)
        for pos, color_val in enumerate(rgb_values):
            draw.rectangle([int(pos * 500 / len(rgb_values)), 0,
                            int(pos * 500 / len(rgb_values) +
                                500 / len(rgb_values)), 300], color_val)
        del draw
        palette_im.save(original_images_path + "palettes/" + imagename)
    appendfile.close()
def find_nearest_cluster(starting_filename):
    '''
    Takes the filename of an image, opens the image, deserializes the
    list of lists which contains a filename and its corresponding clusters,
    and clusters the test image.

    For each cluster in the training set, calculates the distance between
    the images by using Euclidean Distance on the nearest cluster color
    points between the two images and summing them all together.

    The result is the image in the training set that has the smallest
    distance from the test image.

    Args:
        starting_filename: An input random image.

    Returns:
        Closest image match from the training set.
    '''
    print('In find_nearest_cluster')
    # Obtain test image
    starting_img = Image.open(starting_filename)
    starting_img = starting_img.resize((150, 150))
    # Cluster test image
    #print('Here clustering')
    test_codes, labels = cluster.cluster_image(starting_img)
    print('Clustered test image')
    # warnings.filterwarnings('error')
    # print('Here')
    # try:
    #     test_codes = cluster.cluster_image(starting_img)
    #     print('Done clustering')
    # except Warning:
    #     print('Warning was raised as an exception!')
    # Obtain training clusters
    clusterfilename = "backend/clusterlistbytes.txt"
    training_clusters = cluster.deserialize(clusterfilename)
    #print('got DS clusters')
    current_distance = -1
    current_image = None
    current_image_clusters = []
    #print('Looking for match...')
    for filename, colors in training_clusters:
        # Get training image
        # For each training image, create a matrix of euclidian
        result = create_distance_matrix(test_codes, colors)
        mymunk = Munkres()
        try:
            bipartite_pairings = mymunk.compute(result)
            #print(filename)
            potential_distance = calculate_distance(bipartite_pairings, result)
            #print('potential_distance, current_distance', potential_distance, current_distance)
            if current_distance < 0 or potential_distance < current_distance:
                current_distance = potential_distance
                current_image = filename
                current_image_clusters = colors
        except:
            print('Error in bipartite_pairings:', filename, colors)
        #print('new current_distance', current_distance)

    #print('Min distance:', current_distance)
    return current_image, test_codes, current_image_clusters, current_distance