import lime
import shap
import matplotlib.pyplot as plt
import numpy as np
import ast

def lime_values_to_weights_dict(class_names, lime_explanation):
  weights_dict = {}
  for i,label in enumerate(class_names):
    weight_list = lime_explanation.as_list(label=i)
    weight_list = [(str(x[0]), float(x[1])) for x in weight_list] #remove np.str & np.float
    weights_dict[label] = weight_list

  return weights_dict


def shap_values_to_weights_dict(class_names, classification, shap_values, feature_names):
  weights_dict = {}

  if classification == True :
    shap_values = shap_values.T
    for i,weights in enumerate(shap_values):
      key = str(class_names[i])
      val = list(zip(feature_names,weights.tolist()))
      weights_dict[key] = val

  else :
    shap_values = [shap_values]
    key = "target"
    for i,weights in enumerate(shap_values):
      val = list(zip(feature_names,weights.tolist()))
      weights_dict[key] = val

  return weights_dict

# modified as_pyplot function from LIME library
def weights_dict_to_pyplot(weights_dict, label, figsize=(4,4)):
  exp = ast.literal_eval(str(weights_dict))
  # print(exp)
  exp = exp[label]
  fig = plt.figure(figsize=figsize)
  vals = [x[1] for x in exp]
  names = [x[0] for x in exp]
  vals.reverse()
  names.reverse()
  colors = ['green' if x > 0 else 'red' for x in vals]
  pos = np.arange(len(exp)) + .5
  plt.barh(pos, vals, align='center', color=colors)
  plt.yticks(pos, names)
  title = 'Local explanation for class %s' % label
  plt.title(title)
  return fig