Flask App 500 Internal Server Error for chrome extension tool

42 Views Asked by At

Im new to flask and im trying to create a chrome extension tool for a phishing email detection system. I imagine the system works by clicking a Extract Button which will extract the sender, subject and email body text and a scan button which will analyze the extracted body text of the email to determine is it a phishing email.

I can extract the information of the email but when I click the analyze button it display 500 Internal Server Error in the console. Tried research some way to solve this but still can't.

backend.py

import traceback
from flask import Flask, request, jsonify
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from flask_cors import CORS
import json
import logging
from http import HTTPStatus


app = Flask(__name__)


# Load the dataset
dataset = pd.read_csv("mail_data.csv")

# replace null value with null string
mail_data = dataset.where((pd.notnull(dataset)), '')

# label spam mail as 0; authentic as 1
mail_data.loc[mail_data['Category'] == 'spam', 'Category',] = 0
mail_data.loc[mail_data['Category'] == 'authentic', 'Category',] = 1

# Assuming your dataset has a 'text' column containing the email content and a 'label' column for phishing or not
X = mail_data['Message']
Y = mail_data['Category']

# Feature Extraction
feature_extraction = TfidfVectorizer(min_df=1, stop_words='english', lowercase=True)
X_features = feature_extraction.fit_transform(X)

# Convert Y values as integers
Y = Y.astype('int')

# Train the model
model = LogisticRegression()
model.fit(X_features, Y)


@app.route('/', methods=['GET', 'POST'])
def predict_phishing():
    if request.method == 'POST':
        email_content = request.json.get('email_content', '')
        # Feature extraction for the input data

        email_content_feature = feature_extraction.transform([email_content])
        # Make prediction using the trained model
        prediction = model.predict(email_content_feature)[0]

        

        return jsonify({'prediction': prediction})
    # If the request method is GET, return a message
    else:
        return jsonify({'message': 'Please use POST method to make predictions.'})
    

   
if __name__ == '__main__':
    app.run(debug=True)
    
    
 

popup.js

// Variable to store email subject, sender, and message
let emailSubjectSenderMessage = {};

// Function to send a message to content.js to extract email content
function extractEmailContent() {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs && tabs.length > 0 && tabs[0].id) {
      const activeTab = tabs[0];
      chrome.tabs.sendMessage(activeTab.id, { action: 'extractEmailContent' }, (response) => {
        if (chrome.runtime.lastError) {
          // Handle any errors in sending the message

        } else {
          // Check if the response contains emailContent
          if (response && response.emailContent) {
            // Extracted email content
            const emailContent = response.emailContent;

            // Extracted sender's email address
            const senderEmail = emailContent.senderEmail;

            // Store the email subject, sender, and message in the variable
            emailSubjectSenderMessage = {
              subject: emailContent.subject,
              sender: senderEmail,
              message: emailContent.body
            };

            // Display the extracted content including the sender's email address
            displayEmailContent(emailContent, senderEmail);
          } else {
            displayErrorMessage('No email data found on this page.');
          }
        }
      });
    } else {
      console.error('Invalid tab or tab ID not available.');
    }
  });
}


// Function to display the extracted email content
function displayEmailContent(emailContent, senderEmail) {
  const emailContentDiv = document.getElementById('emailContent');
  emailContentDiv.innerHTML = `<strong>Sender:</strong> ${senderEmail}<br><strong>Subject:</strong> ${emailContent.subject}<br><strong>Message:</strong> ${emailContent.body}`;
}

// Function to display an error message
function displayErrorMessage(message) {
  const emailContentDiv = document.getElementById('emailContent');
  emailContentDiv.textContent = message;
}




// Add a click event listener to the extract button
document.getElementById('extractButton').addEventListener('click', extractEmailContent);

// Add a click event listener to the scan button
document.getElementById('scanButton').addEventListener('click', scanEmailContent);


// Function to send the extracted email content to the Flask server for prediction
function scanEmailContent() {
  // Check if email content is available
  if (Object.keys(emailSubjectSenderMessage).length === 0) {
    displayErrorMessage('Please extract email content first.');
    return;
  }

  // Extracted email content
  const emailContent = emailSubjectSenderMessage.message;

  // Make an HTTP POST request to Flask server for prediction
  fetch('http://127.0.0.1:5000', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email_content: emailContent,
    }),
  })
    .then(response => response.json())
    .then(data => {
      // Handle the prediction result
      const prediction = data.prediction;

      // Display the prediction result
      displayPredictionResult(prediction);
    })
    .catch(error => {
      console.error('Error in predicting phishing:', error);
      console.log('Response Content:');
      displayErrorMessage('Error in predicting phishing. Please try again.');
    });
}


// Function to display the prediction result
function displayPredictionResult(prediction) {
  const emailContentDiv = document.getElementById('emailContent');
  let resultMessage;

  if (prediction === 0) {
    resultMessage = 'This email is predicted as a phishing email.';
  } else {
    resultMessage = 'This email is predicted as authentic.';
  }

  emailContentDiv.textContent = resultMessage;
}

I have tried to just used 'POST"

@app.route('/', methods=[ 'POST'])

But i just end up with error 405

1

There are 1 best solutions below

0
Aswindanu Anwar On

No need to do jsonify(). This should work

@app.route('/', methods=['GET', 'POST'])
def predict_phishing():
    if request.method == 'POST':
        email_content = request.json.get('email_content', '')
        # Feature extraction for the input data

        email_content_feature = feature_extraction.transform([email_content])
        # Make prediction using the trained model
        prediction = model.predict(email_content_feature)[0]

        

        return {'prediction': prediction}, 200
    # If the request method is GET, return a message
    else:
        return {'message': 'Please use POST method to make predictions.'}, 400