Alamgirapi commited on
Commit
fe77a26
·
verified ·
1 Parent(s): 7c15afe

Upload folder NoCodeTextClassifier

Browse files
NoCodeTextClassifier/EDA.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import seaborn as sns
2
+ import matplotlib.pyplot as plt
3
+ import streamlit as st
4
+ import numpy as np
5
+ from NoCodeTextClassifier.preprocessing import TextCleaner
6
+ from sklearn.preprocessing import LabelEncoder
7
+
8
+
9
+ class Informations:
10
+ def __init__(self, data, text_data, target):
11
+ self.data = data
12
+ self.text_data = text_data
13
+ self.target = target
14
+
15
+ def shape(self):
16
+ return self.data.shape
17
+
18
+ def class_imbalanced(self):
19
+ return self.data[self.target].value_counts()
20
+
21
+ def missing_values(self):
22
+ return self.data.isnull().sum()
23
+
24
+ def label_encoder(self):
25
+ encoder = LabelEncoder()
26
+ target = encoder.fit_transform(self.data[self.target])
27
+ return target
28
+
29
+ def clean_text(self):
30
+ text_cleaner = TextCleaner()
31
+ return self.data[self.text_data].apply(lambda x: text_cleaner.clean_text(x))
32
+
33
+ def text_length(self):
34
+ return self.data[self.text_data].apply(lambda x: len(x))
35
+
36
+ def analysis_text_length(self, text_length):
37
+ result = self.data[text_length].describe()
38
+ return result
39
+
40
+ def correlation(self, other_feature):
41
+ return self.data[other_feature].corr(self.data["target"])
42
+
43
+
44
+
45
+
46
+
47
+ class Visualizations:
48
+ def __init__(self, data, text_data, target):
49
+ self.data = data
50
+ self.text_data = text_data
51
+ self.target = target
52
+
53
+ def simple_plot(self):
54
+ # Generate sample data
55
+ x = np.linspace(0, 10, 100)
56
+ y = np.sin(x)
57
+ fig, ax = plt.subplots()
58
+ ax.plot(x, y, label="Sine Wave")
59
+ ax.set_title("Matplotlib Plot in Streamlit")
60
+ ax.set_xlabel("X-axis")
61
+ ax.set_ylabel("Y-axis")
62
+ ax.legend()
63
+ # Display the plot in Streamlit
64
+ st.pyplot(fig)
65
+
66
+ def class_distribution(self):
67
+ fig, ax = plt.subplots()
68
+ sns.countplot(x=self.data[self.target], ax=ax,palette="pastel")
69
+ ax.set_title("Class Distribution")
70
+ ax.set_xlabel("Class")
71
+ ax.set_ylabel("Count")
72
+ st.pyplot(fig)
73
+
74
+ def text_length_distribution(self):
75
+ fig, ax = plt.subplots()
76
+ sns.histplot(self.data['text_length'], ax=ax, kde=True)
77
+ ax.set_title("Text Length Distribution")
78
+ ax.set_xlabel("Text Length")
79
+ ax.set_ylabel("Count")
80
+ st.pyplot(fig)
81
+
82
+
83
+
84
+
85
+
86
+
87
+
NoCodeTextClassifier/Inference.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from NoCodeTextClassifier import preprocessing
2
+ from NoCodeTextClassifier import utils
3
+
4
+
5
+ def prediction(text):
6
+ TextCleaner = preprocessing.TextCleaner()
7
+ clean_text = TextCleaner.clean_text(text)
8
+
9
+ vectorize = preprocessing.Vectorization()
10
+ vectorize_text = vectorize.TfidfVectorizer(eval=True, string=clean_text)
11
+
12
+ prediction = utils.prediction("DecisionTreeClassifier.pkl",vectorize_text)
13
+
14
+ encoder = utils.load_artifacts("artifacts","encoder.pkl")
15
+ output = encoder.inverse_transform(prediction)[0]
16
+
17
+ print(f"The prediction of given text : \t{output}")
18
+
19
+
20
+
21
+
22
+
NoCodeTextClassifier/__init__.py ADDED
File without changes
NoCodeTextClassifier/__pycache__/EDA.cpython-311.pyc ADDED
Binary file (6.13 kB). View file
 
