#!/usr/bin/env python
# coding: utf-8

# In[49]:


#Loading neccesary packages
import numpy as np
import pandas as pd
import plotly.express as px
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules


# In[4]:


#Reading Data 
data=pd.read_csv('transactionData.csv',encoding='latin-1')


# In[5]:


data.head()


# In[46]:


predata=data[["Invoice No","ITEM NAME"]]


# In[47]:


def bar_plot(df,col):

    fig = px.bar(df,
        x = df[col].value_counts().keys(), 
        y = df[col].value_counts().values,
        color= df[col].value_counts().keys()
    )
    fig.update_layout(
    xaxis_title= col,
    yaxis_title="Count",
    legend_title=col,
    font_family="Courier New",
    font_color="blue",
    title_font_family="Times New Roman",
    title_font_color="red",
    legend_title_font_color="green"
)
    
    fig.show()


# In[51]:


#want to dispaly on frontend
bar_plot(predata,'ITEM NAME')


# In[125]:


#all count items name
predata['ITEM NAME'].value_counts()


# In[6]:


#Data Cleaning
data['ITEM NAME'] = data['ITEM NAME'].str.strip() #removes spaces from beginning and end
data.dropna(axis=0, subset=['Invoice No'], inplace=True) #removes duplicate invoice
data['Invoice No'] = data['Invoice No'].astype('str') #converting invoice number to be string
data = data[~data['Invoice No'].str.contains('C')] #remove the credit transactions 
data.head()


# In[7]:



mybasket = (data.groupby(['Invoice No', 'ITEM NAME'])['QTY.']
          .sum().unstack().reset_index().fillna(0)
          .set_index('Invoice No'))


# In[8]:


mybasket.head()


# In[9]:


#converting all positive vaues to 1 and everything else to 0
def my_encode_units(x):
    if x <= 0:
        return 0
    if x >= 1:
        return 1

my_basket_sets = mybasket.applymap(my_encode_units)


# In[10]:


my_basket_sets


# # TRAINING MODEL

# In[11]:


my_basket_sets=my_basket_sets.replace(np.nan,0)


# In[12]:


#Generatig frequent itemsets
my_frequent_itemsets = apriori(my_basket_sets, min_support=0.07, use_colnames=True,verbose=1)


# In[13]:


my_frequent_itemsets


# In[14]:


#generating rules
my_rules = association_rules(my_frequent_itemsets, metric="lift", min_threshold=1)


# In[15]:


#viewing top 100 rules
my_rules.head(100)


# # Making recommendations

# In[16]:


my_basket_sets['Airtel 50/='].sum()


# In[17]:


my_basket_sets['Dialog 50'].sum()


# In[19]:


#Filtering rules based on condition
rule=my_rules[ (my_rules['lift'] >= 3) &
       (my_rules['confidence'] >= 0.3) ]


# In[20]:


rule


# In[101]:


a = rule[["antecedents","consequents"]].head()
antecedents = a[["antecedents"]]
consequents = a[["consequents"]]
a


# In[138]:


a = rule[["antecedents","consequents"]].head().values.tolist()
A =[list(x) for x in a]
A


# In[136]:


first = antecedents['antecedents'].values.tolist()
C=[list(x) for x in first]
C[0]


# In[137]:


second = consequents['consequents'].values.tolist()
D=[list(x)for x in second]
D[0]


# In[134]:





# In[57]:


B= a.to_dict
B


# In[ ]:




