# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/11_test_metrics_calculator.ipynb (unless otherwise specified).

__all__ = ['generate_results', 'pre_rec_f1', 'brand_confusion_matrix', 'find_closest', 'size_metrics']

# Cell

import pandas as pd
import numpy as np
from sklearn.metrics import precision_recall_fscore_support, classification_report
from sklearn.metrics import precision_score, recall_score, f1_score, confusion_matrix, average_precision_score

# Cell

def generate_results(df1, df2, merge_column= "Image_ID"):

    """df1: generated csv from models
       df2: manual csv existing

    """
    intersect = pd.merge(results, original_results, on=[merge_column], how="left")
    pre_rec_f1_vals = pre_rec_f1(intersect)

def pre_rec_f1(merged_df, col1=" Is_TV_annotated", col2= "is_outer_keypoint_detected", labels=[True, False]):
    pre_tv_detector = precision_score(merged_df[col1], merged_df[col2])
    rec_tv_detector = recall_score(merged_df[col1], merged_df[col2])
    f1_tv_detector = f1_score(merged_df[col1], merged_df[col2])

    confusion_matrix(merged_df[col1], merged_df[col2],labels=labels)
    return pre_tv_detector, rec_tv_detector, f1_tv_detector


def brand_confusion_matrix(merged_df, col1 = "brand", col2 = "Brand Present"):
    merged_df[col2] = merged_df[col2].replace(np.nan,'')
    merged_df[col1] = merged_df[col1].replace('logo not detected', '')

    merged_df[col2] = merged_df[col2].apply(lambda x:"others" if x not in ["sony", "samsung", "lg", "panasonic", "sharp", "philips"] else x)

    merged_df[col2] = merged_df[col2].apply(lambda x:x.upper())

    merged_df[col1]= merged_df[col1].apply(lambda x:x.upper())

    merged_df[col1] = merged_df[col1].replace("", "OTHERS")

    confusion_matrix(intersect[col2], intersect[col1],labels=["SONY","SAMSUNG", "LG", "PANASONIC", "SHARP",
                                                                        "PHILIPS", "OTHERS"])


def find_closest(num, array):
    val = [ abs(num-a) for a in array]
    i = min(val)
    index = val.index(i)
    return array[index]



def size_metrics(merged_df, col1= "size", col2= "TV_size_original"):
    possible_sizes = [0, 24, 32, 40, 43, 49, 55, 60, 65, 75, 100]
    intersect["Sticky_note_height"] = intersect["Sticky_note_height"].apply(lambda x:float(x))
    k = intersect[intersect["Sticky_note_height"] > 0][["size", "TV_size_original"]]
    intersect.loc[intersect[col1] > 85, [col1]] = 100
    intersect.loc[intersect[col1] < 20, [col1]] = 0
    intersect.loc[intersect[col2] > 85, [col2]] = 100
    intersect.loc[intersect[col2] < 20, [col2]] = 0
    intersect["size_using_outer_approximated"] = intersect[col1].apply(lambda x: find_closest(x, possible_sizes))
    intersect["TV_size_original_approximated"] = intersect[col2].apply(lambda x: find_closest(x, possible_sizes))
    merged_df.to_excel("final.xlsx")
    print(classification_report(intersect["size_using_outer_approximated"], intersect["TV_size_original_approximated"]))