0% found this document useful (0 votes)
4 views

implemention of sms spam filtering

The document outlines the implementation of an SMS spam filter using Python and Django, detailing the code structure and libraries used, such as Pandas and Scikit-learn. It explains the workflow from data loading, text vectorization, model training with Multinomial Naive Bayes, to user input prediction. Additionally, it covers the Django app configuration and form handling for user interaction with the spam detection model.

Uploaded by

shalinigowda004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

implemention of sms spam filtering

The document outlines the implementation of an SMS spam filter using Python and Django, detailing the code structure and libraries used, such as Pandas and Scikit-learn. It explains the workflow from data loading, text vectorization, model training with Multinomial Naive Bayes, to user input prediction. Additionally, it covers the Django app configuration and form handling for user interaction with the spam detection model.

Uploaded by

shalinigowda004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

SMS spam filter 2024-25

Chapter 5

Implementation:
CODE EXPLANATION:

IMPORT LIBRARY:

CODE :

import pandas as pd from sklearn.feature_extraction.text

import CountVectorizer from sklearn.model_selection

import train_test_split from sklearn.naive_bayes import

MultinomialNB from sklearn.metrics import

accuracy_score

1. import pandas as pd

 Purpose: Imports the Pandas library, which is used for data manipulation and analysis.

 Usage: To load and handle datasets in a tabular format (e.g., CSV, Excel).

2. from sklearn.feature_extraction.text import CountVectorizer

 Purpose: Imports the CountVectorizer from Scikit-learn.

 Usage: Converts text data into a bag-of-words representation (numerical vectors). It tokenizes the

text and counts the occurrences of each word.

3. from sklearn.model_selection import train_test_split

 Purpose: Imports the train_test_split function.

 Usage: Splits the dataset into two parts:

o Training set: Used to train the model.

o Testing set: Used to evaluate the model's performance.

4. from sklearn.naive_bayes import MultinomialNB

Department of CS&BS P a g e |27


SMS spam filter 2024-25
 Purpose: Imports the Multinomial Naive Bayes classifier.

 Usage: A probabilistic learning algorithm suited for text classification tasks (e.g., spam detection).

5. from sklearn.metrics import accuracy_score

• Purpose: Imports the accuracy_score function.

• Usage: Measures the model's accuracy by comparing predicted labels with actual labels.

• Formula: Accuracy=Number of correct predictionsTotal number of predictions\text{Accuracy} =


\frac{\text{Number of correct predictions}}{\text{Total number of predictions}}

Workflow Overview:

1. Dataset Loading (not shown here):

o The text data (e.g., SMS messages) and their labels (e.g., spam or ham) are loaded into a
Pandas DataFrame.

2. Text Vectorization:

o Using CountVectorizer to transform the text data into numerical data.

3. Dataset Splitting:

o Using train_test_split to divide the dataset into training and testing sets.

4. Model Initialization:

o Initializing the Multinomial Naive Bayes classifier.

5. Model Training:

o Fitting the model using the training data.

6. Prediction:

o Making predictions on the test data.

7. Model Evaluation:

o Calculating the model's accuracy using accuracy_score.

Accuracy_score?

Department of CS&BS P a g e |28


SMS spam filter 2024-25
Purpose: To evaluate how well the model performs in terms of correctly predicting the labels.

Interpretation: A high accuracy score means the model is predicting labels correctly for most cases.

A low accuracy score indicates the model needs improvement (e.g., more data, better preprocessing, or a
different algorithm).

Step -2: dataset=pd.read.csv(‘/emails.csv’) dataset :

Assigns the loaded data to the variable dataset.

Dataset: A Pandas DataFrame object, which is a two-dimensional tabular structure with rows and
columns. The DataFrame allows easy manipulation, analysis, and visualization of data.

CSV : Specifies the path to the CSV file

CSV file: A text file where each line represents a row, and each column value is separated by a comma.
Commonly used to store tabular data such as datasets for analysis.

Step:3: CODE: dataset.head() The

dataset.head() Do:

urpose: It shows the first 5 rows of the DataFrame by default. This is helpful for: Verifying that the dataset
is loaded correctly. Understanding the structure of the data.

Output:
text spam

0 Subject: naturally irresistible your corporate... 1

