#pr6

import pandas as pd  # Needed for reading dataset

data = pd.read_csv("SMSSpamCollection", sep='\t', names=["label", "message"])
data['label_num'] = data['label'].map({'ham': 0, 'spam': 1})

print("Dataset loaded successfully!")

print(data.head())

data.shape


import re  # For text cleaning (regex)
import nltk  # For tokenization, stopwords, stemming
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize

nltk.download('punkt')
nltk.download('punkt_tab')
nltk.download('stopwords')

stop_words = stopwords.words('english')  
stemmer = PorterStemmer()  
def clean_text_simple(text):
    text = text.lower()  # lowercase
    text = re.sub(r"http\S+|www\S+", "", text)  
    text = re.sub(r"[^a-z\s]", "", text)  
    words = word_tokenize(text) 
    words = [stemmer.stem(w) for w in words if w not in stop_words]  
    return " ".join(words)

data["clean_msg"] = data["message"].apply(clean_text_simple)

print(data[["message", "clean_msg"]].head())


from sklearn.model_selection import train_test_split

X = data["clean_msg"]
y = data["label_num"]

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)



from sklearn.feature_extraction.text import TfidfVectorizer

tfidf = TfidfVectorizer(max_features=3000) 
X_train_tfidf = tfidf.fit_transform(X_train)  
X_test_tfidf = tfidf.transform(X_test)


from sklearn.naive_bayes import MultinomialNB

nb = MultinomialNB()
nb.fit(X_train_tfidf, y_train)
y_pred = nb.predict(X_test_tfidf)


from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report

print("Accuracy:", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(y_test, y_pred))
print("Recall:", recall_score(y_test, y_pred))
print("F1 Score:", f1_score(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred, target_names=["HAM","SPAM"]))