
import argparse
from helper import load_image, save_image_file, inverse_normalize
import clip
import open_clip
import math
import torch
from sklearn.decomposition import TruncatedSVD

def compute_lipschitz(original_input, epsilon, vec):
    vec = np.array(vec)
    vec = torch.from_numpy(vec)
    vec = vec.reshape(1,3,224,224)
    
    perturbed_input = original_input + epsilon*vec
    perturbed_output = model2.encode_image(perturbed_input)
    
    diff = original_input - perturbed_input
    diff = diff.flatten()
    change_of_output = torch.norm(original_output - perturbed_output)
    # change_of_input = torch.norm(original_input - perturbed_input)
    change_of_input = torch.norm(diff)
    # print('change of input and change of output ', change_of_input.detach().item(), '   ', change_of_output.detach().item())
    lc = change_of_output.item()/change_of_input.detach().item()
    return lc



def get_lcs(svd):
    vecs = svd.components_
    lc_vals = []
    for i in range(len(vecs)):
        lc = compute_lipschitz(original_input= original_input, epsilon = 1e-5, vec = vecs[i])
        lc_vals.append(lc)
        
        
def get_kdeplot():  
    import seaborn as sns
    sns.kdeplot(np.array(lc_arr))
    plt.xlabel('lc_vals')
    # plt.savefig('./res/lipschitz_vals.pdf')
    plt.show()
    
    
def lc_bars():
    plt.rcParams.update({'font.size': 12})
    plt.bar(range(0,len(svd1.singular_values_)),np.array(svd1.singular_values_),width=.3)
    plt.xlabel('number')
    plt.ylabel('singular values')
    plt.savefig('./res/singular_vals_bar.pdf')
    plt.show()
    
def ldlc_bars():
    plt.rcParams.update({'font.size': 12})
    fig = plt.figure(figsize = (8,4))
    bar_vals = np.array(list(lc_map.values()))
    print(bar_vals)
    plt.bar(range(0,len(bar_vals)),bar_vals,width=0.3)
    plt.xlabel('direction')
    plt.ylabel('ldlc values')
    plt.savefig('./res/ldlc_values_bar_using_image_diffs_final.pdf')
    plt.show()