1 Subject: the stock trading gunslinger fanny i... 1

2 Subject: unbelievable new homes made easy im ... 1

3 Subject: 4 color printing special request add... 1

4 Subject: do not have money , get software cds ... 1

Step-4: CODE: vectorizer=CountVectorizer()

Department of CS&BS P a g e |29


SMS spam filter 2024-25
X=vectorizer.fit_transform(dataset['text'])

X_train, X_test, y_train, y_test=train_test_split(X, dataset['spam'],test_size=0.2)

model=MultinomialNB() model.fit(X_train,y_train)

Code Explanation

1. vectorizer = CountVectorizer()

 Initializes the CountVectorizer from Scikit-learn.

 Converts text data into a Bag-of-Words (BoW) representation:

o Each text is tokenized (split into individual words). o A sparse matrix is created

where each row represents a document, and each column represents a unique word in

the dataset.

o The values in the matrix indicate the frequency of the word in the document.

X = vectorizer.fit_transform(dataset['text'])

 dataset['text']: The column containing SMS messages or email text.

 fit_transform():

o fit: Learns the vocabulary from the text data


(unique words).

o transform: Converts the text data into a sparse


matrix of word counts.

 Result: X is a sparse matrix representing the numerical form of the text data.

X_train, X_test, y_train, y_test = train_test_split(X, dataset['spam'], test_size=0.2)

 X: Input features (word count vectors).

 dataset['spam']: Target labels (e.g., 1 for spam, 0 for ham).

 test_size=0.2: Reserves 20% of the data for testing and 80% for training.

 Outputs:

Department of CS&BS P a g e |30


SMS spam filter 2024-25
o X_train: Features for training. o X_test:

Features for testing. o y_train: Labels for

training. o y_test: Labels for testing.

model = MultinomialNB()

 Initializes the Multinomial Naive Bayes classifier.

 This algorithm is suited for text classification problems, especially with discrete data (e.g., word
frequencies).

model.fit(X_train, y_train)

 Purpose: Trains the Naive Bayes model on the training data.

 Inputs:

o X_train: Word count matrix for training data.

o y_train: Corresponding labels for training

data.

 Result: The model learns the relationship between word occurrences and labels (spam/ham). Step-5:

yPred=model.predict(X_test) accuracy=accuracy_score(y_test,yPred) print(accuracy) output:

0.9886561954624782 Code Explanation yPred = model.predict(X_test)

Purpose: Makes predictions on the test data.

Inputs: X_test: Word count matrix for test data.

Output: yPred contains the predicted labels for the test set.

accuracy = accuracy_score(y_test, yPred)

• Purpose: Calculates the accuracy of the model.

• Formula: Accuracy=Number of Correct PredictionsTotal Predictions\text{Accuracy} =


\frac{\text{Number of Correct Predictions}}{\text{Total
Predictions}}Accuracy=Total PredictionsNumber of Correct Predictions

Department of CS&BS P a g e |31


SMS spam filter 2024-25
• Inputs:

o y_test: Actual labels of the test data. o

yPred: Predicted labels of the test data.

• Output: The calculated accuracy (0.9886561954624782 means 98.87% accuracy).

print(accuracy)

• Displays the accuracy of the model on the test set.

Text Preprocessing:

• Convert text into numerical data using CountVectorizer.

Data Splitting:

• Split the dataset into training and testing sets.

Model Training:

• Train the Naive Bayes classifier using the training data.

Prediction:

• Predict labels for the test set.

Evaluation:

• Calculate and display the accuracy of the model.

Step 6: Sms spam filter code:

def pridictMessage(message):
messageVector=vectorizer.transform([message])
prediction=model.predict(messageVector) return
'Spam' if prediction[0] == 1 else 'Ham

#Get user input to predict

UserMessage=input('Enter Text to Predict Ham and Spam message: ')