NoCodeTextClassifier/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (160 Bytes). View file
 
NoCodeTextClassifier/__pycache__/models.cpython-311.pyc ADDED
Binary file (7.77 kB). View file
 
NoCodeTextClassifier/__pycache__/preprocessing.cpython-311.pyc ADDED
Binary file (12.6 kB). View file
 
NoCodeTextClassifier/__pycache__/utils.cpython-311.pyc ADDED
Binary file (2.73 kB). View file
 
NoCodeTextClassifier/exception/__init__.py ADDED
File without changes
NoCodeTextClassifier/logger/__init__.py ADDED
File without changes
NoCodeTextClassifier/main.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from NoCodeTextClassifier.preprocessing import *
2
+ from NoCodeTextClassifier.models import *
3
+
4
+
5
+ if __name__=="__main__":
6
+ data_path = r"C:\Users\abdullah\projects\NLP_project\NoCodeTextClassifier\ML Engineer\train.csv"
7
+
8
+ process = process(data_path,'email','class')
9
+
10
+ df = process.processing()
11
+
12
+ print(df.head())
13
+
14
+ Vectorization = Vectorization(df,'clean_text')
15
+
16
+ TfidfVectorizer = Vectorization.TfidfVectorizer(max_features= 10000)
17
+ print(TfidfVectorizer.toarray())
18
+ X_train, X_test, y_train, y_test = process.split_data(TfidfVectorizer.toarray(), df['labeled_target'])
19
+
20
+ print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
21
+ # print(X_train, y_train)
22
+ models = Models(X_train=X_train,X_test = X_test, y_train = y_train, y_test = y_test)
23
+
24
+ models.DecisionTree()
NoCodeTextClassifier/models.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sklearn.neighbors import KNeighborsClassifier
2
+ from sklearn.ensemble import GradientBoostingClassifier
3
+ import xgboost as xgb
4
+ import streamlit as st
5
+ # import lightgbm as lgb
6
+ # from catboost import CatBoostClassifier
7
+
8
+ from NoCodeTextClassifier.utils import *
9
+
10
+ class Models:
11
+ def __init__(self, X_train,X_test, y_train, y_test):
12
+ self.X_train = X_train
13
+ self.y_train = y_train
14
+ self.X_test = X_test
15
+ self.y_test = y_test
16
+ os.makedirs("models",exist_ok=True)
17
+
18
+
19
+ def LogisticRegression(self, **kwargs):
20
+ from sklearn.linear_model import LogisticRegression
21
+ model = LogisticRegression(**kwargs)
22
+ model.fit(self.X_train, self.y_train)
23
+ save_path = os.path.join("models", 'LogisticRegression.pkl')
24
+ with open(save_path, 'wb') as f:
25
+ pickle.dump(model, f)
26
+ print("Training Completed")
27
+ st.markdown("**Training Completed**")
28
+
29
+ evaluation('LogisticRegression.pkl', self.X_test,self.y_test)
30
+ print("Finished")
31
+
32
+
33
+
34
+ def DecisionTree(self, **kwargs):
35
+ from sklearn.tree import DecisionTreeClassifier
36
+ model = DecisionTreeClassifier(**kwargs)
37
+ model.fit(self.X_train, self.y_train)
38
+ save_path = os.path.join("models", 'DecisionTreeClassifier.pkl')
39
+ with open(save_path, 'wb') as f:
40
+ pickle.dump(model, f)
41
+ print("Training Completed")
42
+ evaluation('DecisionTreeClassifier.pkl', self.X_test,self.y_test)
43
+ print("Finished")
44
+
45
+
46
+ def LinearSVC(self, **kwargs):
47
+ from sklearn.svm import LinearSVC
48
+ model = LinearSVC(**kwargs)
49
+ model.fit(self.X_train, self.y_train)
50
+ save_path = os.path.join("models", 'LinearSVC.pkl')
51
+ with open(save_path, 'wb') as f:
52
+ pickle.dump(model, f)
53
+
54
+ evaluation('LinearSVC.pkl', self.X_test,self.y_test)
55
+ print("Training Completed")
56
+
57
+
58
+ def SVC(self, **kwargs):
59
+ from sklearn.svm import SVC
60
+ model = SVC(**kwargs)
61
+ model.fit(self.X_train, self.y_train)
62
+ save_path = os.path.join("models", 'SVC.pkl')
63
+ with open(save_path, 'wb') as f:
64
+ pickle.dump(model, f)
65
+
66
+ evaluation('SVC.pkl', self.X_test,self.y_test)
67
+ print("Training Completed")
68
+
69
+
70
+ def RandomForestClassifier(self, **kwargs):
71
+ from sklearn.ensemble import RandomForestClassifier
72
+ model = RandomForestClassifier(**kwargs)
73
+ model.fit(self.X_train, self.y_train)
74
+ save_path = os.path.join("models", 'RandomForestClassifier.pkl')
75
+ with open(save_path, 'wb') as f:
76
+ pickle.dump(model, f)
77
+
78
+ evaluation('RandomForestClassifier.pkl', self.X_test,self.y_test)
79
+ print("Training Completed")
80
+
81
+
82
+ def MultinomialNB(self, **kwargs):
83
+ from sklearn.naive_bayes import MultinomialNB
84
+ model = MultinomialNB(**kwargs)
85
+ model.fit(self.X_train, self.y_train)
86
+ save_path = os.path.join("models", 'MultinomialNB.pkl')
87
+ with open(save_path, 'wb') as f:
88
+ pickle.dump(model, f)
89
+
90
+ evaluation('MultinomialNB.pkl', self.X_test,self.y_test)
91
+ print("Training Completed")
92
+
93
+
94
+ def GaussianNB(self, **kwargs):
95
+ from sklearn.naive_bayes import GaussianNB
96
+ model = GaussianNB(**kwargs)
97
+ model.fit(self.X_train, self.y_train)
98
+ save_path = os.path.join("models", 'GaussianNB.pkl')
99
+ with open(save_path, 'wb') as f:
100
+ pickle.dump(model, f)
101
+
102
+ evaluation('GaussianNB.pkl', self.X_test,self.y_test)
103
+ print("Training Completed")
104
+
105
+
106
+
107
+
NoCodeTextClassifier/preprocessing.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from sklearn.preprocessing import LabelEncoder
3
+ from pathlib import Path
4
+ import pickle
5
+ import re
6
+ import nltk
7
+ from nltk.corpus import stopwords
8
+ from nltk.stem import WordNetLemmatizer
9
+ import string
10
+ import os
11
+ from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
12
+ from NoCodeTextClassifier import utils
13
+ import numpy as np
14
+ import ssl
15
+
16
+ # Fix SSL certificate issues for NLTK downloads
17
+ try:
18
+ _create_unverified_https_context = ssl._create_unverified_context
19
+ except AttributeError:
20
+ pass
21
+ else:
22
+ ssl._create_default_https_context = _create_unverified_https_context
23
+
24
+ # Download NLTK data with error handling
25
+ def download_nltk_data():
26
+ try:
27
+ nltk.data.find('corpora/stopwords')
28
+ except LookupError:
29
+ nltk.download('stopwords', quiet=True)
30
+
31
+ try:
32
+ nltk.data.find('corpora/wordnet')
33
+ except LookupError:
34
+ nltk.download('wordnet', quiet=True)
35
+ nltk.download('omw-1.4', quiet=True) # Required for newer NLTK versions
36
+
37
+ # Download required NLTK data
38
+ download_nltk_data()
39
+
40
+ class TextCleaner:
41
+ '''Class for cleaning Text'''
42
+ def __init__(self, currency_symbols = r'[\$\£\€\¥\₹\¢\₽\₩\₪]', stop_words=None, lemmatizer=None):
43
+ self.currency_symbols = currency_symbols
44
+
45
+ if stop_words is None:
46
+ try:
47
+ self.stop_words = set(stopwords.words('english'))
48
+ except LookupError:
49
+ nltk.download('stopwords', quiet=True)
50
+ self.stop_words = set(stopwords.words('english'))
51
+ else:
52
+ self.stop_words = stop_words
53
+
54
+ if lemmatizer is None:
55
+ try:
56
+ self.lemmatizer = WordNetLemmatizer()
57
+ # Test the lemmatizer to ensure it works
58
+ test_word = self.lemmatizer.lemmatize('testing')
59
+ except (AttributeError, LookupError) as e:
60
+ print(f"WordNet lemmatizer initialization failed: {e}")
61
+ nltk.download('wordnet', quiet=True)
62
+ nltk.download('omw-1.4', quiet=True)
63
+ self.lemmatizer = WordNetLemmatizer()
64
+ else:
65
+ self.lemmatizer = lemmatizer
66
+
67
+ def remove_punctuation(self,text):
68
+ return text.translate(str.maketrans('', '', string.punctuation))
69
+
70
+ # Functions for cleaning text
71
+ def clean_text(self, text):
72
+ '''
73
+ Clean the text by removing punctuations, html tag, underscore,
74
+ whitespaces, numbers, stopwords.
75
+ Lemmatize the words in root format.
76
+ '''
77
+ # Handle non-string inputs
78
+ if not isinstance(text, str):
79
+ text = str(text) if text is not None else ""
80
+
81
+ if not text.strip():
82
+ return ""
83
+
84
+ try:
85
+ text = text.lower()
86
+ text = re.sub(self.currency_symbols, 'currency', text)
87
+
88
+ '''remove any kind of emojis in the text'''
89
+ emoji_pattern = re.compile("["
90
+ u"\U0001F600-\U0001F64F" # emoticons
91
+ u"\U0001F300-\U0001F5FF" # symbols & pictographs
92
+ u"\U0001F680-\U0001F6FF" # transport & map symbols
93
+ u"\U0001F1E0-\U0001F1FF" # flags (iOS)
94
+ u"\U00002702-\U000027B0"
95
+ u"\U000024C2-\U0001F251"
96
+ "]+", flags=re.UNICODE)
97
+ text = emoji_pattern.sub(r'', text)
98
+ text = self.remove_punctuation(text)
99
+ text = re.compile('<.*?>').sub('', text)
100
+ text = text.replace('_', '')
101
+ text = re.sub(r'[^\w\s]', '', text)
102
+ text = re.sub(r'\d', ' ', text)
103
+ text = re.sub(r'\s+', ' ', text).strip()
104
+ text = ' '.join(word for word in text.split() if word not in self.stop_words)
105
+
106
+ # Lemmatization with error handling
107
+ try:
108
+ text = ' '.join(self.lemmatizer.lemmatize(word) for word in text.split())
109
+ except (AttributeError, LookupError) as e:
110
+ print(f"Lemmatization failed for text: {e}")
111
+ # Continue without lemmatization
112
+ pass
113
+
114
+ return str(text)
115
+
116
+ except Exception as e:
117
+ print(f"Error cleaning text: {e}")
118
+ return str(text)
119
+
120
+
121
+ class process:
122
+ def __init__(self, data_path:str, text_feature:str,target_feature:str):
123
+ self.data_path = Path(data_path)
124
+ self.text_feature = text_feature
125
+ self.target_feature = target_feature
126
+
127
+ def _read_data(self):
128
+ df = pd.read_csv(self.data_path)
129
+ return df
130
+
131
+ def encoder_class(self, df):
132
+ encoder = LabelEncoder()
133
+ target = encoder.fit_transform(df[self.target_feature])
134
+ os.makedirs("artifacts",exist_ok=True)
135
+ save_path = os.path.join("artifacts", 'encoder.pkl')
136
+ with open(save_path, 'wb') as f:
137
+ pickle.dump(encoder, f)
138
+
139
+ return target
140
+
141
+ def clean_text(self, df):
142
+ text_cleaner = TextCleaner()
143
+ return df[self.text_feature].apply(lambda x: text_cleaner.clean_text(x))
144
+
145
+ def processing(self):
146
+ df = self._read_data()
147
+ df['labeled_target'] = self.encoder_class(df)
148
+ print("started Cleaning")
149
+ df['clean_text'] = self.clean_text(df)
150
+ return df
151
+
152
+ @staticmethod
153
+ def split_data( X, y):
154
+ from sklearn.model_selection import train_test_split
155
+ X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=42)
156
+ return X_train, X_test, y_train, y_test
157
+
158
+
159
+ class Vectorization:
160
+ def __init__(self, dataframe=np.zeros((5,5)), text_feature='text_feature'):
161
+ self.df = dataframe
162
+ self.text = text_feature
163
+
164
+ # Define the directory where you want to save the vectorizer
165
+ self.vectorizer_dir = "vectorizers"
166
+
167
+ def TfidfVectorizer(self, eval=False, string="text", **kwargs):
168
+ # Step 1: Fit the Vectorizer on the Training Data
169
+ vectorizer = TfidfVectorizer(**kwargs)
170
+ if eval==True:
171
+ tfidf_vectorizer = utils.load_artifacts("vectorizers","tfidf_vectorizer.pkl")
172
+ return tfidf_vectorizer.transform([string])
173
+
174
+ tfidf_vectorizer = vectorizer.fit_transform(self.df[self.text])
175
+ print(tfidf_vectorizer.toarray().shape)
176
+ os.makedirs(self.vectorizer_dir,exist_ok=True)
177
+ save_path = os.path.join(self.vectorizer_dir, 'tfidf_vectorizer.pkl')
178
+ with open(save_path, 'wb') as f:
179
+ pickle.dump(vectorizer, f)
180
+
181
+ return tfidf_vectorizer
182
+
183
+ def CountVectorizer(self, eval=False, string="text",**kwargs):
184
+ # Step 1: Fit the Vectorizer on the Training Data
185
+ vectorizer = CountVectorizer(**kwargs)
186
+ if eval==True:
187
+ tfidf_vectorizer = utils.load_artifacts("vectorizers","count_vectorizer.pkl")
188
+ return tfidf_vectorizer.transform([string])
189
+ count_vectorizer = vectorizer.fit_transform(self.df[self.text])
190
+ print(count_vectorizer.toarray().shape)
191
+ os.makedirs(self.vectorizer_dir,exist_ok=True)
192
+ save_path = os.path.join(self.vectorizer_dir, 'count_vectorizer.pkl')
193
+ with open(save_path, 'wb') as f:
194
+ pickle.dump(vectorizer, f)
195
+
196
+ return count_vectorizer
NoCodeTextClassifier/utils.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
2
+ import pickle
3
+ import os
4
+ import streamlit as st
5
+
6
+ def load_model(model_name):
7
+ with open(os.path.join('models',model_name), 'rb') as f:
8
+ model = pickle.load(f)
9
+ return model
10
+
11
+ def load_artifacts(folder_name, file_name):
12
+ with open(os.path.join(folder_name,file_name), 'rb') as f:
13
+ model = pickle.load(f)
14
+ return model
15
+
16
+ def prediction(model, X_test):
17
+ model = load_model(model)
18
+ y_pred = model.predict(X_test)
19
+ return y_pred
20
+
21
+
22
+ def evaluation(model, X_test, y_test):
23
+ y_pred = prediction(model, X_test)
24
+ accuracy = accuracy_score(y_test, y_pred)
25
+ class_report = classification_report(y_test, y_pred)
26
+ conf_matrix = confusion_matrix(y_test, y_pred)
27
+ model_name = model.split(".")[0]
28
+ print(f"Accuracy of {model_name}: {accuracy}\n")
29
+ print(f"Classification Report of {model_name} : \n{class_report}\n")
30
+ print(f"Confusion Matrix of {model_name} : \n{conf_matrix}")
31
+
32
+ st.markdown(f"Accuracy of **{model_name}**: **{accuracy*100}%**\n")
33
+ # st.markdown(f"\nClassification Report of **{model_name}** :\n")
34
+ # st.write(class_report)
35
+ st.markdown(f"\nConfusion Matrix of **{model_name}** : \n")
36
+ st.write(conf_matrix)
37
+
38
+
39
+