I’m building a simple text summarizer using HTML , CSS and Flask. It is a simple web application that I’m trying to build, it should give summary when .txt file is uploaded but I’m getting internal server error in flask and in index.html (when I hit summarize button ) I’m getting summary not fetched error.
Am I missing something? Can anybody solve this error?
–This is index.html code–
document.getElementById('upload-form').addEventListener('submit', function (event) {
event.preventDefault();
const fileInput = document.getElementById('file-input');
const file = fileInput.files[0];
if (!file) {
alert('Please select a .txt file.');
return;
}
const formData = new FormData();
formData.append('file', file);
fetch('http://127.0.0.1:5000/render', { // Corrected the fetch URL here
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// Display the summarized content on the page
const summaryContainer = document.getElementById('summary-container');
summaryContainer.innerHTML = '<h3>Summary:</h3><p>' + data + '</p>';
for (const sentence of data) {
const paragraph = document.createElement('p');
paragraph.textContent = sentence;
summaryContainer.appendChild(paragraph);
}
})
.catch(error => {
console.error('Error fetching the summary:', error);
alert('An error occurred while fetching the summary. Please try again.');
});
});
@font-face {
font-family: 'DragonInktrap';
src: url(fonts/Dragon-Inktrap-BF64b9feda79567.ttf);
}
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
margin: 0;
padding: 0;
background: rgb(2,0,36);
background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(7,56,41,1) 35%, rgba(7,119,161,1) 100%);
}
.container {
max-width: 200px;
margin: 30px auto;
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1{
text-align: center;
color: whitesmoke;
font-family: 'DragonInktrap';
font-size: 150px;
}
/* textarea {
width: 60%;
height: 150px;
resize: vertical;
border: 1px solid #ccc;
padding: 10px;
} */
button {
background-color:#097956;
color: #fff;
border: none;
padding: 10px 30px;
margin-top: 10px;
cursor: pointer;
border-radius: 5px;
font-size: 20px;
}
.summary {
background: rgb(2,0,36);
background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(7,56,41,1) 35%, rgba(7,119,161,1) 100%);
border: 1px solid #ccc;
padding: 50px;
margin-top: 20px;
border-radius: 5px;
font-size: 20px;
}
.form{
text-align: center;
color: #f5f5f5;
font-size: 30px;
font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
padding-bottom: 60%;
}
<!DOCTYPE html>
<html>
<head>
<title>Text Summarizer</title>
</head>
<body>
<h1>TEXT SUMMARIZER</h1>
<div class="form">
<form id="upload-form">
<label for="file-input">Choose a .txt file:</label>
<input type="file" id="file-input" accept=".txt" required>
<button type="submit">Summarize</button>
<div class="summary" id="summary-container">
</div>
</form>
</div>
<!-- <div id="summary-container"> -->
<!-- Summarized content will be displayed here -->
<!-- </div> -->
</body>
–This is flask code–
import nltk
from nltk.corpus import stopwords
from nltk.cluster.util import cosine_distance
import numpy as np
import networkx as nx
from flask import Flask, request, jsonify,render_template
import json
from flask_cors import CORS
app = Flask(__name__)
def read_article(file_name):
file = open(file_name, "r")
filedata = file.readlines()
article = filedata[0].split(". ")
sentences = []
for sentence in article:
print(sentence)
sentences.append(sentence.replace("[^a-zA-Z]", " ").split(" "))
#sentences.pop()
return sentences
def sentence_similarity(sent1, sent2, stopwords=None):
if stopwords is None:
stopwords = []
sent1 = [w.lower() for w in sent1]
sent2 = [w.lower() for w in sent2]
all_words = list(set(sent1 + sent2))
vector1 = [0] * len(all_words)
vector2 = [0] * len(all_words)
# build the vector for the first sentence
for w in sent1:
if w in stopwords:
continue
vector1[all_words.index(w)] += 1
# build the vector for the second sentence
for w in sent2:
if w in stopwords:
continue
vector2[all_words.index(w)] += 1
return 1 - cosine_distance(vector1, vector2)
def build_similarity_matrix(sentences, stop_words):
# Create an empty similarity matrix
similarity_matrix = np.zeros((len(sentences), len(sentences)))
for idx1 in range(len(sentences)):
for idx2 in range(len(sentences)):
if idx1 == idx2: #ignore if both are same sentences
continue
similarity_matrix[idx1][idx2] = sentence_similarity(sentences[idx1], sentences[idx2], stop_words)
return similarity_matrix
def generate_summary(file_name, top_n=5):
nltk.download('stopwords')
stop_words = stopwords.words('english')
summarize_text = []
# Step 1 - Read text and split it
sentences = read_article(file_name)
# Step 2 - Generate Similarity Matrix across sentences
sentence_similarity_matrix = build_similarity_matrix(sentences, stop_words)
# Step 3 - Rank sentences in similarity matrix
sentence_similarity_graph = nx.from_numpy_array(sentence_similarity_matrix)
scores = nx.pagerank(sentence_similarity_graph)
# Step 4 - Sort the rank and pick top sentences
ranked_sentence = sorted(((scores[i],s) for i,s in enumerate(sentences)), reverse=True)
for i in range(top_n):
summarize_text.append(" ".join(ranked_sentence[i][1]))
return summarize_text
def read_json_file(file_path):
with open(file_path, 'r') as file:
json_content = json.load(file)
return json_content
@app.route('/')
def index():
return render_template('index.html')
@app.route('/render', methods=['POST'])
def render_json_file():
try:
file = request.files['file']
if file and file.filename.endswith('.txt'):
# Save the uploaded .txt file to the server
file_path = 'msft.txt'
file.save(file_path)
# Generate the summary using the updated function
summarized_content = generate_summary(file_path, top_n=2)
# Return the summary as JSON response
return jsonify(summarized_content), 200
else:
return 'Invalid file format. Please upload a .txt file.', 400
except Exception as e:
return str(e), 500
if __name__ == '__main__':
CORS(app)
app.run(debug=True)
I tried looking for errors from flask logs to route handling , file upload handling , CORS , exception handling ,etc.
Everything looks fine but still I’m getting error, there are no errors in the terminal (zero errors in terminal), however when the flask local host link is clicked it is showing Internal server error 500 and when index.html is executed and .txt file is uploaded and summarize button is hit , it is showing summary not fetched .I’m not getting where it went wrong so can anybody help with this.
I would really appreciate the help.
user008 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.