prediction = pridictMessage(UserMessage) print(f'the messgage is:
{prediction}')

Department of CS&BS P a g e |32


SMS spam filter 2024-25

OUTPUT:
Enter Text to Predict Ham and Spam message: hii how are you the
messgage is: Ham
Enter Text to Predict Ham and Spam message: Congratulations! You've won a free vacation.

the message is: Spam Code

Explanation:

Purpose: Defines a function predict Message that takes a single input parameter, message (the text to
classify as spam or ham).

vectorizer.transform([message]): Converts the input message (text) into a numerical vector representation
using the pre-trained CountVectorizer.

This ensures the input format matches what the model was trained on. model.predict(messageVector):

Uses the trained Naive Bayes model to predict the label (1 for spam, 0 for ham) of the input vector.

model.predict(messageVector): Uses the trained Naive Bayes model to predict the label (1 for spam, 0 for

ham) of the input vector. model.predict(messageVector): Uses the trained Naive Bayes model to predict

the label (1 for spam, 0 for ham) of the input vector.

Return the Result: Return 'Spam' if prediction[0] == 1 else 'Ham'

 Logic: If the model's prediction (prediction[0]) is 1, the message is classified as "Spam". Otherwise,
it is classified as "Ham" (not spam).
 Prompts the user to enter a text message for classification.

pridictMessage(UserMessage):Calls the function with the user-entered message.

 Prints: Outputs whether the message is classified as "Spam" or "Ham".

Processing:

1. Convert the text to a vector.

2. Predict the label using the model.

3. Return and display the result.

Department of CS&BS P a g e |33


SMS spam filter 2024-25
the configuration class for a Django application named detector. Let’s break it down:

Apps.py file

Code :

from django.apps import AppConfig class

DetectorConfig(AppConfig):

default_auto_field = 'django.db.models.BigAutoField'

name = 'detector'

Code Explanation

1. AppConfig Class: AppConfig is a base class provided by Django for configuring an application.

Each app in a Django project can have its own configuration class, which is registered in the project's
INSTALLED_APPS list in the settings.py file.

2. Attributes of DetectorConfig

a. default_auto_field: default_auto_field = 'django.db.models.BigAutoField': This sets the default


field type for automatically generated primary keys in the app's models.BigAutoField is a 64-bit integer
field, which can handle large values compared to the older AutoField (32-bit integer). This is useful for
scalability as it ensures models can handle a large number of records without primary key conflicts.

b. name: name = 'detector': This specifies the name of the application.The name must match the app’s
folder name, making it easy for Django to locate and recognize the app.

3. Purpose of DetectorConfig: This configuration class allows you to:

Define metadata for the app (name, default settings, etc.).

Perform app-specific initialization tasks (e.g., importing signals or configuring settings) by overriding the
ready() method of AppConfig.

4.Usage: In settings.py, the app is referenced like this:

INSTALLED_APPS = [

...

Department of CS&BS P a g e |34


SMS spam filter 2024-25
'detector',

Django uses the DetectorConfig class to initialize and configure the detector app during the project setup.

Forms.py:

Code: from django import forms class

MessageForm(forms.Form):

text = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Enter


your message here...'}))

CODE EXPLANATION:

A Django form class named messageform, which is used to handle user input in a structured way. Here's a
detailed explanation:

1. forms.Form: The forms.Form class is part of Django's forms framework. It is used to define and
manage HTML forms in a clean, Pythonic way.Forms handle input validation and rendering, making it easy
to work with user input.

2. The MessageForm Class: MessageForm inherits from forms.Form, meaning it is a custom form
that can include various fields, validation rules, and attributes.

3. The text Field forms.CharField: Defines a single-line text field. In this case, the text field is
intended to accept the user's message.

Widget Customization: widget=forms.Textarea:

 Customizes the default input widget for CharField to a multi-line text area (<textarea> element in
HTML).

 This makes it more suitable for entering longer messages.

attrs Parameter: The attrs dictionary allows you to pass HTML attributes to the rendered widget. These

enhance the user experience and appearance: class: 'form-control': Adds the CSS class form-control

to the <textarea>.This is often used with frameworks like Bootstrap to style form elements.

placeholder: 'Enter your message here...': Adds a placeholder text to guide the user on what to input.

Department of CS&BS P a g e |35


SMS spam filter 2024-25
It Works: When this form is used in a Django view, it:

1. Renders an HTML form with a multi-line text area for the text input.

2. <textarea class="form-control" placeholder="Enter your message here..."></textarea>

3. Validates the user input automatically based on the field type (e.g., ensuring it is a string and not
empty by default).

4. Provides Data to the backend when the form is submitted, making it easy to access the text value in
your views.

Views.py file

5. from django.shortcuts import render


6.
7. # Create your views here.

Department of CS&BS P a g e |36


SMS spam filter 2024-25
8. import pandas as pd # to handle our dataset
9.
10. from sklearn.feature_extraction.text import CountVectorizer #for converting text data into nume
11.
12. from sklearn.model_selection import train_test_split #to split data
13.
14. from sklearn.naive_bayes import MultinomialNB
15.
16. from sklearn.metrics import accuracy_score
17.
18. from .forms import MessageForm
19.
20. dataset = pd.read_csv('C:/Users/shali/Desktop/spam detector/spamDetection/emails.csv')
21.
22. vectorizer = CountVectorizer()
23. X = vectorizer.fit_transform(dataset['text'])
24.
25. X_train, X_test, y_train, y_test = train_test_split(X, dataset['spam'], test_size=0.2, random_state=42)
26.
27. model = MultinomialNB()
28. model.fit(X_train, y_train)
29.
30. def predictMessage(message):
31. message_vector = vectorizer.transform([message])
32. prediction = model.predict(message_vector) 33. return 'Spam' if prediction[0] == 1 else 'Ham'
34.
35. def Home(request):
36. result = None
37. if request.method == 'POST':
38. form = MessageForm(request.POST)
39. if form.is_valid():
40. message = form.cleaned_data['text']
41. result = predictMessage(message)
42.

Department of CS&BS P a g e |37


SMS spam filter 2024-25
43. else:
44. form = MessageForm()
45.
46. return render(request, 'home.html', {'form': form, 'result': result})
47.
Code Explanation

The provided Django code is a backend implementation of a simple SMS Spam Detector using machine
learning. Below is a step-by-step breakdown of the code:

Imports

1. Django Imports : render: Used to render templates (HTML files) and pass context variables to
them.

2. Pandas (pd) : Used to handle the dataset (emails.csv) for preprocessing and analysis.

3. Scikit-learn Modules : CountVectorizer: Converts text data into numerical feature vectors using a
bag-of-words model.train_test_split: Splits the dataset into training and testing sets.MultinomialNB:
A Naive Bayes algorithm suitable for text classification. accuracy_score: Evaluates the accuracy of
the trained model.

4. Custom Imports .forms.MessageForm: A Django form to accept user input for message
classification.

Dataset Loading and Preprocessing dataset = pd.read_csv('C:/Users/shali/Desktop/spam

detector/spamDetection/emails.csv') .The emails.csv file is loaded into a Pandas DataFrame. It is

assumed to contain: text: The SMS text. spam: A binary column indicating whether the message is spam

(1) or not (0). vectorizer = CountVectorizer()

X = vectorizer.fit_transform(dataset['text'])

• CountVectorizer transforms the text data into numerical vectors based on word frequency.

• X contains the feature matrix.

Dataset Splitting

X_train, X_test, y_train, y_test = train_test_split(X, dataset['spam'], test_size=0.2, random_state=42)

Department of CS&BS P a g e |38


SMS spam filter 2024-25
The dataset is split into:

X_train and X_test: Training and testing feature sets.

y_train and y_test: Labels for training and testing.

test_size=0.2: Reserves 20% of the data for testing.

random_state=42: Ensures reproducibility. Model

Training model = MultinomialNB()

model.fit(X_train, y_train)

• A Naive Bayes model is initialized and trained on the training dataset. Message Prediction

def predictMessage(message): message_vector = vectorizer.transform([message]) prediction =

model.predict(message_vector) return 'Spam' if prediction[0] == 1 else 'Ham'

• Input: A single message (string).

• Process: Converts the input message into a numerical vector using vectorizer.transform.
Predicts whether the message is spam (1) or ham (0) using the trained model.

• Output: 'Spam' or 'Ham'. Django View def Home(request): result = None if

request.method == 'POST':

form = MessageForm(request.POST)

if form.is_valid():

message = form.cleaned_data['text']

result = predictMessage(message)

else:

form = MessageForm()

return render(request, 'home.html', {'form': form, 'result': result})

1. Method Handling:

o If the HTTP request method is POST:

Department of CS&BS P a g e |39


SMS spam filter 2024-25
 Retrieve the submitted form data (MessageForm).

 Validate the form.

 Predict the message type using predictMessage.

o If the request method is GET, display an empty form.

2. Template Rendering:

o home.html is rendered with:

 form: The MessageForm object.

 result: The prediction result (Spam or Ham).

• The code implements a basic machine-learning-backed SMS spam detection system.

• The trained Naive Bayes model predicts whether a user-submitted message is spam or ham.

• The Django view (Home) handles both displaying the form and showing prediction results.

• home.html is the frontend template for user interaction.

Urls.py
• """
• URL configuration for spam_detection project.

• The `urlpatterns` list routes URLs to views. For more information please see:
• https://docs.djangoproject.com/en/5.0/topics/http/urls/
• Examples:
• Function views
• 1. Add an import: from my_app import views
• 2. Add a URL to urlpatterns: path('', views.home, name='home')
• Class-based views
• 1. Add an import: from other_app.views import Home
• 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')

• Including another URLconf

Department of CS&BS P a g e |40


SMS spam filter 2024-25

• 1. Import the include() function: from django.urls import include, path

• 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))

• """

• from django.contrib import admin

• from django.urls import path, include

• urlpatterns = [
• path('admin/', admin.site.urls),

• path('', include('detector.urls'))

• ]

Code Explanation:

Django URL Configuration

The provided code configures the URL routing for a Django project named spam_detection. It defines how
requests to various URLs are handled by linking them to specific views or apps. Here's a detailed breakdown:

File Purpose: This file (usually named urls.py in a Django project) acts as the central routing configuration
for the project. It maps URLs to their corresponding views or other URL configurations.

Imports: from django.contrib import admin and from django.urls import path, include

1. admin: Provides access to Django's built-in admin interface for managing the project's data and
models.

2. path: A function for defining URL patterns.

3. include: Used to include other URL configurations from different apps or modules.

urlpatterns urlpatterns = [

path('admin/', admin.site.urls),

path('', include('detector.urls'))

This is a list of all the URL patterns (routes) for the project.

Department of CS(Business System) P a g e |41


SMS spam filter 2024-25
1. path('admin/', admin.site.urls)

• Maps the /admin/ URL to the Django admin site.

• When users navigate to /admin/, they are directed to the admin interface where they can manage
models and data.

• Example: http://127.0.0.1:8000/admin/

2. path('', include('detector.urls'))

• Maps the root URL (/) to the URL configuration of the detector app.

include('detector.urls'):

o Refers to another urls.py file located inside the detector app.

o This allows modular URL configuration, where each app has its own URL patterns.

Example: If the detector.urls file

contains: from django.urls import path

from . import views urlpatterns = [

path('', views.Home, name='home'),

Then the root URL (http://127.0.0.1:8000/) will route to the Home view.

It Works: Django processes incoming requests by matching the requested URL against the patterns in
urlpatterns.

If a match is found, it forwards the request to the appropriate view or app-specific URL configuration.

If no match is found, Django raises a 404 Not Found error.

Advantages of This Approach

1. Modular Design:

o Apps can have their own urls.py files, keeping the project structure organized.

o Example: The detector app handles its own routes.

Department of CS(Business System) P a g e |42


SMS spam filter 2024-25
2. Reusability:

o include() allows reusing URL patterns across multiple projects or apps.

3. Scalability:

o As the project grows, you can add more apps and their URL configurations without cluttering
the main urls.py.

Code Explanation: Django App URL Configuration

The provided code defines the URL configuration for a specific Django app. It maps URLs to
corresponding views within the app, enabling Django to serve appropriate responses based on the requested
URL.

File Purpose

This file (usually named urls.py in the app directory) contains the URL patterns for the app. It ensures that
requests to certain URLs are routed to specific functions or class-based views defined in the app's views.py
file.

Imports from django.urls

import path from . import

views

1. path: A Django function used to define URL patterns.

2. views:

o Imports the views.py file from the current app (. represents the current directory).

o Views contain the logic that handles requests and returns responses.

urlpatterns urlpatterns = [ path('',

views.Home, name='home')

1. path('', views.Home, name='home')

• Maps the root URL ('') of the app to the Home view in views.py.

Department of CS(Business System) P a g e |43


SMS spam filter 2024-25
Components of path(): '':

o Represents the root URL for the app.

o If this app is included in the project at the root level (e.g., path('', include('detector.urls')) in
the project urls.py), this URL would match http://127.0.0.1:8000/.

2. views.Home:

o Refers to the Home function (or class-based view) in the app's views.py file.

o This function will be executed when a user accesses the root URL.

3. name='home': Provides a unique name for this URL pattern. Allows reverse URL resolution (e.g.,
using reverse('home') or {% url 'home' %} in templates to generate the URL dynamically).Helps
avoid hardcoding URLs in multiple places.

Works : When a request is made to the root URL of this app (e.g., /), Django matches the URL against the
urlpatterns list. If the URL matches '', Django calls the Home view from views.py.The Home view handles
the request and generates a response (e.g., rendering an HTML template).

Example of views.Home

In the app's views.py:

from django.shortcuts import render def

Home(request):

return render(request, 'home.html')

• Input: The request object.

• Output: Renders and returns the home.html template.

• Maps the root URL of the app to the Home view.

• Provides a unique name (home) for reverse URL resolution.

• Allows the app to handle its specific routes independently while integrating into the overall project.

Urls.py file : from django.urls import path

Department of CS(Business System) P a g e |44


SMS spam filter 2024-25
from . import views urlpatterns

= [ path('',

views.Home,name='home')

Code Explanation: Django App URL Configuration

The provided code defines the URL configuration for a specific Django app. It maps URLs to
corresponding views within the app, enabling Django to serve appropriate responses based on the
requested URL.

File Purpose

This file (usually named urls.py in the app directory) contains the URL patterns for the app. It

ensures that requests to certain URLs are routed to specific functions or class-based views defined

in the app's views.py file. Imports from django.urls import path from . import views

1. path: A Django function used to define URL patterns.


2. views: o Imports the views.py file from the current app (. represents the current
directory). o Views contain the logic that handles requests and returns responses.

urlpatterns

urlpatterns = [ path('',

views.Home, name='home')

1. path('', views.Home, name='home')

• Maps the root URL ('') of the app to the Home view in views.py.

Components of path():

1. '':
o Represents the root URL for the app.

Department of CS(Business System) P a g e |45


SMS spam filter 2024-25
o If this app is included in the project at the root level (e.g., path('', include('detector.urls')) in
the project urls.py), this URL would match http://127.0.0.1:8000/.
2. views.Home: o Refers to the Home function (or class-based view) in the app's views.py file.
o This function will be executed when a user accesses the root URL.
3. name='home':
o Provides a unique name for this URL pattern. o Allows reverse URL resolution (e.g.,
using reverse('home') or {% url 'home' %} in templates to generate the URL dynamically).
o Helps avoid hardcoding URLs in multiple places.

Works: When a request is made to the root URL of this app (e.g., /), Django matches the URL against the
urlpatterns list. If the URL matches '', Django calls the Home view from views.py.The Home view handles
the request and generates a response (e.g., rendering an HTML template).

Example of views.Home: In the app's views.py:

from django.shortcuts import render def

Home(request):

return render(request, 'home.html') Input:

The request object.

Output: Renders and returns the home.html template.

 Maps the root URL of the app to the Home view.


 Provides a unique name (home) for reverse URL resolution.
 Allows the app to handle its specific routes independently while integrating into the overall
project.

HTML CODE :

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

Department of CS(Business System) P a g e |46


SMS spam filter 2024-25
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Spam Detection</title>

<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap"
rel="stylesheet">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">

</head> <style> body { font-family: 'Roboto', sans-

serif; background: linear-gradient(to right, #6a11cb,

#2575fc); color: #333; margin: 0; padding: 0;

display: flex; justify-content: center; align-items:

center; height: 100vh;

.container { width: 90%; max-

width: 500px; padding: 30px;

background: #fff; border-radius: 15px;

box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);

text-align: center;

h1 { font-size: 2em;

margin-bottom: 10px;

color: #6a11cb;

} p{ font-size:

1.1em; margin-

bottom: 20px;

Department of CS(Business System) P a g e |47


SMS spam filter 2024-25
} form { display:

flex; flex-direction:

column; align-items:

center;

.form-control {

width: 100%; padding:

15px; margin-bottom:

20px; border: 1px solid

#ddd; border-radius:

8px; font-size: 1em;

.btn { padding: 15px 30px;

background-color: #6a11cb;

color: white; border: none;

border-radius: 8px; font-size:

1.1em; cursor: pointer;

transition: background-color

0.3s;

.btn:hover { background-

color: #2575fc;

Department of CS(Business System) P a g e |48


SMS spam filter 2024-25
.result { margin-

top: 20px;

padding: 20px;

border-radius: 8px;

font-size: 1.2em;

font-weight: bold;

.result.spam { background-

color: #ffdddd; color:

#d8000c;

.result.ham { background-

color: #ddffdd; color:

#4f8a10;

@media (max-width: 600px) {

h1 { font-size:

1.5em;

} p{

font-size: 1em;

.btn { padding:

10px 20px; font-

size: 1em;

Department of CS(Business System) P a g e |49


SMS spam filter 2024-25
}

.result { font-

size: 1em;

</style>

</style>

<body>

<div class="container">

<h1><i class="fas fa-shield-alt"></i> Spam Detection</h1>

<p>Enter your message below to check if it is spam or not.</p>

<form method="post">

{% csrf_token %}

{{form.as_p}}

<button type="submit" class="btn"><i class="fas fa-check"></i> Check</button>

</form>

{% if result %}

<div class="result {{ result|lower }}">

<h2>The message is: {{result}}</h2>

</div>

{% endif %}

</div>

</body>

</html>

Department of CS(Business System) P a g e |50


SMS spam filter 2024-25
OUTPUT:

CODE EXPLANATION

Html Code Explanation : This HTML template creates a visually appealing, responsive, and user-friendly
interface for a Spam Detection application. Here's the explanation of the code:

1. HTML Structure

HTML <head>

• Metadata and External Resources:

o The meta tags ensure proper character encoding and mobile responsiveness. o Google

Fonts (Roboto) is used for clean typography.

o Font Awesome icons are included for visual enhancements (e.g., the shield and check
icons).

• Title:

o The <title> sets the webpage's title as "Spam Detection."

HTML <body>

Department of CS(Business System) P a g e |51


SMS spam filter 2024-25
Container: A centered div with a class container wraps all content. It includes a heading, description, a form
for input, and a section for displaying results.

Form: The form is built to accept a message input from the user and process it.{{form.as_p}}: A Django
template tag to render form fields in <p> tags. {% csrf_token %}: Adds a CSRF token for security (required
in Django forms). The submit button uses a Font Awesome icon and CSS styling.

Result Display: If there is a result ({% if result %}), it dynamically displays a message styled differently
based on whether it's "Spam" or "Ham."

2. CSS Styles

Body Styling: Font and Background: Uses the "Roboto" font. The background is a gradient transitioning
from purple to blue for a modern feel.

Layout: The page is flex-centered to vertically and horizontally align the content within the viewport.

Card Design: White background with rounded corners and a shadow for a card-like effect. A max width of
500px ensures responsiveness.

Text: Headings and paragraph text are styled to enhance readability and highlight key information: Heading
(h1) ses a gradient color tone to reflect branding.Paragraph text is slightly larger and spaced.

Form : Input Fields (.form-control): Styled with padding, rounded corners, and light borders.

Button (.btn): Purple background with white text, changing to blue on hover for interactivity.

Result Box: The result class styles are conditionally applied:

Spam Messages (.result.spam): Red background and text to indicate a warning.

Ham Messages (.result.ham): Green background and text to show it's safe.

Responsive Design: Media queries adjust font sizes and button padding for smaller devices.

3. Dynamic Functionality: Django template tags integrate backend logic into the frontend: {% csrf_token
%}: Prevents CSRF attacks during form submission.{{form.as_p}}: Dynamically renders the form fields
defined in the Django backend.{{result|lower}}: Converts the result to lowercase for conditional
styling.{{result}}: Displays the classification result.

4. Features

1. User-Friendly Design: Clear, intuitive interface with a modern layout.

Department of CS(Business System) P a g e |52


SMS spam filter 2024-25
2. Dynamic Result Display: Visually distinct feedback for spam vs. ham messages.

3. Responsive: Adjusts seamlessly for various screen sizes.

4. Backend Integration: Supports Django form handling and result display.

Final Output

Department of CS(Business System) P a g e |53

You might also like